Concept Flow - CSRF protection
Client sends request
Server checks CSRF token
Process
Send response
The server checks if the CSRF token sent by the client matches the expected token before processing the request.
const cookieParser = require('cookie-parser'); const csrf = require('csurf'); const express = require('express'); const app = express(); app.use(cookieParser()); app.use(express.urlencoded({ extended: false })); app.use(csrf({ cookie: true })); app.get('/form', (req, res) => { res.send(`<form method="POST" action="/form"> <input type="hidden" name="_csrf" value="${req.csrfToken()}"> <button type="submit">Submit</button> </form>`); }); app.post('/form', (req, res) => { res.send('Form submitted'); });
| Step | Request Type | CSRF Token Present | Token Valid? | Action | Response |
|---|---|---|---|---|---|
| 1 | GET /form | No (token generated) | N/A | Generate token and send form | Form with CSRF token |
| 2 | POST /form | Yes (token sent) | Yes | Process form data | Form submitted |
| 3 | POST /form | Yes (token sent) | No | Reject request | 403 Forbidden |
| 4 | POST /form | No token | No | Reject request | 403 Forbidden |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|---|
| csrfToken | undefined | generated token string | token string from client | token string from client | undefined |
CSRF protection in Express: - Use csurf middleware to add CSRF tokens - Server generates token on safe requests (GET) - Client sends token with unsafe requests (POST) - Server validates token before processing - Reject requests with missing or invalid tokens - Prevents unauthorized cross-site requests