csurf
csurf is an Express middleware for CSRF (Cross-Site Request Forgery) protection that generates and validates tokens to prevent malicious websites from submittin…
Installation
npm install csurf
yarn add csurf
pnpm add csurf
Import
import csurf from 'csurf';
Quick Example
import express from 'express';
import csurf from 'csurf';
const app = express();
app.use(csurf({ cookie: true }));
app.get('/form', (req, res) => {
res.render('form', { csrfToken: req.csrfToken() });
});About csurf
csurf is an Express middleware for CSRF (Cross-Site Request Forgery) protection that generates and validates tokens to prevent malicious websites from submitting unauthorized requests on behalf of authenticated users. CSRF attacks exploit the fact that browsers automatically include cookies with requests to a domain, allowing a malicious page to submit a form or API request that the server cannot distinguish from a legitimate request. csurf generates a unique token for each session or request that must be included in form submissions or API requests — since the attacker's page cannot read this token, forged requests will be rejected. The middleware supports both cookie-based and session-based token storage, with the token accessible through req.csrfToken() for embedding in forms or headers. csurf validates the token from request body (_csrf field), query string, or headers (CSRF-Token, XSRF-TOKEN, X-CSRF-Token, X-XSRF-Token). While csurf has been deprecated with a recommendation to use alternative CSRF protection approaches (especially for SPAs using bearer tokens), it remains widely used in traditional server-rendered Express applications with form-based interactions where cookie-based session authentication is used.
Quick Facts
| Package | csurf |
| Category | Auth |
| Weekly Downloads | 200K+ |
| License | MIT |
| Install | npm install csurf |
Related Packages
Express is the most widely used web application framework for Node.js, providing a minimal and flexi…
Helmet helps secure Express.js applications by setting various HTTP response headers that protect ag…
CORS (Cross-Origin Resource Sharing) is an Express/Connect middleware that enables cross-origin requ…
express-session is a session middleware for Express that creates server-side sessions identified by …
Browse npm Packages by Category
Explore our reference of 200 popular npm packages with install commands, examples, and quick-start guides.