csrf-csrf is a utility package designed to provide stateless Cross-Site Request Forgery (CSRF) protection for Express applications, implementing the Double Submit Cookie Pattern. Currently at version 4.0.3, it offers a robust alternative to the deprecated `csurf` library, aiming for a simpler and more explicit configuration. Unlike session-based CSRF protection mechanisms like `csrf-sync` (which uses the Synchronizer Token Pattern), `csrf-csrf` is suited for stateless architectures, making it a distinct choice for specific application designs. The library ships with comprehensive TypeScript types (requiring TypeScript >= 3.8) and emphasizes clear implementation guidance to prevent common misconfigurations that can render CSRF protection ineffective. Development is active, with a recent major version release bringing breaking changes and improvements, and it explicitly recommends consulting upgrade guides for migration.
npm install csrf-csrfVerified import paths — ran on the pinned version, not inferred.
Demonstrates a basic Express server configuring `csrf-csrf` with `cookie-parser`, exposing a route to fetch a CSRF token, and protecting a POST endpoint. It highlights proper middleware ordering and token retrieval.
Refer to the official upgrade guide (`UPGRADING.md`) and `CHANGELOG.md` for specific changes and adapt your code accordingly.
Ensure `app.use(cookieParser(...))` is called before `app.use(doubleCsrfProtection)`. If using `express-session`, `cookie-parser` should be after `express-session` as well.
Implement `getTokenFromRequest` with clear, explicit checks, prioritizing trusted locations like a specific header or body field. For example, `if (req.headers['x-csrf-token']) { return req.headers['x-csrf-token']; } else if (req.body._csrf) { return req.body._csrf; } return '';`Assess your application's state management. If using sessions, consider `csrf-sync`. If strictly stateless, `csrf-csrf` is appropriate, but understand the pattern's implications.
Store secrets in environment variables (e.g., `process.env.CSRF_SECRET`) and ensure they are sufficiently long and random.
Ensure the frontend sends the CSRF token (obtained from `/csrf-token` endpoint) in the correct header (`x-csrf-token`) or body field (`_csrf`) as configured by `getTokenFromRequest`.
Add `import cookieParser from 'cookie-parser';` (ESM) or `const cookieParser = require('cookie-parser');` (CJS, for versions <4) and `app.use(cookieParser(...))` before `app.use(doubleCsrfProtection)`.Provide a string secret to the `doubleCsrf` configuration object: `doubleCsrf({ secret: 'your-strong-secret', ... })`.Switch to ES Module syntax: `import { doubleCsrf } from 'csrf-csrf';`. Ensure your `package.json` specifies `"type": "module"` for your project, or rename files to `.mjs`.