Gathering detailed insights and metrics for @edge-csrf/nextjs
Gathering detailed insights and metrics for @edge-csrf/nextjs
Gathering detailed insights and metrics for @edge-csrf/nextjs
Gathering detailed insights and metrics for @edge-csrf/nextjs
CSRF protection library for JavaScript that runs on the edge runtime (with Next.js, SvelteKit, Express, Node-HTTP integrations)
npm install @edge-csrf/nextjs
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
150 Stars
74 Commits
9 Forks
2 Watching
4 Branches
2 Contributors
Updated on 26 Nov 2024
TypeScript (98.04%)
JavaScript (1.02%)
Shell (0.94%)
Cumulative downloads
Total Downloads
Last day
6.7%
2,820
Compared to previous day
Last week
4.3%
14,926
Compared to previous week
Last month
40.8%
61,597
Compared to previous month
Last year
0%
261,377
Compared to previous year
Edge-CSRF is a CSRF protection library for JavaScript that runs on the edge runtime.
The Edge-CSRF library helps you to implement the signed double submit cookie pattern except it only uses edge runtime dependencies so it can be used in both node environments and in edge functions (e.g. Vercel Edge Functions, Cloudflare Page Functions). The recommended way to use this library is via its drop-in integrations for Next.js and SvelteKit though it also has a lower-level API for more custom implementations.
We hope you enjoy using this software. Contributions and suggestions are welcome!
X-CSRF-Token
) or from request bodyFirst, install Edge-CSRF's Next.js integration library:
1npm install @edge-csrf/nextjs 2# or 3pnpm add @edge-csrf/nextjs 4# or 5yarn add @edge-csrf/nextjs
Next, create a middleware file (middleware.ts
) for your project and add the Edge-CSRF middleware:
1// middleware.ts 2 3import { createCsrfMiddleware } from '@edge-csrf/nextjs'; 4 5// initalize csrf protection middleware 6const csrfMiddleware = createCsrfMiddleware({ 7 cookie: { 8 secure: process.env.NODE_ENV === 'production', 9 }, 10}); 11 12export const middleware = csrfMiddleware;
Now, all HTTP submission requests (e.g. POST, PUT, DELETE, PATCH) will be rejected if they do not include a valid CSRF token. To add the CSRF token to your forms, you can fetch it from the X-CSRF-Token
HTTP response header server-side or client-side. For example:
1// app/page.tsx 2 3import { headers } from 'next/headers'; 4 5export default async function Page() { 6 // NOTE: headers() don't need to be awaited in Next14 7 const h = await headers(); 8 const csrfToken = h.get('X-CSRF-Token') || 'missing'; 9 10 return ( 11 <form action="/api/form-handler" method="post"> 12 <input type="hidden" name="csrf_token" value={csrfToken}> 13 <input type="text" name="my-input"> 14 <input type="submit"> 15 </form> 16 ); 17}
1// app/form-handler/route.ts 2 3import { NextResponse } from 'next/server'; 4 5export async function POST() { 6 return NextResponse.json({ status: 'success' }); 7}
For more Next.js examples see the package documentation.
First, install Edge-CSRF's SvelteKit integration library:
1npm install @edge-csrf/sveltekit 2# or 3pnpm add @edge-csrf/sveltekit 4# or 5yarn add @edge-csrf/sveltekit
Next, create a server-side hooks file (hooks.server.ts
) for your project and add the Edge-CSRF handle:
1// src/hooks.server.ts 2 3import { createCsrfHandle } from '@edge-csrf/sveltekit'; 4 5// initalize csrf protection handle 6const csrfHandle = createCsrfHandle({ 7 cookie: { 8 secure: process.env.NODE_ENV === 'production', 9 }, 10}); 11 12export const handle = csrfHandle;
Now, all HTTP submission requests (e.g. POST, PUT, DELETE, PATCH) will be rejected if they do not include a valid CSRF token. To add the CSRF token to your forms, you can fetch it from the event's locals
data object server-side. For example:
1// src/routes/+page.server.ts 2 3export async function load({ locals }) { 4 return { 5 csrfToken: locals.csrfToken, 6 }; 7} 8 9export const actions = { 10 default: async () => { 11 return { success: true }; 12 }, 13};
1<!-- src/routes/+page.svelte --> 2 3<script lang="ts"> 4 export let data; 5 6 export let form; 7</script> 8 9{#if form?.success} 10<span>success</span> 11{:else} 12<form method="post"> 13 <input type="hidden" name="csrf_token" value={data.csrfToken}> 14 <input type="text" name="my-input"> 15 <input type="submit"> 16</form> 17{/if}
Finally, to make typescript aware of the new locals
attributes you can add Edge-CSRF types to your app's types:
1// src/app.d.ts 2 3import type { CsrfLocals } from '@edge-csrf/sveltekit'; 4 5declare global { 6 namespace App { 7 // ... 8 interface Locals extends CsrfLocals {} 9 // ... 10 } 11} 12 13export {};
First, install Edge-CSRF's Express integration library:
1npm install @edge-csrf/express 2# or 3pnpm add @edge-csrf/express 4# or 5yarn add @edge-csrf/express
Next, add the Edge-CSRF middleware to your app:
1// app.js 2 3import { createCsrfMiddleware } from '@edge-csrf/express'; 4import express from 'express'; 5 6// initalize csrf protection middleware 7const csrfMiddleware = createCsrfMiddleware({ 8 cookie: { 9 secure: process.env.NODE_ENV === 'production', 10 }, 11}); 12 13// init app 14const app = express(); 15const port = 3000; 16 17// add csrf middleware 18app.use(csrfMiddleware); 19 20// define handlers 21app.get('/', (req, res) => { 22 const csrfToken = res.getHeader('X-CSRF-Token') || 'missing'; 23 res.send(` 24 <!doctype html> 25 <html> 26 <body> 27 <p>CSRF token value: ${csrfToken}</p> 28 <form action="/" method="post"> 29 <legend>Form with CSRF (should succeed):</legend> 30 <input type="hidden" name="csrf_token" value="${csrfToken}" /> 31 <input type="text" name="input1" /> 32 <button type="submit">Submit</button> 33 </form> 34 </body> 35 </html> 36 `); 37}); 38 39app.post('/', (req, res) => { 40 res.send('success'); 41}); 42 43// start server 44app.listen(port, () => { 45 console.log(`Example app listening on port ${port}`) 46});
With the middleware installed, all HTTP submission requests (e.g. POST, PUT, DELETE, PATCH) will be rejected if they do not include a valid CSRF token.
First, install Edge-CSRF's Node-HTTP integration library:
1npm install @edge-csrf/node-http 2# or 3pnpm add @edge-csrf/node-http 4# or 5yarn add @edge-csrf/node-http
Next, add the Edge-CSRF CSRF protection function to your request handlers:
1// server.js 2 3import { createServer } from 'http'; 4 5import { createCsrfProtect } from '@edge-csrf/node-http'; 6 7// initalize csrf protection middleware 8const csrfProtect = createCsrfProtect({ 9 cookie: { 10 secure: process.env.NODE_ENV === 'production', 11 }, 12}); 13 14// init server 15const server = createServer(async (req, res) => { 16 // apply csrf protection 17 try { 18 await csrfProtect(req, res); 19 } catch (err) { 20 if (err instanceof CsrfError) { 21 res.writeHead(403); 22 res.end('invalid csrf token'); 23 return; 24 } 25 throw err; 26 } 27 28 // add handler 29 if (req.url === '/') { 30 if (req.method === 'GET') { 31 const csrfToken = res.getHeader('X-CSRF-Token') || 'missing'; 32 res.writeHead(200, { 'Content-Type': 'text/html' }); 33 res.end(` 34 <!doctype html> 35 <html> 36 <body> 37 <form action="/" method="post"> 38 <legend>Form with CSRF (should succeed):</legend> 39 <input type="hidden" name="csrf_token" value="${csrfToken}" /> 40 <input type="text" name="input1" /> 41 <button type="submit">Submit</button> 42 </form> 43 </body> 44 </html> 45 `); 46 return; 47 } 48 49 if (req.method === 'POST') { 50 res.writeHead(200, { 'Content-Type': 'text/plain' }); 51 res.end('success'); 52 return; 53 } 54 } 55 56 res.writeHead(404); 57 res.end('not found'); 58}); 59 60// start server 61server.listen(3000, () => { 62 console.log('Server is listening on port 3000'); 63});
With the CSRF protection method, all HTTP submission requests (e.g. POST, PUT, DELETE, PATCH) will be rejected if they do not include a valid CSRF token.
To develop edge-csrf, first clone the repository then install the dependencies:
1git clone git@github.com:kubetail-org/edge-csrf.git 2cd edge-csrf 3pnpm install
Edge-CSRF uses jest for testing (via vitest). To run the tests in node, edge and miniflare environments, use the test-all
command:
1pnpm test-all
The test files are colocated with the source code in each package's src/
directory, with the filename format {name}.test.ts
.
To build Edge-CSRF for production, run the build
command:
1pnpm build
The build artifacts will be located in the dist/
directory of each package.
No vulnerabilities found.
No security vulnerabilities found.