Security and hardening · Intermediate · 27 min
Stop cross-site scripting with output encoding and a Content Security Policy
By Padding · Updated 26 Nov 2026
Node.js 26.13 (node:26) · Express 5.3.0 · Helmet 8.3.0 · DOMPurify 3.5.0 · jsdom 31.0.1
You will prove stored, reflected and DOM-based cross-site scripting in a copy of Noticeboard with failing tests, then fix each one with escaping by default, a DOMPurify allow-list, textContent, an HttpOnly session cookie and a Helmet Content Security Policy.
On this page
Cross-site scripting (XSS) happens when text a user typed reaches a page as markup. The browser cannot tell which <script> or onerror= the developer wrote and which one arrived in a comment, so it runs both, with the victim's session. In the OWASP Top 10:2025 it sits under A05 Injection, next to the SQL injection you may already have fixed.
The copy of Noticeboard you write in step 1 has the flaw in three shapes:
- Stored. A comment is saved as typed and printed into the post page for every later visitor.
- Reflected. The search page prints the
qparameter from the URL back into the page, so a crafted link attacks whoever opens it. - DOM-based. A small browser script on the search page reads the query from the address bar and writes it into the page with
innerHTML. The server never sees the attack at all.
Post bodies are a fourth case: authors may use bold, lists and links, so you cannot escape everything there. You will prove all of this with tests that use a harmless marker, an image tag whose error handler would only change the page title, then fix each flaw at its source. The Content Security Policy comes last, as a backstop for the mistake you have not found yet, not as the fix.
Practise only on your own copy of Noticeboard on 127.0.0.1. Never try these inputs on sites you do not own.
Step 1 · Start from this copy of Noticeboard
This part works in its own folder, ~/noticeboard-demo/part3, so the app from parts 1 and 2 stays exactly as it is. The copy keeps part 1's names where it can: the users amara, bola and chen, the sid cookie, POST /signin, a page(title, user, body) layout in views.js and a test/security folder. It is trimmed to posts, comments and search, and it adds the search banner script, so the DOM-based shape has somewhere to live. Two shortcuts keep it small: sign-in takes a name with no password, and sessions live in a SQLite table so the tests can create one directly. Neither is how you should ship an app; parts 2 and 7 deal with both.
Create the folder and install Express:
mkdir -p ~/noticeboard-demo/part3/public ~/noticeboard-demo/part3/test/security
cd ~/noticeboard-demo/part3
cat > package.json <<'JSON'
{
"name": "noticeboard-part3",
"private": true,
"type": "module",
"scripts": {
"start": "node server.js",
"test": "node --test"
}
}
JSON
npm install --save-exact express@5.3.0db.js creates the tables and, on first run, the three users and one post whose body is formatted HTML:
cd ~/noticeboard-demo/part3
cat > db.js <<'JS'
import { DatabaseSync } from 'node:sqlite'
export function openDb(file = 'noticeboard.db') {
const db = new DatabaseSync(file)
db.exec(`
CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT UNIQUE NOT NULL);
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, user_id INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY, owner_id INTEGER NOT NULL,
title TEXT NOT NULL, body_html TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS comments (id INTEGER PRIMARY KEY, post_id INTEGER NOT NULL,
author_id INTEGER NOT NULL, body TEXT NOT NULL);
`)
if (!db.prepare('SELECT 1 FROM users').get()) {
db.exec(`
INSERT INTO users (id, name) VALUES (1, 'amara'), (2, 'bola'), (3, 'chen');
INSERT INTO posts (id, owner_id, title, body_html)
VALUES (1, 1, 'Welcome', '<p>Welcome to the <b>noticeboard</b>.</p>');
`)
}
return db
}
JSsession.js sets the sid cookie and finds the signed-in user. It sets the cookie with no options, as part 1 does:
cd ~/noticeboard-demo/part3
cat > session.js <<'JS'
import { randomBytes } from 'node:crypto'
export function startSession(db, res, userId) {
const id = randomBytes(32).toString('base64url')
db.prepare('INSERT INTO sessions (id, user_id) VALUES (?, ?)').run(id, userId)
res.cookie('sid', id)
}
export function loadUser(db) {
const find = db.prepare(
'SELECT users.id, users.name FROM sessions JOIN users ON users.id = sessions.user_id WHERE sessions.id = ?'
)
return (req, res, next) => {
const match = /(?:^|;\s*)sid=([^;]+)/.exec(req.headers.cookie ?? '')
req.user = match ? find.get(match[1]) : undefined
next()
}
}
JSviews.js holds the layout and every page. This is where the stored and reflected flaws live: each ${...} drops a value into the HTML unchanged.
cd ~/noticeboard-demo/part3
cat > views.js <<'JS'
export function page(title, user, body) {
const who = user ? `Signed in as ${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>${title} - Noticeboard</title></head>
<body><header><a href="/">Noticeboard</a> <a href="/search">Search</a> ${who}</header>
<main>${body}</main></body>
</html>`
}
export function homePage(posts, user) {
return page('Home', user, `<h1>Posts</h1><ul>${posts
.map((p) => `<li><a href="/posts/${p.id}">${p.title}</a></li>`)
.join('')}</ul>`)
}
export function postPage(post, comments, user) {
return page(post.title, user, `
<article><h1>${post.title}</h1><div class="post-body">${post.body_html}</div></article>
<section class="comments"><h2>Comments</h2>
${comments.map((c) => `<div class="comment"><p class="by">${c.author}</p><p class="text">${c.body}</p></div>`).join('')}
${user ? `<form method="post" action="/posts/${post.id}/comments">
<label>Comment <textarea name="body" required></textarea></label>
<button>Add comment</button></form>` : ''}
</section>`)
}
export function searchPage(q, posts, user) {
return page('Search', user, `
<h1>Search</h1>
<form action="/search"><input name="q" value="${q}" aria-label="Search posts"><button>Search</button></form>
<p id="you-searched"></p>
<p class="count">${posts.length} results for ${q}</p>
<ul>${posts.map((p) => `<li><a href="/posts/${p.id}">${p.title}</a></li>`).join('')}</ul>
<script src="/search-banner.js"></script>`)
}
export function signInPage(user) {
return page('Sign in', user, `<h1>Sign in</h1>
<form method="post" action="/signin">
<label>Name <input name="name" autocomplete="username" required></label>
<button>Sign in</button></form>`)
}
JSThe routes go in three small files, posts.js, search.js and auth.js:
cd ~/noticeboard-demo/part3
cat > posts.js <<'JS'
import { Router } from 'express'
import { homePage, postPage } from './views.js'
export function postsRouter(db) {
const router = Router()
router.get('/', (req, res) => {
res.send(homePage(db.prepare('SELECT id, title FROM posts ORDER BY id').all(), req.user))
})
router.get('/posts/:id', (req, res) => {
const post = db.prepare('SELECT * FROM posts WHERE id = ?').get(req.params.id)
if (!post) return res.status(404).send('Not found')
const comments = db.prepare(
'SELECT comments.body, users.name AS author FROM comments JOIN users ON users.id = comments.author_id WHERE post_id = ? ORDER BY comments.id'
).all(post.id)
res.send(postPage(post, comments, req.user))
})
router.post('/posts', (req, res) => {
if (!req.user) return res.status(401).send('Sign in first')
const { lastInsertRowid } = db.prepare(
'INSERT INTO posts (owner_id, title, body_html) VALUES (?, ?, ?)'
).run(req.user.id, String(req.body.title ?? ''), String(req.body.body_html ?? ''))
res.redirect(303, `/posts/${lastInsertRowid}`)
})
router.post('/posts/:id/comments', (req, res) => {
if (!req.user) return res.status(401).send('Sign in first')
db.prepare('INSERT INTO comments (post_id, author_id, body) VALUES (?, ?, ?)')
.run(req.params.id, req.user.id, String(req.body.body ?? ''))
res.redirect(303, `/posts/${req.params.id}`)
})
return router
}
JS
cat > search.js <<'JS'
import { Router } from 'express'
import { searchPage } from './views.js'
export function searchRouter(db) {
const router = Router()
router.get('/search', (req, res) => {
const q = String(req.query.q ?? '')
const posts = db.prepare("SELECT id, title FROM posts WHERE title LIKE '%' || ? || '%'").all(q)
res.send(searchPage(q, posts, req.user))
})
return router
}
JS
cat > auth.js <<'JS'
import { Router } from 'express'
import { startSession } from './session.js'
import { signInPage } from './views.js'
export function authRouter(db) {
const router = Router()
router.get('/signin', (req, res) => res.send(signInPage(req.user)))
router.post('/signin', (req, res) => {
const user = db.prepare('SELECT id FROM users WHERE name = ?').get(String(req.body.name ?? ''))
if (!user) return res.status(401).send('Unknown user')
startSession(db, res, user.id)
res.redirect(303, '/')
})
return router
}
JSLast, app.js builds the app without starting it, so the tests can start their own copy, server.js starts it on 127.0.0.1 only, and public/search-banner.js is the browser script with the DOM-based flaw:
cd ~/noticeboard-demo/part3
cat > app.js <<'JS'
import express from 'express'
import { loadUser } from './session.js'
import { authRouter } from './auth.js'
import { postsRouter } from './posts.js'
import { searchRouter } from './search.js'
export function createApp(db) {
const app = express()
app.use(express.urlencoded({ extended: false }))
app.use(express.static('public'))
app.use(loadUser(db))
app.use(authRouter(db))
app.use(postsRouter(db))
app.use(searchRouter(db))
return app
}
JS
cat > server.js <<'JS'
import { createApp } from './app.js'
import { openDb } from './db.js'
createApp(openDb()).listen(3000, '127.0.0.1', () => {
console.log('Noticeboard on http://127.0.0.1:3000')
})
JS
cat > public/search-banner.js <<'JS'
const q = new URLSearchParams(location.search).get('q') ?? ''
document.querySelector('#you-searched').innerHTML = `You searched for <b>${q}</b>`
JS
node --check app.js && echo "app.js parses"Check it worked
The last command prints app.js parses, and ls ~/noticeboard-demo/part3 lists app.js, auth.js, db.js, posts.js, search.js, server.js, session.js, views.js, public, test and the npm files. If npm install failed, check you are on Node.js 26 with node --version.
Step 2 · Write tests that prove the flaw
Each part of this series starts with a test that fails while the flaw is there. The XSS tests need a real HTML parser, so they can ask the question a browser would: did the marker become an element, or did it stay as text? Install jsdom, a DOM implementation for Node.js. Later in this tutorial the app itself uses it too, so it goes in dependencies:
cd ~/noticeboard-demo/part3
npm install --save-exact jsdom@31.0.1Create test/security/xss.test.js. The tests start Noticeboard on a random port with an in-memory database and sign in as amara by writing a session row, so they never touch your real noticeboard.db:
cd ~/noticeboard-demo/part3
cat > test/security/xss.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { once } from 'node:events'
import { JSDOM } from 'jsdom'
import { createApp } from '../../app.js'
import { openDb } from '../../db.js'
import { startSession } from '../../session.js'
// Harmless markers: if either one becomes markup, the most it could do is change the page title.
const MARKER = `<img src="x" onerror="document.title='nb-xss'">`
const BREAKOUT = `"><img src="x" onerror="document.title='nb-xss'">`
let db, server, base
const cookie = 'sid=xss-test-session'
before(async () => {
db = openDb(':memory:')
db.prepare('INSERT INTO sessions (id, user_id) VALUES (?, 1)').run('xss-test-session')
server = createApp(db).listen(0, '127.0.0.1')
await once(server, 'listening')
base = `http://127.0.0.1:${server.address().port}`
})
after(() => {
server.closeAllConnections()
server.close()
})
async function getDocument(path) {
const res = await fetch(base + path)
return new JSDOM(await res.text()).window.document
}
function postForm(path, fields) {
return fetch(base + path, {
method: 'POST',
headers: { cookie, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(fields),
redirect: 'manual',
})
}
test('stored: a comment is shown as text, not markup', async () => {
await postForm('/posts/1/comments', { body: MARKER })
const doc = await getDocument('/posts/1')
assert.equal(doc.querySelector('.comments [onerror]'), null, 'the comment became an element')
assert.ok(doc.querySelector('.comments').textContent.includes(MARKER), 'the comment text is missing')
})
test('reflected: the search query stays inside the input and the text', async () => {
const doc = await getDocument('/search?q=' + encodeURIComponent(BREAKOUT))
assert.equal(doc.querySelector('[onerror]'), null, 'the query broke out of its attribute')
assert.equal(doc.querySelector('input[name=q]').value, BREAKOUT)
assert.ok(doc.querySelector('.count').textContent.includes(BREAKOUT))
})
test('DOM-based: the search banner script writes text, not HTML', async () => {
const dom = await JSDOM.fromURL(base + '/search?q=' + encodeURIComponent(MARKER), {
runScripts: 'dangerously',
resources: 'usable',
})
if (dom.window.document.readyState !== 'complete') await once(dom.window, 'load')
const banner = dom.window.document.querySelector('#you-searched')
assert.equal(banner.querySelector('img'), null, 'the banner script created an element')
assert.ok(banner.textContent.includes(MARKER))
dom.window.close()
})
test('formatted post body keeps bold text and loses scripts', async () => {
const res = await postForm('/posts', {
title: 'Formatting test',
body_html: `<p>Hello <b>team</b></p>${MARKER}<a href="javascript:document.title='nb-xss'">click</a>`,
})
const doc = await getDocument(res.headers.get('location'))
const body = doc.querySelector('.post-body')
assert.ok(body.querySelector('b'), 'allowed formatting was removed')
assert.equal(body.querySelector('[onerror]'), null, 'an event handler survived')
for (const a of body.querySelectorAll('a[href]')) {
assert.ok(!/^\s*javascript:/i.test(a.getAttribute('href')), 'a javascript: link survived')
}
})
test('the session cookie is HttpOnly', () => {
const calls = []
const res = { cookie: (name, value, options = {}) => calls.push({ name, options }) }
startSession(openDb(':memory:'), res, 1)
assert.equal(calls[0].name, 'sid')
assert.equal(calls[0].options.httpOnly, true, 'scripts on the page can read the session cookie')
})
test('pages carry a Content Security Policy', async () => {
const res = await fetch(base + '/search?q=test')
const csp = res.headers.get('content-security-policy') ?? ''
assert.match(csp, /script-src 'self'/)
assert.match(csp, /script-src-attr 'none'/)
assert.match(csp, /object-src 'none'/)
})
JSRun the file on its own:
node --test test/security/xss.test.jsCheck it worked
All six tests fail, and the summary at the end shows pass 0 and fail 6. Read the messages: "the comment became an element", "the query broke out of its attribute" and "the banner script created an element" are the three XSS shapes; the last two failures are the missing cookie flag and the missing policy. If a test fails with ECONNREFUSED or Cannot find module instead, check that you ran it from ~/noticeboard-demo/part3 and that the imports at the top match your file names.
Step 3 · Make escaping the default in your templates
Noticeboard builds its pages with plain template literals, so every ${...} drops a value into the page unchanged. The fix is not to remember escaping at every place. It is to make escaping what happens when you forget, and to make trusted HTML the thing you have to ask for by name.
Create html.js. It is a tagged template: html escapes every value it is given, except values that are already html fragments or that you wrapped in raw() on purpose:
cd ~/noticeboard-demo/part3
cat > html.js <<'JS'
const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }
export function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (ch) => ESCAPES[ch])
}
class SafeHtml {
constructor(value) {
this.value = value
}
toString() {
return this.value
}
}
// Only for HTML you produced or sanitised yourself. Never for raw user input.
export function raw(trusted) {
return new SafeHtml(String(trusted))
}
function render(value) {
if (value instanceof SafeHtml) return value.value
if (Array.isArray(value)) return value.map(render).join('')
if (value === null || value === undefined || value === false) return ''
return escapeHtml(value)
}
export function html(strings, ...values) {
let out = strings[0]
values.forEach((value, i) => {
out += render(value) + strings[i + 1]
})
return new SafeHtml(out)
}
// For href and src: escaping does not stop javascript: URLs, so allow only these schemes.
export function safeUrl(value) {
try {
const url = new URL(String(value), 'http://placeholder.invalid')
return ['http:', 'https:', 'mailto:'].includes(url.protocol) ? String(value) : '#'
} catch {
return '#'
}
}
JSThe five characters it replaces are enough for two places a value can land:
- Text between tags, such as a comment body.
<becomes<, so no new tag can start. - A quoted attribute value, such as
value="..."in the search box."becomes", so the value cannot close the attribute. This only holds if the attribute is quoted, so always quote:value="${q}", nevervalue=${q}.
Other places need other rules, which is why the OWASP guidance calls this context-aware encoding:
- URLs in
hreforsrc.javascript:alert(1)contains none of the five characters, so escaping lets it through. Pass any link a user supplied throughsafeUrl(), which keeps onlyhttp,httpsandmailto. - Inside
<script>or an event handler. Do not put user data there at all. Put it in adata-attribute or a<script type="application/json">block and read it from your script. - Inside
<style>or astyleattribute. Same rule: keep user data out.
If you use a template engine instead, the idea is identical: Nunjucks and Handlebars escape {{ value }} by default, and EJS escapes <%= value %> but not <%- value %>. Search your templates for the unescaped form; each hit needs a reason.
Check it worked
Try the helper from the command line:
cd ~/noticeboard-demo/part3
node -e "
import('./html.js').then(({ html, raw, safeUrl }) => {
const q = '\"><img src=x onerror=alert(1)>'
console.log(String(html\`<input value=\"\${q}\">\`))
console.log(String(html\`<p>\${raw('<b>trusted</b>')}</p>\`))
console.log(safeUrl('javascript:alert(1)'), safeUrl('https://example.org/a'))
})
"The first line shows "><img inside the attribute instead of a new tag. The second keeps <b>trusted</b>, because you asked for it with raw(). The third prints # https://example.org/a.
Step 4 · Allow formatting in post bodies with DOMPurify
Post bodies are the one field where authors may write HTML: bold, italics, lists, quotes and links. Escaping would show them the tags as text, and a hand-written regular expression that removes "bad" tags will miss something, because browsers accept a great deal of broken markup. Use a sanitiser that parses the HTML the way a browser does and keeps only an allow-list. DOMPurify is that sanitiser; on the server it needs the jsdom window you installed in the last step. The DOMPurify team asks you to keep jsdom current, because old jsdom versions have parsing bugs that let markup through.
cd ~/noticeboard-demo/part3
npm install --save-exact dompurify@3.5.0Create sanitise.js with an allow-list that matches what the post editor offers, and nothing more:
cd ~/noticeboard-demo/part3
cat > sanitise.js <<'JS'
import { JSDOM } from 'jsdom'
import createDOMPurify from 'dompurify'
const purify = createDOMPurify(new JSDOM('').window)
const POST_BODY = {
ALLOWED_TAGS: ['p', 'br', 'b', 'strong', 'i', 'em', 'ul', 'ol', 'li', 'blockquote', 'code', 'a'],
ALLOWED_ATTR: ['href'],
// Links may go to http, https, mailto or a path on this site. Nothing else.
ALLOWED_URI_REGEXP: /^(?:https?:|mailto:|\/(?!\/))/i,
}
export function cleanPostHtml(dirty) {
return purify.sanitize(String(dirty), POST_BODY)
}
JSYou sanitise when the page is rendered, not only when the post is saved. The posts already in your database were saved before this fix, and cleaning on output covers them too. On a busy site, store a cleaned copy alongside the original when a post is saved, and re-clean the stored copies whenever you change the allow-list.
Check it worked
Feed it a mix of allowed formatting and the marker:
cd ~/noticeboard-demo/part3
node -e "
import('./sanitise.js').then(({ cleanPostHtml }) => {
console.log(cleanPostHtml('<p>Hi <b>all</b></p><img src=x onerror=alert(1)><a href=\"javascript:alert(1)\">x</a><a href=\"/posts/1\">ok</a>'))
})
"The output keeps <p>Hi <b>all</b></p>, drops the <img> entirely, leaves the first link as <a>x</a> with no href, and keeps <a href="/posts/1">ok</a>.
Step 5 · Rebuild the views on the safe helpers
Now replace views.js so every page, the page() layout included, is built with html, and the post body goes through the sanitiser before raw() lets it in. It also re-exports escapeHtml, so code that only needs to escape one value can import it from views.js next to page. The route files do not change: each view still returns a string.
cd ~/noticeboard-demo/part3
cat > views.js <<'JS'
import { html, raw } from './html.js'
import { cleanPostHtml } from './sanitise.js'
export { escapeHtml } from './html.js'
// body must be an html`...` fragment. A plain string is escaped and shows as text.
export function page(title, user, body) {
const who = user ? html`Signed in as ${user.name}` : html`<a href="/signin">Sign in</a>`
return String(html`<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>${title} - Noticeboard</title></head>
<body><header><a href="/">Noticeboard</a> <a href="/search">Search</a> ${who}</header>
<main>${body}</main></body>
</html>`)
}
export function homePage(posts, user) {
return page('Home', user, html`<h1>Posts</h1><ul>${posts.map(
(p) => html`<li><a href="/posts/${p.id}">${p.title}</a></li>`
)}</ul>`)
}
export function postPage(post, comments, user) {
return page(post.title, user, html`
<article><h1>${post.title}</h1><div class="post-body">${raw(cleanPostHtml(post.body_html))}</div></article>
<section class="comments"><h2>Comments</h2>
${comments.map((c) => html`<div class="comment"><p class="by">${c.author}</p><p class="text">${c.body}</p></div>`)}
${user && html`<form method="post" action="/posts/${post.id}/comments">
<label>Comment <textarea name="body" required></textarea></label>
<button>Add comment</button></form>`}
</section>`)
}
export function searchPage(q, posts, user) {
return page('Search', user, html`
<h1>Search</h1>
<form action="/search"><input name="q" value="${q}" aria-label="Search posts"><button>Search</button></form>
<p id="you-searched"></p>
<p class="count">${posts.length} results for ${q}</p>
<ul>${posts.map((p) => html`<li><a href="/posts/${p.id}">${p.title}</a></li>`)}</ul>
<script src="/search-banner.js"></script>`)
}
export function signInPage(user) {
return page('Sign in', user, html`<h1>Sign in</h1>
<form method="post" action="/signin">
<label>Name <input name="name" autocomplete="username" required></label>
<button>Sign in</button></form>`)
}
JSNotice what is gone: .join('') on each list. The helper renders arrays itself, and a joined string would be escaped as text, which is the safe failure. The only raw() in the file wraps the output of cleanPostHtml, so a code review has one line to question.
node --test test/security/xss.test.jsCheck it worked
Three tests now pass: stored, reflected and the formatted post body. The summary shows pass 3 and fail 3. The DOM-based test still fails, even though the server now escapes the query perfectly, because that attack never goes through your templates.
Step 6 · Stop the browser script writing user data as HTML
public/search-banner.js takes q from the address bar and hands it to innerHTML, which parses it as markup. Server-side escaping cannot help: the script reads the raw URL in the browser. The rule for browser code is that user data goes into the page through APIs that treat it as text, such as textContent, createElement, setAttribute on a non-URL attribute, and value. innerHTML, outerHTML, insertAdjacentHTML and document.write are for markup you wrote yourself.
Replace the script:
cd ~/noticeboard-demo/part3
cat > public/search-banner.js <<'JS'
const q = new URLSearchParams(location.search).get('q') ?? ''
const banner = document.querySelector('#you-searched')
const term = document.createElement('b')
term.textContent = q
banner.replaceChildren('You searched for ', term)
JSThe banner looks the same as before, with the search term in bold, but the term can only ever be text. The same rule applies to frameworks: React escapes values in JSX, and dangerouslySetInnerHTML is the innerHTML of React, so give it only DOMPurify output.
Check it worked
node --test test/security/xss.test.jsThe DOM-based test passes, and the summary shows pass 4 and fail 2. To find any other unsafe sinks in your own code, search for them:
cd ~/noticeboard-demo/part3
grep -rnE "innerHTML|outerHTML|insertAdjacentHTML|document\.write" --include='*.js' --exclude-dir=node_modules --exclude-dir=test . || echo "no HTML sinks found"It prints no HTML sinks found. In a larger project, every hit is a line to review.
Step 7 · Keep the session cookie away from page scripts
Escaping and sanitising remove the hole. The next two changes limit the damage if a new one appears. The first: a script injected into a Noticeboard page can read document.cookie, and with it amara's sid, which is all an attacker needs to be amara from their own machine. A cookie marked HttpOnly is still sent with every request, but scripts cannot read it.
Replace session.js. The only change is the options on res.cookie:
cd ~/noticeboard-demo/part3
cat > session.js <<'JS'
import { randomBytes } from 'node:crypto'
export function startSession(db, res, userId) {
const id = randomBytes(32).toString('base64url')
db.prepare('INSERT INTO sessions (id, user_id) VALUES (?, ?)').run(id, userId)
// HttpOnly: sent with requests, invisible to document.cookie.
res.cookie('sid', id, { httpOnly: true, path: '/' })
}
export function loadUser(db) {
const find = db.prepare(
'SELECT users.id, users.name FROM sessions JOIN users ON users.id = sessions.user_id WHERE sessions.id = ?'
)
return (req, res, next) => {
const match = /(?:^|;\s*)sid=([^;]+)/.exec(req.headers.cookie ?? '')
req.user = match ? find.get(match[1]) : undefined
next()
}
}
JSHttpOnly does not stop an injected script from acting as amara while she has the page open, because her browser still sends the cookie with the script's requests. It stops the session leaving her browser. The cookie still has no SameSite or Secure attribute and no expiry: part 4 covers SameSite and part 7 finishes the cookie.
Check it worked
node --test test/security/xss.test.jsFive tests pass. Now see the header a real sign-in sends. Start Noticeboard in your second terminal:
cd ~/noticeboard-demo/part3
npm startBack in the first terminal, sign in as amara and print the cookie the app sets:
cookie_header=$(curl -si -d name=amara http://127.0.0.1:3000/signin | grep -i '^set-cookie:')
echo "$cookie_header"
grep -qiE '^set-cookie: sid=[^;]+; Path=/; HttpOnly' <<<"$cookie_header"It prints one line, Set-Cookie: sid=...; Path=/; HttpOnly, with a long random value in place of the dots. To see the same in a browser, open http://127.0.0.1:3000/signin, sign in as amara, open DevTools and look at the sid cookie under Application, Cookies in Chrome or Storage, Cookies in Firefox: the HttpOnly column is ticked, and typing document.cookie in the Console no longer shows sid. Stop the app with Ctrl+C before the next step.
Step 8 · Add a Content Security Policy with Helmet
A Content Security Policy (CSP) is a response header that tells the browser which scripts, styles and other resources a page may load. With a policy that allows scripts only from your own origin and forbids inline event handlers, a marker that slipped past your escaping would sit in the page doing nothing. Helmet 8.3 sets a sensible default policy, plus other security headers, in one middleware.
cd ~/noticeboard-demo/part3
npm install --save-exact helmet@8.3.0Put the configuration in its own file, security-headers.js:
cd ~/noticeboard-demo/part3
cat > security-headers.js <<'JS'
import helmet from 'helmet'
const isProduction = process.env.NODE_ENV === 'production'
export function securityHeaders() {
return helmet({
contentSecurityPolicy: {
directives: {
// Keep the upgrade to HTTPS in production. Drop it while you develop on plain
// http://127.0.0.1, where some browsers would otherwise try HTTPS and fail.
'upgrade-insecure-requests': isProduction ? [] : null,
},
},
})
}
JSThen replace app.js. It has two additions: the import, and the middleware as the first app.use after const app = express(), so every response gets the headers, including static files and error pages:
cd ~/noticeboard-demo/part3
cat > app.js <<'JS'
import express from 'express'
import { securityHeaders } from './security-headers.js'
import { loadUser } from './session.js'
import { authRouter } from './auth.js'
import { postsRouter } from './posts.js'
import { searchRouter } from './search.js'
export function createApp(db) {
const app = express()
app.use(securityHeaders())
app.use(express.urlencoded({ extended: false }))
app.use(express.static('public'))
app.use(loadUser(db))
app.use(authRouter(db))
app.use(postsRouter(db))
app.use(searchRouter(db))
return app
}
JSHelmet's default policy includes these directives, among others:
script-src 'self': scripts only from files on your own origin. Inline<script>blocks are refused, which is why the search banner lives in/search-banner.js.script-src-attr 'none': no inline event handlers such asonerror=oronclick=, which is exactly what the marker uses.object-src 'none'andbase-uri 'self': no plugins, and no<base>tag that would redirect your relative script URLs.style-src 'self' https: 'unsafe-inline': styles are left loose, because inline styles are common and far less dangerous than scripts.
This is an allow-list policy, and it is a first layer. If you ever add a CDN to script-src, any script on that CDN becomes allowed, including old library versions with known bypasses. The stricter design, with a random nonce per response and 'strict-dynamic', has its own tutorial, linked at the end.
If many of your readers use older Android phones whose browsers rarely update, which is common on prepaid plans where updates cost data, remember the order of these layers: escaping and sanitising work in every browser ever made, while an old browser may ignore newer CSP directives such as script-src-attr. The policy is the backstop, never the fix.
Check it worked
Run the tests once more:
cd ~/noticeboard-demo/part3
node --test test/security/xss.test.jsAll six pass: the summary shows pass 6 and fail 0. Now look at the headers a browser receives. Start Noticeboard again in your second terminal:
cd ~/noticeboard-demo/part3
npm startBack in the first terminal, ask for the search page's headers:
curl -sI 'http://127.0.0.1:3000/search?q=test' | grep -iE '^(content-security-policy|x-content-type-options|x-frame-options):'
curl -sI 'http://127.0.0.1:3000/search?q=test' | grep -i '^content-security-policy:' | grep -q "script-src-attr 'none'"You see three headers. Content-Security-Policy starts with something like default-src 'self';base-uri 'self' and contains script-src 'self' and script-src-attr 'none', with no upgrade-insecure-requests while NODE_ENV is unset. X-Content-Type-Options: nosniff and X-Frame-Options: SAMEORIGIN come from Helmet too. Open http://127.0.0.1:3000/search?q=hello in your browser: the page works and the Console shows no CSP errors, because Noticeboard no longer has any inline script. Stop the app with Ctrl+C.
Step 9 · Carry the fixes into your own Noticeboard
If you built Noticeboard in part 1, the same flaws sit in its app.js: titles and comments in GET /posts/:id, and the search term in GET /search, all go into page() unescaped. Part 1 has no search banner script and no formatted post bodies, so two of the fixes here are only needed if you add those features. To carry the rest across:
- Helpers. Copy
html.jsfrom~/noticeboard-demo/part3next to yourapp.js. Addsanitise.jsas well, and installjsdom@31.0.1anddompurify@3.5.0, only if you let authors format posts. - Templates. Import
htmland buildpage()and every page body with` html...`` instead of plain template literals, then remove the `.join('')calls on lists. Search the file forraw(; each one should wrap HTML you wrote or sanitised. - Session cookie. In the
POST /signinhandler, changeres.cookie('sid', sid)tores.cookie('sid', sid, { httpOnly: true, path: '/' }). Part 4 addsSameSiteandSecure. - Headers. Copy
security-headers.js, installhelmet@8.3.0, and makeapp.use(securityHeaders())the firstapp.useincreateApp. - Tests. Copy
test/security/xss.test.jsand change the stored and reflected tests to match your routes: part 1's comment list uses<li>items rather than.commentblocks, and its search results have no.countparagraph.
Check it worked
In your own project, node --test test/security/xss.test.js shows the tests you kept passing, and curl -si against your POST /signin shows HttpOnly on the sid cookie. Keep ~/noticeboard-demo/part3 too: it is a working reference for the helpers. Part 4 works in its own copy, ~/noticeboard-demo/part4, so nothing there depends on this folder.
Next steps
- Protect Noticeboard's forms from cross-site posts with SameSite cookies and tokens in part 4: /tutorials/protect-forms-from-csrf-with-samesite-cookies-and-tokens
- Replace the allow-list with a strict nonce-based policy, Report-Only roll-out and Trusted Types: /tutorials/set-a-strict-content-security-policy-with-nonces
- Set the same headers for static sites served by nginx: /tutorials/add-security-headers-in-nginx
- Go back over part 2's access-control matrix if you skipped it: /tutorials/fix-broken-access-control-in-an-express-app
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