Gathering detailed insights and metrics for csrf-edge
Gathering detailed insights and metrics for csrf-edge
Gathering detailed insights and metrics for csrf-edge
Gathering detailed insights and metrics for csrf-edge
CSRF protection library for JavaScript that runs on the edge runtime (with Next.js, SvelteKit, Express, Node-HTTP integrations)
npm install csrf-edge
Typescript
Module System
Node Version
NPM Version
TypeScript (98.04%)
JavaScript (1.02%)
Shell (0.94%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
173 Stars
77 Commits
14 Forks
3 Watchers
4 Branches
4 Contributors
Updated on Jun 04, 2025
Latest Version
0.1.4
Package Id
csrf-edge@0.1.4
Unpacked Size
9.25 kB
Size
3.42 kB
File Count
5
NPM Version
8.5.5
Node Version
16.15.0
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
[!CAUTION] This library implements the Naive Double-Submit Cookie Pattern which is vulnerable to sub-domain attacks (when an attacker is able to set cookies for the the parent domain or other sub-domains). In order to prevent sub-domain attacks, the CSRF token must be tied to the user session which means it requires a tight integration with the session/authentication library. If your site isn't vulnerable to sub-domain attacks then you can continue to use this library but if it is, then you should consider a CSRF solution that is integrated with your auth system.
Longer term, the next step for this library is to provide plugins for authentication libraries and/or to encourge authentication plugin providers to use the library primitives in
packages/core
. Unfortunately I have my hands full at the moment with another project (https://github.com/kubetail-org/kubetail) so I would like to hand this project off to another maintainer. If you're interested please let me know!
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.