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-syncVerified import paths — ran on the pinned version, not inferred.
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.
Ensure `express-session` and `@types/express-session` are installed: `npm install express-session @types/express-session`.
Update import statements to use named exports for CommonJS or `import { csrfSync } from 'csrf-sync';` for ESM.Always ensure `express-session` or a compatible session middleware is initialized and used prior to `csrfSynchronisedProtection` middleware.
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.
Evaluate your application's architecture; choose `csrf-sync` for stateful web applications and consider alternatives for stateless APIs.
Ensure `app.use(session(...))` is called *before* `app.use(csrfSynchronisedProtection)` in your Express application setup.
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.
For ESM, use `import { csrfSync } from 'csrf-sync';`. For CommonJS, use `const { csrfSync } = require('csrf-sync');`.