Security and hardening · Intermediate · 25 min
Protect forms from cross-site request forgery with SameSite cookies and tokens
By Padding · Updated 18 Nov 2026
node:26 image (Debian) · Node.js 26.13.1 · Express 5.3.0 · csrf-csrf 4.1.0 · Playwright 1.65.1
You will prove in a real browser that a page on another origin can delete a Noticeboard post, then close the hole in four layers (SameSite=Lax, no state changes on GET, a Sec-Fetch-Site and Origin check, and csrf-csrf form tokens) with a test that passes one more case after each layer.
On this page
Cross-site request forgery (CSRF) is a borrowed signature. Your browser attaches the session cookie to every request it sends to Noticeboard, whichever page started that request. So a page on any other site can hold a form that posts to /posts/1/delete, and if you are signed in when you press its button, Noticeboard sees a valid session and deletes the post. The attacker never sees your cookie. They only need you to visit their page. The OWASP Top 10:2025 lists CSRF under A01 Broken Access Control.
Part 1 flagged the two delete routes in app.js with one FLAW (A01 CSRF, part 4) comment: app.post('/posts/:id/delete', ...) accepts a form from any site, and app.get('/posts/:id/delete', ...) deletes on a plain link. In this part you prove both flaws in a real browser, using a "prize draw" page you serve yourself on a second local origin. Then you add four layers, and each one makes one more test pass:
- A
SameSite=Laxsession cookie, and the gaps Lax leaves. - No state changes on
GET. - A check on the
Sec-Fetch-SiteandOriginheaders, which refuses unsafe requests from other sites. - Form tokens from csrf-csrf 4.1, for browsers and clients that send neither header.
Last, you see why a JSON API that authenticates with a bearer token and sends no cookies needs none of this.
Practise only on your own copy of Noticeboard on your own machine. The prize page targets localhost and nothing else. Never aim a forged form at a site you do not own.
Step 1 · Create a working copy for this part
This part works in its own folder, ~/noticeboard-demo/part4, so the app you built and fixed in parts 1 to 3 stays exactly as it is. The copy keeps part 1's layout and names (app.js, db.js, server.js, the users amara, bola and chen, the sid cookie, the test/security folder), trimmed to sign-in, a list of posts and deleting a post. The last step shows how to carry the fixes back into your own copy.
Create the folder and package.json. test:security runs one test file at a time, because each file starts a browser:
mkdir -p ~/noticeboard-demo/part4/test/security
cd ~/noticeboard-demo/part4
cat > package.json <<'JSON'
{
"name": "noticeboard-part4",
"version": "1.0.0",
"private": true,
"type": "module",
"engines": { "node": ">=26" },
"scripts": {
"start": "node --env-file=.env server.js",
"lure": "node lure.js",
"test:security": "node --test --test-concurrency=1 \"test/security/*.test.js\""
}
}
JSON
cat > .gitignore <<'TXT'
node_modules/
.env
TXT
npm install express@5.3.0 --save-exact
npm install playwright@1.65.1 --save-dev --save-exact
npx playwright install --with-deps chromiumPlaywright drives a real Chromium in the tests. CSRF depends on what a browser decides to send, which cookies and which headers, so a plain HTTP client cannot prove these fixes. --with-deps installs the system libraries Chromium needs and asks for your sudo password on Linux; on macOS it only downloads the browser. The download is large. If you pay for mobile data by the bundle, run this step on Wi-Fi.
Now the secrets. Write them to .env with a umask 077 subshell, so the file is private from the moment it exists:
(umask 077 && node -e "
const r = (n) => require('node:crypto').randomBytes(n).toString('hex')
console.log('SEED_PASSWORD=' + r(12) + '\nCSRF_SECRET=' + r(32) + '\nAPI_TOKEN=' + r(32))
" > .env)SEED_PASSWORD is the demo users' password, as in part 1. CSRF_SECRET signs the form tokens in step 7, and API_TOKEN is the bearer token for the JSON API in step 8. None of them appear in the code.
Check it worked
npm ls --depth=0
ls -l .envnpm ls lists express@5.3.0 and playwright@1.65.1, and ls -l shows .env with permissions -rw-------.
Step 2 · Write the trimmed Noticeboard
The database holds three users and three posts. amara owns the first two. As in part 1, passwords are stored as plain text; hashing passwords with Argon2id covers that fix:
cat > db.js <<'JS'
import { DatabaseSync } from 'node:sqlite'
export function openDb(file, seedPassword) {
const db = new DatabaseSync(file)
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY, name TEXT UNIQUE NOT NULL, password TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY, owner_id INTEGER NOT NULL REFERENCES users(id), title TEXT NOT NULL);
`)
if (!db.prepare('SELECT 1 FROM users').get()) {
if (!seedPassword) throw new Error('Set SEED_PASSWORD to create the demo users')
const addUser = db.prepare('INSERT INTO users (name, password) VALUES (?, ?)')
for (const name of ['amara', 'bola', 'chen']) addUser.run(name, seedPassword)
const addPost = db.prepare('INSERT INTO posts (owner_id, title) VALUES (?, ?)')
addPost.run(1, 'Welcome to Noticeboard')
addPost.run(1, 'Bake sale on Friday')
addPost.run(2, 'Fire drill at 10:00')
}
return db
}
JSThree small files hold everything this part changes. session.js holds the session cookie's attributes and part 1's cookie parser. csrf.js will hold the defences. For now it does nothing, in the same way errors.js started out in part 1. views.js is the page layout, with the escaping helper from part 3:
cat > session.js <<'JS'
// FLAW (A01 CSRF, part 4): SameSite=None sends the cookie with requests from any site.
export const sessionCookie = { httpOnly: true, secure: true, sameSite: 'none', path: '/' }
export function parseCookies(header = '') {
const cookies = {}
for (const pair of header.split(';')) {
const i = pair.indexOf('=')
if (i > 0) cookies[pair.slice(0, i).trim()] = decodeURIComponent(pair.slice(i + 1).trim())
}
return cookies
}
JS
cat > csrf.js <<'JS'
// FLAW (A01 CSRF, part 4): no check on where a write came from, and no form token.
export function csrfProtection() {
return (req, res, next) => next()
}
// Returns the hidden form field that carries the token. Empty for now.
export function tokenField(req, res) {
return ''
}
JS
cat > views.js <<'JS'
const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }
export const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (ch) => ESCAPES[ch])
export function page(title, user, body) {
const who = user ? `Signed in as ${escapeHtml(user.name)}` : '<a href="/signin">Sign in</a>'
return `<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(title)} - Noticeboard</title></head>
<body><header><a href="/">Noticeboard</a> ${who}</header>
<main>${body}</main></body>
</html>`
}
JSThe posts routes go in posts.js. Deleting already checks ownership in the query (part 2's lesson), so bola cannot delete amara's post. The problem in this part is different: Noticeboard cannot tell whether amara meant to press the button.
cat > posts.js <<'JS'
import { Router } from 'express'
import { page, escapeHtml } from './views.js'
import { tokenField } from './csrf.js'
export function postsRouter(db) {
const router = Router()
const signedIn = (req, res, next) =>
req.user ? next() : res.status(401).send(page('Sign in', undefined, '<p>Sign in first.</p>'))
router.get('/', (req, res) => {
const posts = db.prepare('SELECT id, owner_id, title FROM posts ORDER BY id').all()
const field = req.user ? tokenField(req, res) : ''
const items = posts.map((p) => {
const del = req.user?.id === p.owner_id
? ` <form method="post" action="/posts/${p.id}/delete">${field}<button>Delete</button></form>`
: ''
return `<li>${escapeHtml(p.title)}${del}</li>`
})
res.send(page('Notices', req.user, `<h1>Notices</h1><ul>${items.join('')}</ul>`))
})
const deletePost = (req, res) => {
const { changes } = db
.prepare('DELETE FROM posts WHERE id = ? AND owner_id = ?')
.run(Number(req.params.id), req.user.id)
if (changes === 0) return res.status(404).send(page('Not found', req.user, '<p>No such post.</p>'))
res.redirect(303, '/')
}
router.post('/posts/:id/delete', signedIn, deletePost)
// FLAW (A01 CSRF, part 4): a plain link can delete a post, from any page.
router.get('/posts/:id/delete', signedIn, deletePost)
return router
}
JSThe JSON API is for scripts and a future mobile app. It reads a bearer token from the Authorization header and never looks at a cookie. You come back to it in step 8:
cat > api.js <<'JS'
import { Router } from 'express'
import { createHash, timingSafeEqual } from 'node:crypto'
const digest = (value) => createHash('sha256').update(value).digest()
export function apiRouter(db) {
const router = Router()
router.use((req, res, next) => {
const expected = process.env.API_TOKEN
if (!expected) return res.status(503).json({ error: 'API_TOKEN is not set' })
const given = /^Bearer (.+)$/.exec(req.get('authorization') ?? '')?.[1] ?? ''
if (!timingSafeEqual(digest(given), digest(expected))) {
return res.status(401).json({ error: 'Missing or wrong token' })
}
req.apiUserId = 1 // in this demo the token belongs to amara
next()
})
router.delete('/posts/:id', (req, res) => {
const { changes } = db
.prepare('DELETE FROM posts WHERE id = ? AND owner_id = ?')
.run(Number(req.params.id), req.apiUserId)
res.status(changes ? 204 : 404).end()
})
return router
}
JSapp.js wires it together. The order is the point. The API is mounted first, before anything that reads cookies. Then the body parser, then the cookie and user lookup, then csrfProtection(), and only then the routes. The error handler already knows the error csrf-csrf raises, so step 7 does not need to touch this file:
cat > app.js <<'JS'
import express from 'express'
import { randomBytes } from 'node:crypto'
import { sessionCookie, parseCookies } from './session.js'
import { csrfProtection, tokenField } from './csrf.js'
import { apiRouter } from './api.js'
import { postsRouter } from './posts.js'
import { page } from './views.js'
export function createApp({ db }) {
const app = express()
const sessions = new Map() // session ID -> user ID, kept in memory
// Bearer-token API: mounted before any middleware that reads cookies.
app.use('/api', express.json({ limit: '10kb' }), apiRouter(db))
app.use(express.urlencoded({ extended: false, limit: '10kb' }))
app.use((req, res, next) => {
req.cookies = parseCookies(req.get('cookie'))
const userId = sessions.get(req.cookies.sid)
req.user = userId ? db.prepare('SELECT id, name FROM users WHERE id = ?').get(userId) : undefined
next()
})
app.use(csrfProtection())
app.get('/signin', (req, res) => {
res.send(page('Sign in', req.user, `<form method="post" action="/signin">${tokenField(req, res)}
<label>Name <input name="name" autocomplete="username"></label>
<label>Password <input name="password" type="password" autocomplete="current-password"></label>
<button>Sign in</button></form>`))
})
app.post('/signin', (req, res) => {
const { name = '', password = '' } = req.body ?? {}
const user = db
.prepare('SELECT id FROM users WHERE name = ? AND password = ?')
.get(String(name), String(password))
if (!user) return res.status(401).send(page('Sign in', undefined, '<p>Wrong name or password.</p>'))
const sid = randomBytes(32).toString('base64url')
sessions.set(sid, user.id)
res.cookie('sid', sid, sessionCookie)
res.redirect(303, '/')
})
app.use(postsRouter(db))
app.use((err, req, res, next) => {
if (err.code === 'EBADCSRFTOKEN') {
return res.status(403).send(page('Form expired', req.user,
'<p>This form has expired. Go back, reload the page and try again.</p>'))
}
console.error(err)
res.status(500).type('text/plain').send('Something went wrong.')
})
return app
}
JS
cat > server.js <<'JS'
import { createApp } from './app.js'
import { openDb } from './db.js'
// Loopback only, as in part 1. Data lives in memory, so a restart brings deleted posts back.
const HOST = '127.0.0.1'
const PORT = Number(process.env.PORT ?? 3000)
const app = createApp({ db: openDb(':memory:', process.env.SEED_PASSWORD) })
const server = app.listen(PORT, HOST, (err) => {
if (err) throw err
console.log(`Noticeboard (part 4) on http://localhost:${server.address().port}`)
})
JSThe server listens on 127.0.0.1, and you open it as http://localhost:3000. Both names point at your own machine, but browsers treat them as two different sites. The next step relies on that difference.
Check it worked
node --input-type=module -e "import('./app.js').then((m) => console.log(typeof m.createApp))"The command prints function. A SyntaxError means a heredoc was cut short; run that block again.
Step 3 · Prove the forged delete from a second origin
The attack needs a page you control on another origin. lure-page.js builds it: a prize-draw page with a form that posts to /posts/1/delete on Noticeboard, and a link to the GET version of the same route. lure.js serves it on port 4100:
cat > lure-page.js <<'JS'
// Stands in for a page an attacker runs. It only ever targets your own Noticeboard.
export function lurePage(target) {
return `<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>Prize draw</title></head>
<body>
<h1>You have won a prize</h1>
<form id="claim" method="post" action="${target}/posts/1/delete"><button>Claim your prize</button></form>
<p><a id="link" href="${target}/posts/1/delete">Or claim it with this link</a></p>
</body></html>`
}
JS
cat > lure.js <<'JS'
import { createServer } from 'node:http'
import { lurePage } from './lure-page.js'
const target = 'http://localhost:3000'
createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
res.end(lurePage(target))
}).listen(4100, '127.0.0.1', () => {
console.log('Lure on http://127.0.0.1:4100 (another site) and http://localhost:4100 (same site)')
})
JSOne server gives you two kinds of attacker, depending on the address you open it with:
http://127.0.0.1:4100is cross-site. A site is the scheme plus the registrable domain, or the host itself when there is none, as withlocalhostand IP addresses.127.0.0.1andlocalhostare different hosts, so to the browser this is someone else's site.http://localhost:4100is same-site but cross-origin. Ports count for the origin but not for the site. This one stands for a sibling you share a site with: another app on a subdomain of your company's domain, a user-content host, or a forgotten marketing page onpromo.example.com.
See it in a browser (optional)
In a second terminal, start Noticeboard. In a third, start the lure:
cd ~/noticeboard-demo/part4
npm startcd ~/noticeboard-demo/part4
npm run lureCheck both from your first terminal:
curl -s http://127.0.0.1:3000/ | grep -o "Welcome to Noticeboard"
curl -s http://127.0.0.1:4100/ | grep -o "Claim your prize"Open http://localhost:3000/signin in Chrome and sign in as amara with the SEED_PASSWORD from .env (run cat .env). In a new tab, open http://127.0.0.1:4100 and press Claim your prize. The tab lands on Noticeboard, and "Welcome to Noticeboard" has gone from the list. You pressed a button on another site, and your own session deleted your post. Stop both servers with Ctrl+C when you have seen it. The data is in memory, so the post comes back the next time you start the app.
Write the tests
Now make the proof repeatable. test/helpers.js starts a fresh app and a lure on random free ports, signs in through the real form in Chromium, and can send a raw request with only a cookie, the way an old browser or a script would. It sets test-only secrets, so the tests never read your .env:
cat > test/helpers.js <<'JS'
import { createServer, request } from 'node:http'
import { randomBytes } from 'node:crypto'
import { createApp } from '../app.js'
import { openDb } from '../db.js'
import { lurePage } from '../lure-page.js'
process.env.CSRF_SECRET ??= randomBytes(32).toString('hex')
process.env.API_TOKEN ??= randomBytes(32).toString('hex')
function listen(server) {
return new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(0, '127.0.0.1', () => resolve(server.address().port))
})
}
async function stop(server) {
server.closeAllConnections()
await new Promise((resolve) => server.close(resolve))
}
export async function startApp() {
const password = randomBytes(12).toString('hex')
const db = openDb(':memory:', password)
const server = createServer(createApp({ db }))
const port = await listen(server)
return {
password,
base: `http://127.0.0.1:${port}`, // for raw requests from Node
site: `http://localhost:${port}`, // what the browser opens
postExists: (id) => db.prepare('SELECT 1 FROM posts WHERE id = ?').get(id) !== undefined,
async close() {
await stop(server)
db.close()
},
}
}
export async function startLure(target) {
const server = createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
res.end(lurePage(target))
})
const port = await listen(server)
return {
crossSite: `http://127.0.0.1:${port}`,
sameSite: `http://localhost:${port}`,
close: () => stop(server),
}
}
// Signs in through the real form, as a person would.
export async function signIn(page, app, name = 'amara') {
await page.goto(`${app.site}/signin`)
await page.fill('input[name=name]', name)
await page.fill('input[name=password]', app.password)
await Promise.all([page.waitForURL(`${app.site}/`), page.click('button')])
}
// Clicks, then waits until the browser has had an answer from url.
export async function clickAndWait(page, selector, url) {
const [response] = await Promise.all([
page.waitForResponse((r) => r.url() === url),
page.click(selector),
])
return response.status()
}
export async function sessionCookie(page) {
const sid = (await page.context().cookies()).find((c) => c.name === 'sid')
return `sid=${sid.value}`
}
// A request with a cookie and nothing else: no Origin, no Sec-Fetch-Site, no token.
export function rawRequest(app, method, path, headers = {}) {
return new Promise((resolve, reject) => {
const req = request(`${app.base}${path}`, { method, headers }, (res) => {
res.resume()
resolve(res.statusCode)
})
req.on('error', reject)
req.end()
})
}
JSThe security test describes the safe behaviour in five cases. The first is a regression guard: your own delete button must keep working through every layer. The other four are attacks, and each layer in this part makes one more of them pass:
cat > test/security/csrf.test.js <<'JS'
import { test, before, after, beforeEach, afterEach } from 'node:test'
import assert from 'node:assert/strict'
import { chromium } from 'playwright'
import { startApp, startLure, signIn, clickAndWait, sessionCookie, rawRequest } from '../helpers.js'
let browser, app, lure, page
before(async () => { browser = await chromium.launch() })
after(() => browser.close())
beforeEach(async () => {
app = await startApp()
lure = await startLure(app.site)
page = await browser.newPage() // a fresh profile: no cookies from earlier tests
await signIn(page, app)
})
afterEach(async () => {
await page.close()
await lure.close()
await app.close()
})
test('your own delete button still works', async () => {
await clickAndWait(page, 'li:first-child button', `${app.site}/posts/1/delete`)
assert.equal(app.postExists(1), false)
})
test('a form on another site cannot delete your post', async () => {
await page.goto(lure.crossSite)
await clickAndWait(page, '#claim button', `${app.site}/posts/1/delete`)
assert.equal(app.postExists(1), true, 'a cross-site form deleted post 1')
})
test('a link on another site cannot delete your post', async () => {
await page.goto(lure.crossSite)
await clickAndWait(page, '#link', `${app.site}/posts/1/delete`)
assert.equal(app.postExists(1), true, 'a cross-site link deleted post 1')
})
test('a form on a sibling origin cannot delete your post', async () => {
await page.goto(lure.sameSite)
await clickAndWait(page, '#claim button', `${app.site}/posts/1/delete`)
assert.equal(app.postExists(1), true, 'a same-site form on another port deleted post 1')
})
test('a write with no Origin, no Sec-Fetch-Site and no token is refused', async () => {
const cookie = await sessionCookie(page)
const status = await rawRequest(app, 'POST', '/posts/1/delete', { cookie })
assert.equal(status, 403)
assert.equal(app.postExists(1), true)
})
JSRun it:
npm run test:securityCheck it worked
npm reports an error, and that is the result you want. The summary at the end shows pass 1 and fail 4, in lines like ℹ pass 1 and ℹ fail 4. The delete button passes. The four attack tests fail with their messages, starting with a cross-site form deleted post 1: every route into the delete handler is open.
Step 4 · Set the session cookie to SameSite=Lax
SameSite tells the browser when to attach a cookie to a request that another site started:
Nonesends it every time. It must come withSecure. Apps end up here when someone needs the cookie inside an iframe on another site, or wants a payment page's returnPOSTto arrive signed in.Laxsends it on same-site requests, and on cross-site requests only when they are a top-level navigation with a safe method such asGET. A cross-site formPOSTarrives without it.Strictnever sends it on a request another site started, not even when someone follows a link.
Browsers do not agree on what a cookie with no SameSite attribute means. Some treat it as Lax, and still allow cross-site POST requests for two minutes after the cookie is set. Others send it everywhere. Part 1's cookie had no attribute, and this copy starts with None so the flaw shows the same way in every browser. Either way, the fix is to set the value yourself. Rewrite session.js:
cat > session.js <<'JS'
// Lax: not sent on cross-site POSTs, iframes or fetches; still sent when someone follows a link here.
export const sessionCookie = { httpOnly: true, secure: true, sameSite: 'lax', path: '/' }
export function parseCookies(header = '') {
const cookies = {}
for (const pair of header.split(';')) {
const i = pair.indexOf('=')
if (i > 0) cookies[pair.slice(0, i).trim()] = decodeURIComponent(pair.slice(i + 1).trim())
}
return cookies
}
JSnpm run test:securitySecure stays on. Browsers make an exception for http://localhost, so this works in development, and in production the cookie never travels over plain HTTP. Part 7 covers the rest of the session cookie's settings.
Why not Strict? It would also stop the forged link, but it logs people out in a way that feels like a bug. Someone taps a Noticeboard link in WhatsApp or an email, and the page opens signed out because the request came from another app's page. For a session cookie, Lax is the usual choice. The next two layers close what Lax leaves open.
If your app takes payments through a hosted checkout (Paystack, Flutterwave, M-Pesa and the rest), resist setting the session cookie back to None to make the return POST arrive signed in. Make the return route look up the payment by its reference and check it with the provider instead, so it does not need the session at all.
Check it worked
The summary at the end shows pass 2 and fail 3 (ℹ pass 2, ℹ fail 3). The cross-site form now arrives without the cookie. Noticeboard answers 401 and the post stays. Three tests still fail, and they are the two gaps Lax leaves:
a cross-site link deleted post 1: following a link is a top-levelGETnavigation, soLaxsends the cookie, and theGETroute deletes.a same-site form on another port deleted post 1:SameSiteis about sites, not origins. A form onlocalhost:4100, or on any subdomain that shares your site, gets the cookie.- The raw request fails too.
SameSiteis a browser rule, and a client that does not follow it sends whatever cookie it has.
Step 5 · Stop changing state on GET
GET is meant to be safe: following a link, prefetching a page or loading a preview must never change anything. Browsers, link previews in chat apps and some antivirus tools fetch URLs without anyone deciding to. A GET route that deletes data breaks every CSRF defence in this part, because every one of them, Lax and csrf-csrf included, lets GET through. Rewrite posts.js without the GET delete route:
cat > posts.js <<'JS'
import { Router } from 'express'
import { page, escapeHtml } from './views.js'
import { tokenField } from './csrf.js'
export function postsRouter(db) {
const router = Router()
const signedIn = (req, res, next) =>
req.user ? next() : res.status(401).send(page('Sign in', undefined, '<p>Sign in first.</p>'))
router.get('/', (req, res) => {
const posts = db.prepare('SELECT id, owner_id, title FROM posts ORDER BY id').all()
const field = req.user ? tokenField(req, res) : ''
const items = posts.map((p) => {
const del = req.user?.id === p.owner_id
? ` <form method="post" action="/posts/${p.id}/delete">${field}<button>Delete</button></form>`
: ''
return `<li>${escapeHtml(p.title)}${del}</li>`
})
res.send(page('Notices', req.user, `<h1>Notices</h1><ul>${items.join('')}</ul>`))
})
// Deleting is a POST only. GET routes never change data.
router.post('/posts/:id/delete', signedIn, (req, res) => {
const { changes } = db
.prepare('DELETE FROM posts WHERE id = ? AND owner_id = ?')
.run(Number(req.params.id), req.user.id)
if (changes === 0) return res.status(404).send(page('Not found', req.user, '<p>No such post.</p>'))
res.redirect(303, '/')
})
return router
}
JSnpm run test:securityIf an old email still links to /posts/12/delete, keep the URL, but make its GET show a page with a "Delete this post?" form that posts back. Then the deleting is done by the form, which the next two layers protect.
To find any others in your own code, list the GET routes and read what each one does:
grep -nE "(app|router)\.get\(" app.js posts.js api.jsCheck it worked
The summary at the end shows pass 3 and fail 2 (ℹ pass 3, ℹ fail 2). The link now gets Express's 404 page and the post stays. The grep lists only router.get('/', ...) and app.get('/signin', ...), both of which only read. The two failures left are the same-site form and the raw request.
Step 6 · Refuse cross-site writes with Sec-Fetch-Site and Origin
Every current browser adds a Sec-Fetch-Site header to requests sent to HTTPS sites and to localhost. The browser sets it, and page scripts cannot change it. It says where the request came from: same-origin, same-site, cross-site, or none when a person typed the address or opened a bookmark. That is exactly the question CSRF asks, so the server can answer it directly. For an unsafe method, allow same-origin and none and refuse everything else.
Older browsers do not send it. For those, fall back to the Origin header, which browsers add to cross-origin POST requests and which must match your own origin. Phones that stay on old Android versions, with a browser or WebView that no longer updates, are still common in many markets, so the fallback matters. When neither header is there, the request is from a very old browser or from a script that is not a browser at all. This layer lets it through, and the token in the next step decides.
Rewrite csrf.js with the header check:
cat > csrf.js <<'JS'
const SAFE = new Set(['GET', 'HEAD', 'OPTIONS'])
function refuse(res) {
res.status(403).type('text/plain').send('Refused: this request came from another site.')
}
// Layer 2: refuse unsafe requests the browser says came from another site or origin.
function rejectCrossOriginWrites(req, res, next) {
if (SAFE.has(req.method)) return next()
const site = req.get('sec-fetch-site')
if (site) return site === 'same-origin' || site === 'none' ? next() : refuse(res)
const origin = req.get('origin')
// Set APP_ORIGIN (for example https://noticeboard.example.com) behind a proxy.
const expected = process.env.APP_ORIGIN ?? `${req.protocol}://${req.get('host')}`
if (origin && origin !== expected) return refuse(res)
next() // no header at all: an old browser or a script; the token decides
}
export function csrfProtection() {
return [rejectCrossOriginWrites]
}
// Returns the hidden form field that carries the token. Empty until step 7.
export function tokenField(req, res) {
return ''
}
JSnpm run test:securitysame-site is refused on purpose. It is the case Lax cannot see, and Noticeboard has no sibling that should post forms to it. If your app does have one, such as app.example.com posting to api.example.com, allow that exact origin by name rather than every same-site request.
Check it worked
The summary at the end shows pass 4 and fail 1 (ℹ pass 4, ℹ fail 1). The sibling form now gets the Refused message with status 403, and your own delete button still works, because the browser labels it same-origin. The last failure is the raw request. It carries a valid cookie and no headers, so this layer lets it through, as designed.
Step 7 · Add form tokens with csrf-csrf
A CSRF token is a value that a page on another site cannot know. Noticeboard puts it in a hidden field in each of its own forms and refuses any unsafe request that does not send it back.
csrf-csrf 4.1 does this with the signed double-submit cookie pattern. It sets a cookie holding a random value and an HMAC of that value plus the session ID, signed with CSRF_SECRET. The same token goes into the form. On each POST it checks that the form field matches the cookie, and that the HMAC is right for this session. Another site can neither read the cookie nor make a valid HMAC, and a token taken from one session fails in any other. The classic synchroniser token pattern keeps the token in a server-side session instead. If you prefer that, csrf-sync, from the same author, implements it. OWASP's CSRF cheat sheet recommends both patterns.
Install it:
npm install csrf-csrf@4.1.0 --save-exactThen rewrite csrf.js. Layer 2 stays as it is. The token check runs after it, and tokenField now returns a real field:
cat > csrf.js <<'JS'
import { doubleCsrf } from 'csrf-csrf'
const SAFE = new Set(['GET', 'HEAD', 'OPTIONS'])
function refuse(res) {
res.status(403).type('text/plain').send('Refused: this request came from another site.')
}
// Layer 2: refuse unsafe requests the browser says came from another site or origin.
function rejectCrossOriginWrites(req, res, next) {
if (SAFE.has(req.method)) return next()
const site = req.get('sec-fetch-site')
if (site) return site === 'same-origin' || site === 'none' ? next() : refuse(res)
const origin = req.get('origin')
// Set APP_ORIGIN (for example https://noticeboard.example.com) behind a proxy.
const expected = process.env.APP_ORIGIN ?? `${req.protocol}://${req.get('host')}`
if (origin && origin !== expected) return refuse(res)
next() // no header at all: an old browser or a script; the token decides
}
// Layer 3: a signed token in every form, tied to the session ID.
const { doubleCsrfProtection, generateCsrfToken } = doubleCsrf({
getSecret: () => {
if (!process.env.CSRF_SECRET) throw new Error('Set CSRF_SECRET in .env')
return process.env.CSRF_SECRET
},
getSessionIdentifier: (req) => req.cookies.sid ?? '',
cookieName: 'nb.csrf', // over HTTPS, name it __Host-nb.csrf
cookieOptions: { sameSite: 'strict', secure: true, httpOnly: true, path: '/' },
getCsrfTokenFromRequest: (req) => req.body?._csrf,
})
export function csrfProtection() {
return [rejectCrossOriginWrites, doubleCsrfProtection]
}
// One token per response, however many forms the page has.
export function tokenField(req, res) {
res.locals.csrfToken ??= generateCsrfToken(req, res)
return `<input type="hidden" name="_csrf" value="${res.locals.csrfToken}">`
}
JSA few choices in that file matter:
getCsrfTokenFromRequestreads the form field only. It never falls back to the cookie. A check that compares the cookie with itself is no check at all, and the csrf-csrf README warns against fallbacks such as||for the same reason.getSessionIdentifieruses thesidcookie. After sign-in the session ID changes, so the token from the sign-in page stops working, and the next page gets a new one.generateCsrfTokenreuses the cookie's token while it is still valid for the session, so several open tabs keep working.- The token is made once per response. Each call to
generateCsrfTokenwith no valid cookie makes a new token, so caching it inres.localskeeps every form on a page in step with the one cookie. - Sign-in is protected too. Without a token, another site could sign you in to an account it controls ("login CSRF"), and you might then type something private into it.
- csrf-csrf skips
GET,HEADandOPTIONS. That is why the previous step matters: a token is no help to a route that changes data onGET.
When a token is missing or wrong, csrf-csrf passes an error with the code EBADCSRFTOKEN, and the handler you wrote in app.js answers 403 with "This form has expired. Go back, reload the page and try again." That wording matters on slow or patchy connections: someone who opened the form an hour ago and lost signal gets told what to do, not shown a bare error.
Check it worked
npm run test:securityAll five tests pass: the summary at the end shows ℹ pass 5 and ℹ fail 0. The raw request now gets 403, and your own delete button still works, because its form carries the token. If the button test fails instead, check that tokenField(req, res) is inside every <form method="post">.
Step 8 · See why the bearer-token JSON API needs none of this
The API in api.js has no SameSite settings, no header check and no token, and it does not need them. CSRF works because the browser attaches a credential by itself. A bearer token in the Authorization header is never attached by the browser: your own client code has to add it to each request, and another site cannot read it. Two things keep it that way:
- No cookies, ever. The API is mounted before the cookie middleware, so it cannot see a session even if one arrives. The moment an API accepts a cookie as login, it needs the defences above.
- A strict CORS policy.
Authorizationis not a CORS-safelisted header, so a page on another site that tries to send it first gets a preflightOPTIONSrequest. Noticeboard sends noAccess-Control-Allow-Originheader, so the browser refuses. If you add CORS later, list exact origins and never reflect whateverOriginarrives. Configure CORS for an API shows how.
Add a test that pins this down:
cat > test/security/api.test.js <<'JS'
import { test, before, after, beforeEach, afterEach } from 'node:test'
import assert from 'node:assert/strict'
import { chromium } from 'playwright'
import { startApp, startLure, signIn, sessionCookie, rawRequest } from '../helpers.js'
let browser, app, lure, page
before(async () => { browser = await chromium.launch() })
after(() => browser.close())
beforeEach(async () => {
app = await startApp()
lure = await startLure(app.site)
page = await browser.newPage()
await signIn(page, app)
})
afterEach(async () => {
await page.close()
await lure.close()
await app.close()
})
test('the API ignores the session cookie', async () => {
const cookie = await sessionCookie(page)
assert.equal(await rawRequest(app, 'DELETE', '/api/posts/1', { cookie }), 401)
assert.equal(app.postExists(1), true)
})
test('a page on another site cannot call the API', async () => {
await page.goto(lure.crossSite)
const result = await page.evaluate(async (url) => {
try {
const res = await fetch(url, {
method: 'DELETE',
credentials: 'include',
headers: { authorization: 'Bearer a-guess' },
})
return res.status
} catch {
return 'blocked by CORS'
}
}, `${app.site}/api/posts/1`)
assert.equal(result, 'blocked by CORS')
assert.equal(app.postExists(1), true)
})
test('the API works with its bearer token', async () => {
const status = await rawRequest(app, 'DELETE', '/api/posts/1', {
authorization: `Bearer ${process.env.API_TOKEN}`,
})
assert.equal(status, 204)
assert.equal(app.postExists(1), false)
})
JS
npm run test:securityThe opposite also holds. If you ever move a browser app's API token into localStorage to "avoid CSRF", you have swapped CSRF for exposure to XSS: any script that runs on your page can read it. Part 3's escaping and CSP become the defence then. For browser sessions, an HttpOnly cookie with the layers in this part is usually the safer pair.
Check it worked
Both files pass: the summary at the end of the run shows ℹ pass 8 and ℹ fail 0. The session cookie gets 401 from the API. The page on 127.0.0.1 gets blocked by CORS without the request ever reaching the delete handler. The real token deletes the post with 204.
Step 9 · Carry the layers into your own Noticeboard
Your copy from parts 1 to 3 has the same two flagged routes. Make the same four changes there. The file names are part 1's; if you split routes into files in part 2, make each change where that code now lives:
- Session cookie. In the
POST /signinhandler, set the attributes:res.cookie('sid', sid, { httpOnly: true, secure: true, sameSite: 'lax', path: '/' }). Part 7 adds the rest of the session fixes. - No GET writes. Delete the line
app.get('/posts/:id/delete', signedIn, deletePost). Then update the sharedFLAW (A01 CSRF, part 4)comment abovedeletePostso it no longer mentions GET links. Keep it for now: it also covers thePOSTroute, which the next change fixes. - Header check and tokens. Copy this part's
csrf.jsnext toapp.js, runnpm install csrf-csrf@4.1.0 --save-exact, addCSRF_SECRETto.envas in step 1, and addapp.use(csrfProtection())straight after the middleware that setsreq.cookiesandreq.user, before any route. - Every form. Put
${tokenField(req, res)}inside every<form method="post">: sign-in, sign-out, new post, edit, comment, delete and file thumbnails. Add theEBADCSRFTOKENbranch to the error handler inerrors.js, so an expired form gets a helpful 403 instead of a 500. Part 1's handler already keeps the 403 status fromerr.status, so only the message changes.
Then copy lure-page.js, the browser helpers and the csrf.test.js cases into your own test/security folder, adjusting the sign-in to your users. A CSRF test that drives a real browser is the only kind that can tell you a future change broke one of these layers.
Keep ~/noticeboard-demo/part4 for now. It uses little space apart from Playwright's browser, and part 8 removes the whole ~/noticeboard-demo folder.
Check it worked
In your own copy, check that no GET route deletes and that the defence is registered:
cd ~/noticeboard-demo
grep -n "get('/posts/:id/delete'" app.js || echo "no GET delete route"
grep -n "csrfProtection()" app.jsThe first command prints no GET delete route, and the second prints the line number of app.use(csrfProtection()). Start the app, sign in, and delete one of your own posts: it works. Then try the prize page against it, changing the target port in lure.js to 3000 if you moved it. You get the Refused message, and the post stays.
Next steps
- Part 5 turns to a different forged request, the one your server makes for itself: /tutorials/block-server-side-request-forgery-in-a-link-preview-feature
- Finish the session cookie, with a fresh session ID at sign-in, real sign-out and timeouts: /tutorials/secure-sessions-and-cookies-in-an-express-app
- Lock down a JSON API that does accept browser calls from other origins: /tutorials/configure-cors-for-an-api
- Revisit the XSS defences, which matter more once tokens sit in your pages: /tutorials/stop-xss-with-output-encoding-and-a-content-security-policy
Related tutorials
- Write custom Fail2ban jails and filters for your own appsYou will have Fail2ban 1.1 banning repeated failed sign-ins to your own app and to an nginx basic-auth area, with filters you tested against sample logs, your own addresses allow-listed, and longer bans for repeat offenders.
- Validate file uploads before you store or serve themYou will take a FastAPI image upload route that trusts everything the browser sends, prove its flaws with pytest, and rebuild it with size limits, type checks from the file's own bytes, Pillow re-encoding, random storage names and safe download headers.
- Use SSH certificates instead of copying keys to every serverYou will run a small SSH certificate authority with ssh-keygen, log in to an Ubuntu 26.04 server with an eight-hour user certificate, give the server a host certificate so clients stop asking about fingerprints, and revoke a certificate the server then refuses.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials