const express = require('express'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const csrf = require('csurf'); const app = express(); // Middleware setup app.use(cookieParser()); app.use(session({ secret: 'a_very_secret_key_for_session_signing', // Should be a strong, random string resave: false, saveUninitialized: true, cookie: { httpOnly: true, // Prevent client-side JS access secure: process.env.NODE_ENV === 'production', // Only send over HTTPS in production sameSite: 'Lax' // Protect against some CSRF attacks } })); // CSRF middleware. Requires session middleware to be present. // 'cookie: true' option means the CSRF token will be set in a cookie, // and can be accessed from req.csrfToken() const csrfProtection = csrf({ cookie: true }); // Enable JSON body parsing for POST requests app.use(express.json()); // Enable URL-encoded body parsing for form submissions app.use(express.urlencoded({ extended: false })); // Example routes app.get('/', csrfProtection, (req, res) => { // Pass the CSRF token to the client to be included in forms res.send(`
Your CSRF token is: ${req.csrfToken()}
Open developer console -> Application -> Cookies to see 'XSRF-TOKEN'
Test with a POST request to /process with an incorrect or missing CSRF token.
`); }); app.post('/process', csrfProtection, (req, res) => { // If CSRF token validation passes, process the request res.send(`Data received: ${req.body.data || 'No data'}. CSRF token verified successfully.`); }); // Error handling for CSRF issues app.use((err, req, res, next) => { if (err.code === 'EBADCSRFTOKEN') { res.status(403).send('Invalid CSRF token.'); } else { next(err); } }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); console.log('Ensure you have "express-session", "cookie-parser", and "csurf" installed.'); });