Initialize doubleCsrf with the required getSecret and getSessionIdentifier functions. This provides utilities to protect routes and generate tokens.
Important Middleware Order:
express-session (if using sessions)cookie-parserdoubleCsrf utilities/middleware
Note: If using express-session, register cookie-parser after the session middleware to avoid conflicts.
import { doubleCsrf } from "csrf-csrf";
const {
doubleCsrfProtection,
generateCsrfToken
} = doubleCsrf({
getSecret: (req) => 'return some cryptographically pseudorandom secret here',
getSessionIdentifier: (req) => req.session.id
});
// Use doubleCsrfProtection as middleware to protect routes
app.use(doubleCsrfProtection);
// Use generateCsrfToken in a route to provide a token to the client
app.get('/token', (req, res) => {
const token = generateCsrfToken(req, res);
res.json({ csrfToken: token });
});