Registry / auth-security / csrf-sync

csrf-sync

JSON →
library4.2.1jsnpmunverified

CSRF Sync is a utility package designed to provide robust stateful Cross-Site Request Forgery (CSRF) protection for Express applications, utilizing the Synchroniser Token Pattern. Developed in response to the deprecation of `csurf` and the perceived complexity or limited scope of alternative solutions, `csrf-sync` (current stable version 4.2.1) aims for a targeted and simplified implementation. It requires a server-side session management middleware like `express-session` to store tokens. The library focuses on providing the essential components for CSRF protection without imposing a full solution, allowing developers to integrate it flexibly. It is actively maintained with regular updates and follows a clear versioning strategy, with significant changes typically highlighted in major version bumps.

npm install csrf-sync
INSTALL
IMPORT
SIG · CSRF-SYNC
C
csrf-sync
auth-securityjavascriptv4.2.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

csrfSync
✓ import { csrfSync } from 'csrf-sync';
✗ const csrfSync = require('csrf-sync');
Since v3, `csrfSync` is a named export. It's the factory function that returns an object of utilities, and should be imported as such for both ESM and CommonJS.
csrfSynchronisedProtection
✓ const { csrfSynchronisedProtection } = csrfSync();
✗ import { csrfSynchronisedProtection } from 'csrf-sync';
This is a middleware function returned by calling the `csrfSync()` factory function, not a direct named export from the package root. It must be destructured from the `csrfSync()` return value.
generateToken
✓ const { generateToken } = csrfSync();
✗ import { generateToken } from 'csrf-sync';
This utility function, used to create and store CSRF tokens in the session and retrieve them for client-side inclusion, is destructured from the object returned by `csrfSync()`.

This quickstart demonstrates setting up an Express application with `express-session` and `csrf-sync` to protect a form submission route. It shows how to initialize the CSRF protection, generate a token, include it in an HTML form, and handle POST requests with CSRF validation, including basic error handling for invalid tokens.

import express from 'express'; import session from 'express-session'; import { csrfSync } from 'csrf-sync'; const app = express(); const port = 3000; // Configure express-session middleware app.use(session({ secret: process.env.SESSION_SECRET ?? 'super-secret-key-please-change-me', resave: false, saveUninitialized: true, cookie: { httpOnly: true, secure: process.env.NODE_ENV === 'production' } })); // Initialize csrf-sync and get the protection middleware and token generator const { csrfSynchronisedProtection, generateToken } = csrfSync(); // Apply CSRF protection to all routes (or specific ones) app.use(csrfSynchronisedProtection); // Middleware to parse URL-encoded bodies for form submissions app.use(express.urlencoded({ extended: false })); // Route to display a form with a CSRF token app.get('/', (req, res) => { const token = generateToken(req); res.send(` <!DOCTYPE html> <html> <head><title>CSRF Test</title></head> <body> <h1>Submit Form</h1> <form action="/submit" method="POST"> <input type="hidden" name="_csrf" value="${token}"> <input type="text" name="data" placeholder="Enter data"> <button type="submit">Submit</button> </form> </body> </html> `); }); // Protected route to handle form submission app.post('/submit', (req, res) => { res.send(`Data received: ${req.body.data} (CSRF protected)`); }); // Error handling for CSRF issues (optional but recommended) app.use((err, req, res, next) => { if (err.code === 'EBADCSRFTOKEN') { res.status(403).send('Invalid CSRF token - potential attack!'); } else { next(err); } }); app.listen(port, () => { console.log(`Server listening at http://localhost:${port}`); if (!process.env.SESSION_SECRET) { console.warn('WARNING: SESSION_SECRET is not set. Using a default, which is insecure for production.'); } });
Debug
Known issues
breakingStarting with v4.0.0, `csrf-sync` no longer bundles TypeScript types for `express-session`. Users must explicitly install `express-session` and its types (`@types/express-session`) for TypeScript projects.
fix
Ensure `express-session` and `@types/express-session` are installed: `npm install express-session @types/express-session`.
affects: >=4.0.0
breakingVersion 3.0.0 transitioned `csrf-sync` to an ESM-first package. This changed the CommonJS import pattern from attempting a default import to a named import `const { csrfSync } = require('csrf-sync');`.
fix
Update import statements to use named exports for CommonJS or `import { csrfSync } from 'csrf-sync';` for ESM.
affects: >=3.0.0
gotcha`csrf-sync` fundamentally relies on a stateful session middleware (e.g., `express-session`) that populates `req.session`. Without this middleware correctly configured and placed before `csrfSynchronisedProtection`, the library will fail to store and validate tokens.
fix
Always ensure `express-session` or a compatible session middleware is initialized and used prior to `csrfSynchronisedProtection` middleware.
affects: >=1.0.0
gotchaImproper configuration of the underlying session middleware (e.g., weak session secret, insecure cookie flags) can compromise the effectiveness of CSRF protection provided by `csrf-sync`. The library itself cannot mitigate underlying session vulnerabilities.
fix
Follow OWASP guidelines for secure session management. Use a strong, securely stored `session.secret`, set `httpOnly` and `secure` flags appropriately for cookies, and avoid common session hijacking vectors.
affects: >=1.0.0
gotcha`csrf-sync` implements the Synchronizer Token Pattern, which requires server-side state. It is not suitable for purely stateless APIs. For stateless scenarios, consider the Double-Submit Cookie Pattern (e.g., using `csrf-csrf`).
fix
Evaluate your application's architecture; choose `csrf-sync` for stateful web applications and consider alternatives for stateless APIs.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'session')
The `express-session` middleware (or equivalent) has not been configured or is not placed correctly before the `csrf-sync` middleware.
fix
Ensure `app.use(session(...))` is called *before* `app.use(csrfSynchronisedProtection)` in your Express application setup.
Error: Invalid CSRF Token
The CSRF token submitted in the request (e.g., via `_csrf` form field or header) does not match the token stored in the user's session, or no token was provided.
fix
Verify that the client-side code correctly retrieves the token using `generateToken(req)` and includes it in all state-changing requests (e.g., POST, PUT, DELETE). On the server, ensure `csrfSynchronisedProtection` is applied to the routes that require protection.
TypeError: csrfSync is not a function
Incorrect import statement for `csrfSync`. This often happens when treating it as a default export or using an outdated CommonJS pattern after v3.
fix
For ESM, use `import { csrfSync } from 'csrf-sync';`. For CommonJS, use `const { csrfSync } = require('csrf-sync');`.
Upgrade
Version history
4.2.1latest on npm
Audit
Dependencies
express-sessionrequiredRequired for stateful session management to store CSRF tokens in `req.session`.
Agent activity
19 hits · last 30 days
node
16
OpenAI (training)
1
Resources
csrf-sync — npm install csrf-sync · libregistry