{"id":"6b09a4bfff996234422a274c","slug":"security-headers-and-csp","title":"Security headers and CSP – nonces, strict-dynamic, report-only, HSTS, Permissions-Policy and CORS in Express, NestJS and CloudFront","summary":"We configure the pierogi store's security headers – a Content Security Policy with nonces and strict-dynamic rolled out in report-only mode first, HSTS with preload, protection against framing, Referrer-Policy, Permissions-Policy and CORS without the \"star\". Helmet in Express and NestJS, a CloudFront headers policy for a static SPA, real header dumps, an interactive CSP builder and testing tools.","servedLang":"en","availableLangs":["pl","en"],"topics":["web-security","express","nestjs"],"techs":["node","typescript","javascript"],"tags":["csp","content-security-policy","nonce","strict-dynamic","hsts","cors","helmet","permissions-policy","referrer-policy","clickjacking","cloudfront","security-headers"],"level":"intermediate","kind":"tutorial","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":13,"stats":{"views":1,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T15:41:51.458Z","updatedAt":"2026-11-27T17:31:41.335Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"rose","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"HTTP security headers in practice – Content-Security-Policy (nonce, hash, strict-dynamic, report-only, report-to), Strict-Transport-Security and preload, X-Content-Type-Options, frame-ancestors, Referrer-Policy, Permissions-Policy, COOP, CORS with credentials; helmet for Express and NestJS, CloudFro","wordCount":2576,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"After the penetration test, the pierogi store fixed every XSS-prone spot that was found. The auditor asked, though: \"And what if someone adds a new one tomorrow?\". Security headers are the second line of defence: the browser itself refuses to run a script you didn't authorize, to embed the page in someone else's frame or to connect over HTTP – even when the code has a bug. In this tutorial we configure them in Express, NestJS and CloudFront, roll out a CSP without breaking production and verify the result."}]},{"type":"callout","attrs":{"variant":"info","title":"In a nutshell"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A CSP with a nonce and ","marks":[{"type":"bold"}]},{"type":"text","text":"strict-dynamic","marks":[{"type":"code"}]},{"type":"text","text":" is the most effective protection against the impact of XSS.","marks":[{"type":"bold"}]},{"type":"text","text":" A script without the random, one-time "},{"type":"text","text":"nonce","marks":[{"type":"code"}]},{"type":"text","text":" from the current response won't run – injected ones included."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Roll out in two steps.","marks":[{"type":"bold"}]},{"type":"text","text":" First "},{"type":"text","text":"Content-Security-Policy-Report-Only","marks":[{"type":"code"}]},{"type":"text","text":" with reports, then enforcement. Otherwise the first forgotten analytics script breaks the page."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"CORS is not protection, it's a relaxation.","marks":[{"type":"bold"}]},{"type":"text","text":" By default the browser blocks reading responses from other domains; CORS says who is allowed to. A list of specific origins, never "},{"type":"text","text":"*","marks":[{"type":"code"}]},{"type":"text","text":" with cookies."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you will build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"An Express module with helmet: a CSP with a nonce generated for every response, "},{"type":"text","text":"strict-dynamic","marks":[{"type":"code"}]},{"type":"text","text":", reporting ("},{"type":"text","text":"report-uri","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"report-to","marks":[{"type":"code"}]},{"type":"text","text":") and a report-only mode, HSTS with preload, "},{"type":"text","text":"frame-ancestors","marks":[{"type":"code"}]},{"type":"text","text":", Referrer-Policy, Permissions-Policy and CORS with an origin list. Plus a server that injects the nonce into the SPA's "},{"type":"text","text":"index.html","marks":[{"type":"code"}]},{"type":"text","text":", a violation report endpoint, a NestJS setup, a CloudFront headers policy in CDK and an interactive CSP header builder. Download the code (5 files) as a ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" Express or NestJS ("},{"type":"text","text":"Express tutorial","marks":[{"type":"link","attrs":{"href":"/en/articles/express"}}]},{"type":"text","text":", "},{"type":"text","text":"NestJS tutorial","marks":[{"type":"link","attrs":{"href":"/en/articles/nestjs"}}]},{"type":"text","text":"), HTTP basics and the browser's same-origin policy. It's worth reading "},{"type":"text","text":"OWASP Top 10 in practice","marks":[{"type":"link","attrs":{"href":"/en/articles/owasp-top-10-in-practice"}}]},{"type":"text","text":" first."}]},{"type":"stats","attrs":{"items":[{"value":"128 bits","label":"of nonce randomness","hint":"new in every response"},{"value":"≥ 1 year","label":"HSTS max-age","hint":"required for the preload list"},{"value":"0","label":"X-XSS-Protection","hint":"the old browser filter – switched off"},{"value":"2 steps","label":"CSP rollout","hint":"report-only, then enforcement"}]}},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  S[Server / CloudFront<br/>sends headers] --> B{Browser}\n  B -->|CSP| C1[blocks scripts without a nonce<br/>and loads from foreign hosts]\n  B -->|frame-ancestors| C2[blocks embedding in a foreign frame]\n  B -->|HSTS| C3[always HTTPS, no click-through]\n  B -->|CORS| C4[lets only listed origins<br/>read the API response]\n  B -->|Permissions-Policy| C5[disables camera, microphone, USB…]\n  C1 -.violation report.-> R[(/csp-reports)]","caption":"Who enforces the headers: the server sends them, the browser applies them"}},{"type":"heading","attrs":{"level":2,"id":"the-header-map"},"content":[{"type":"text","text":"The header map"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Header"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"What it protects against"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Recommended value"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Content-Security-Policy","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the impact of XSS, loading resources from foreign hosts, clickjacking ("},{"type":"text","text":"frame-ancestors","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a strict CSP with a nonce (below)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Strict-Transport-Security","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"traffic interception, downgrade to HTTP"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"max-age=63072000; includeSubDomains; preload","marks":[{"type":"code"}]},{"type":"text","text":" (once prepared)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"X-Content-Type-Options","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"MIME sniffing (e.g. an \"image\" that is really a script)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nosniff","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"X-Frame-Options","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"clickjacking in older browsers"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"DENY","marks":[{"type":"code"}]},{"type":"text","text":" (twin of "},{"type":"text","text":"frame-ancestors 'none'","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Referrer-Policy","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"leaking URL paths and parameters to other sites"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"strict-origin-when-cross-origin","marks":[{"type":"code"}]},{"type":"text","text":" or "},{"type":"text","text":"no-referrer","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Permissions-Policy","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"abuse of browser APIs by scripts and frames"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"camera=(), microphone=(), geolocation=(self)","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Cross-Origin-Opener-Policy","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"access to your window from windows opened by other sites"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"same-origin","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Cross-Origin-Resource-Policy","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"embedding of your resources by foreign sites"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"same-origin","marks":[{"type":"code"}]},{"type":"text","text":" or "},{"type":"text","text":"same-site","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"X-XSS-Protection","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nothing – the old filter was itself a source of vulnerabilities"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"0","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"csp-from-scratch"},"content":[{"type":"text","text":"CSP from scratch"}]},{"type":"paragraph","content":[{"type":"text","text":"A Content Security Policy is a list of directives telling the browser where the page may load scripts, styles, images, connections and frames from. Scripts are what matters most – and there are three approaches:"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A host allowlist","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"script-src 'self' https://cdn.example","marks":[{"type":"code"}]},{"type":"text","text":") – easy but weak: Google's research showed that most such policies can be bypassed through allowed hosts that serve JSONP or old libraries."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A strict CSP with a nonce","marks":[{"type":"bold"}]},{"type":"text","text":": "},{"type":"text","text":"script-src 'nonce-R4nd0m' 'strict-dynamic'","marks":[{"type":"code"}]},{"type":"text","text":". Only a script whose "},{"type":"text","text":"nonce","marks":[{"type":"code"}]},{"type":"text","text":" attribute equals the value from this particular response's header runs, and "},{"type":"text","text":"strict-dynamic","marks":[{"type":"code"}]},{"type":"text","text":" passes trust on to scripts it loads itself. An attacker who injects a "},{"type":"text","text":"<script>","marks":[{"type":"code"}]},{"type":"text","text":" doesn't know the nonce."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A strict CSP with hashes","marks":[{"type":"bold"}]},{"type":"text","text":" – for static pages where you can't inject a nonce per response: "},{"type":"text","text":"script-src 'sha256-…'","marks":[{"type":"code"}]},{"type":"text","text":" for each inline script. A static SPA with no inline scripts (a typical Vite build) can simply use "},{"type":"text","text":"script-src 'self'","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"https:","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"'unsafe-inline'","marks":[{"type":"code"}]},{"type":"text","text":" in a strict CSP are only a fallback for very old browsers – modern ones ignore them when they see a nonce and "},{"type":"text","text":"strict-dynamic","marks":[{"type":"code"}]},{"type":"text","text":". Always add "},{"type":"text","text":"object-src 'none'","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"base-uri 'none'","marks":[{"type":"code"}]},{"type":"text","text":" (without them "},{"type":"text","text":"script-src","marks":[{"type":"code"}]},{"type":"text","text":" can be bypassed) and "},{"type":"text","text":"frame-ancestors","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"playground","attrs":{"template":"vanilla","files":{"/index.html":{"code":"<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"UTF-8\" />\n    <title>CSP builder</title>\n  </head>\n  <body>\n    <form id=\"form\">\n      <fieldset>\n        <legend>Scripts</legend>\n        <label><input type=\"radio\" name=\"scripts\" value=\"strict\" checked /> nonce + 'strict-dynamic' (recommended)</label>\n        <label><input type=\"radio\" name=\"scripts\" value=\"self\" /> 'self' only (static SPA)</label>\n        <label><input type=\"radio\" name=\"scripts\" value=\"unsafe\" /> 'self' 'unsafe-inline' (weak)</label>\n      </fieldset>\n      <label>Extra image hosts <input name=\"img\" value=\"https://media.pierogarnia.example\" /></label>\n      <label>Extra API hosts (connect-src) <input name=\"connect\" placeholder=\"https://api.pierogarnia.example\" /></label>\n      <div class=\"checks\">\n        <label><input type=\"checkbox\" name=\"object\" checked /> object-src 'none'</label>\n        <label><input type=\"checkbox\" name=\"base\" checked /> base-uri 'none'</label>\n        <label><input type=\"checkbox\" name=\"frames\" checked /> frame-ancestors 'none'</label>\n        <label><input type=\"checkbox\" name=\"upgrade\" checked /> upgrade-insecure-requests</label>\n        <label><input type=\"checkbox\" name=\"report\" /> reports (report-to)</label>\n        <label><input type=\"checkbox\" name=\"reportOnly\" /> report only (Report-Only)</label>\n      </div>\n    </form>\n    <h3>Header</h3>\n    <pre id=\"header\"></pre>\n    <h3>Notes</h3>\n    <ul id=\"warnings\"></ul>\n    <script src=\"index.js\"></script>\n  </body>\n</html>"},"/index.js":{"code":"import \"./styles.css\";\n\nconst T = {\n  unsafe: \"'unsafe-inline' lets any injected inline script run – the CSP barely protects against XSS.\",\n  object: \"No object-src 'none' – legacy plugins (<object>, <embed>) can bypass script-src.\",\n  base: \"No base-uri – an injected <base href> can redirect relative script URLs.\",\n  frames: \"No frame-ancestors – the page can be embedded in someone else's frame (clickjacking).\",\n  reportOnly: \"Report-Only mode blocks nothing – it's a rollout stage, not the end state.\",\n  report: \"Without reports you won't know what the policy blocks for real users.\",\n  ok: \"Looks good. Remember: the nonce must be random in every response.\",\n};\n\nconst form = document.getElementById(\"form\");\n\nfunction build() {\n  const f = Object.fromEntries(new FormData(form));\n  const scripts = {\n    strict: \"'nonce-R4nd0mPerResponse' 'strict-dynamic' https: 'unsafe-inline'\",\n    self: \"'self'\",\n    unsafe: \"'self' 'unsafe-inline'\",\n  }[f.scripts];\n\n  const d = [[\"default-src\", \"'self'\"], [\"script-src\", scripts]];\n  d.push([\"img-src\", `'self' data: ${f.img}`.trim()]);\n  d.push([\"connect-src\", `'self' ${f.connect}`.trim()]);\n  if (f.object) d.push([\"object-src\", \"'none'\"]);\n  if (f.base) d.push([\"base-uri\", \"'none'\"]);\n  if (f.frames) d.push([\"frame-ancestors\", \"'none'\"]);\n  if (f.upgrade) d.push([\"upgrade-insecure-requests\"]);\n  if (f.report) d.push([\"report-to\", \"csp\"]);\n\n  const name = f.reportOnly ? \"Content-Security-Policy-Report-Only\" : \"Content-Security-Policy\";\n  document.getElementById(\"header\").textContent = `${name}: ${d.map((x) => x.join(\" \")).join(\"; \")}`;\n\n  const notes = [];\n  if (f.scripts === \"unsafe\") notes.push(T.unsafe);\n  if (!f.object) notes.push(T.object);\n  if (!f.base) notes.push(T.base);\n  if (!f.frames) notes.push(T.frames);\n  if (f.reportOnly) notes.push(T.reportOnly);\n  if (!f.report) notes.push(T.report);\n  const items = (notes.length ? notes : [T.ok]).map((text) => Object.assign(document.createElement(\"li\"), { textContent: text }));\n  document.getElementById(\"warnings\").replaceChildren(...items);\n}\n\nform.addEventListener(\"input\", build);\nbuild();","active":true},"/styles.css":{"code":"body { font-family: system-ui, sans-serif; margin: 0; padding: 16px; color: #1f2328; font-size: 14px; }\nform { display: grid; gap: 10px; max-width: 680px; }\nfieldset { border: 1px solid #d0d7de; border-radius: 8px; display: grid; gap: 4px; }\ninput[name=\"img\"], input[name=\"connect\"] { width: 100%; box-sizing: border-box; padding: 6px; font: 12px ui-monospace, monospace; }\n.checks { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 4px; }\npre { background: #f6f8fa; padding: 10px; border-radius: 8px; white-space: pre-wrap; word-break: break-all; font-size: 12px; }\nh3 { margin: 12px 0 4px; font-size: 14px; }\nli { margin: 4px 0; }"}},"layout":"preview","height":620,"title":"Content-Security-Policy header builder","caption":"Toggle options and read the notes – a starting point, not a replacement for testing in a browser.","editable":true}},{"type":"heading","attrs":{"level":2,"id":"step-1-express-and-helmet"},"content":[{"type":"text","text":"Step 1. Express and helmet"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"npm install helmet cors pino"}]},{"type":"codeGroup","attrs":{"title":"Security headers in Express (helmet, CORS, a nonce for the SPA)"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/security-headers.ts"},"content":[{"type":"text","text":"import type { Express, Response } from 'express';\nimport cors from 'cors';\nimport helmet from 'helmet';\nimport { randomBytes } from 'node:crypto';\n\nexport function securityHeaders(app: Express, opts: { reportOnly?: boolean } = {}) {\n  // A fresh, unpredictable nonce for every HTML response.\n  app.use((_req, res, next) => {\n    res.locals.cspNonce = randomBytes(16).toString('base64');\n    next();\n  });\n\n  app.use(helmet({\n    contentSecurityPolicy: {\n      useDefaults: false,\n      reportOnly: opts.reportOnly, // roll out as Content-Security-Policy-Report-Only first\n      directives: {\n        defaultSrc: [\"'self'\"],\n        // Strict CSP: only scripts carrying our nonce, plus what they load ('strict-dynamic').\n        // https: and 'unsafe-inline' are fallbacks for old browsers – modern ones ignore them.\n        scriptSrc: [(_req, res) => `'nonce-${(res as Response).locals.cspNonce}'`, \"'strict-dynamic'\", 'https:', \"'unsafe-inline'\"],\n        styleSrc: [\"'self'\"],\n        imgSrc: [\"'self'\", 'data:', 'https://media.pierogarnia.example'],\n        connectSrc: [\"'self'\"],\n        fontSrc: [\"'self'\"],\n        objectSrc: [\"'none'\"],\n        baseUri: [\"'none'\"],\n        formAction: [\"'self'\"],\n        frameAncestors: [\"'none'\"], // nobody may frame us (clickjacking)\n        upgradeInsecureRequests: [],\n        reportUri: ['/csp-reports'], // widely supported\n        reportTo: ['csp'], // Reporting API, endpoint defined below\n      },\n    },\n    strictTransportSecurity: { maxAge: 63_072_000, includeSubDomains: true, preload: true }, // 2 years\n    referrerPolicy: { policy: 'strict-origin-when-cross-origin' },\n    xFrameOptions: { action: 'deny' }, // legacy twin of frame-ancestors 'none'\n  }));\n\n  // Headers helmet doesn't set.\n  app.use((_req, res, next) => {\n    res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=(self), usb=()');\n    res.setHeader('Reporting-Endpoints', 'csp=\"https://pierogarnia.example/csp-reports\"');\n    next();\n  });\n\n  // CORS only for the API and only for our own front-ends – never \"*\" with credentials.\n  app.use('/api', cors({\n    origin: ['https://pierogarnia.example', 'https://admin.pierogarnia.example'],\n    credentials: true,\n    methods: ['GET', 'POST', 'PUT', 'DELETE'],\n    allowedHeaders: ['Content-Type', 'Authorization'],\n    maxAge: 600,\n  }));\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/server.ts"},"content":[{"type":"text","text":"import express from 'express';\nimport { readFileSync } from 'node:fs';\nimport { pino } from 'pino';\nimport { securityHeaders } from './security-headers.js';\n\nconst log = pino();\nconst app = express();\nsecurityHeaders(app, { reportOnly: process.env.CSP_REPORT_ONLY === 'true' });\n\n// CSP violation reports: the classic format (report-uri) and the Reporting API (report-to).\napp.post('/csp-reports', express.json({ type: ['application/csp-report', 'application/reports+json'], limit: '20kb' }), (req, res) => {\n  log.warn({ csp: req.body }, 'csp violation');\n  res.sendStatus(204);\n});\n\napp.get('/api/menu', (_req, res) => { res.json([{ name: 'Ruskie', price: 32 }]); });\n\n// The SPA shell: every <script> gets this response's nonce. Don't let a CDN cache this HTML.\nconst indexHtml = readFileSync(new URL('../public/index.html', import.meta.url), 'utf8');\napp.get(/^\\/(?!api\\/).*/, (_req, res) => {\n  res.set('Cache-Control', 'no-store')\n    .type('html')\n    .send(indexHtml.replaceAll('<script', `<script nonce=\"${res.locals.cspNonce}\"`));\n});\n\napp.listen(3006, () => log.info('http://localhost:3006'));"}]},{"type":"codeBlock","attrs":{"language":"html","filename":"public/index.html"},"content":[{"type":"text","text":"<!doctype html>\n<html lang=\"pl\">\n  <head><meta charset=\"utf-8\" /><title>Pierogarnia</title></head>\n  <body><div id=\"root\"></div><script type=\"module\" src=\"/assets/index-4f2a9c.js\"></script></body>\n</html>"}]}]}]},"toc":[{"id":"the-header-map","text":"The header map","level":2,"locked":false},{"id":"csp-from-scratch","text":"CSP from scratch","level":2,"locked":false},{"id":"step-1-express-and-helmet","text":"Step 1. Express and helmet","level":2,"locked":false},{"id":"step-2-rollout-report-only-first","text":"Step 2. Rollout: report-only first","level":2,"locked":true},{"id":"hsts-and-the-preload-list","text":"HSTS and the preload list","level":2,"locked":true},{"id":"frames-referrer-permissions-and-isolation","text":"Frames, referrer, permissions and isolation","level":2,"locked":true},{"id":"cors-done-right","text":"CORS done right","level":2,"locked":true},{"id":"step-3-nestjs","text":"Step 3. NestJS","level":2,"locked":true},{"id":"step-4-cloudfront-for-a-static-spa","text":"Step 4. CloudFront for a static SPA","level":2,"locked":true},{"id":"how-to-test","text":"How to test","level":2,"locked":true},{"id":"common-mistakes","text":"Common mistakes","level":2,"locked":true},{"id":"test-yourself","text":"Test yourself","level":2,"locked":true},{"id":"what-s-next","text":"What's next","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":58,"visibleBlocks":16,"resources":[{"id":"6b0857c53c96f2d34d0b47c3","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=j9QmMEWmcfo","embedUrl":"https://www.youtube-nocookie.com/embed/j9QmMEWmcfo","title":"SSL, TLS, HTTPS Explained","description":"To get better at system design, subscribe to our weekly newsletter: https://bit.ly/3tfAlYD Checkout our bestselling System Design Interview books: Volume 1: https://amzn.to/3Ou7gkd Volume 2: https://amzn.to/3HqGozy ABOUT US: Covering topics and trends in large-scale system design, from the authors…","author":"ByteByteGo","thumbnailUrl":"https://i.ytimg.com/vi/j9QmMEWmcfo/hqdefault.jpg","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["system-design"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2022-12-08T16:30:04.000Z","popularity":91,"verifiedAt":"2026-11-26T10:55:10.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:07.480Z","updatedAt":"2026-11-26T16:01:07.480Z"},{"id":"6b0857c63c96f2d34d0b48dd","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=WvSVSbGo0wI","embedUrl":"https://www.youtube-nocookie.com/embed/WvSVSbGo0wI","title":"HTTP vs HTTPS Explained","description":"To get better at system design, subscribe to our weekly newsletter: https://bit.ly/3tfAlYD Checkout our bestselling System Design Interview books: Volume 1: https://amzn.to/3Ou7gkd Volume 2: https://amzn.to/3HqGozy ABOUT US: Covering topics and trends in large-scale system design, from the authors…","author":"ByteByteGo","thumbnailUrl":"https://i.ytimg.com/vi/WvSVSbGo0wI/hqdefault.jpg","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["system-design"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2026-08-12T15:00:38.000Z","popularity":68,"verifiedAt":"2026-11-26T10:54:48.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857bf3c96f2d34d0b42af","type":"article","provider":"web","url":"https://learn.microsoft.com/en-us/azure/architecture/patterns/gateway-offloading","embedUrl":null,"title":"Gateway Offloading Pattern","description":"Centralize shared capabilities, such as TLS termination and authentication, in a gateway to simplify backend services.","author":"Microsoft Azure Architecture Center","thumbnailUrl":"https://learn.microsoft.com/en-us/media/open-graph-image.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["azure","cloud"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":61,"verifiedAt":"2026-11-26T11:07:50.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857c43c96f2d34d0b4753","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL19543758W","embedUrl":null,"title":"Agile Application Security: Enabling Security in a Continuous Delivery Pipeline","description":"","author":"Laura Bell, Michael Brunton-Spall, Rich Smith, Jim Bird","thumbnailUrl":"https://covers.openlibrary.org/b/id/8510263-L.jpg","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["book","security","devops"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2017-01-01T00:00:00.000Z","popularity":31,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:07.480Z","updatedAt":"2026-11-26T16:01:07.480Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":104,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":90},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":61},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":59},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":46}]}}