Skip to the content

Lesson 264 of 296

Input validation, output encoding, security headers and CSP

What you will learn

  • Validating input properly
  • Output encoding as the partner of validation
  • The important HTTP security headers
  • Content Security Policy in depth
  • Setting headers with Helmet
On this page

Input validation

Validate every input from any source you do not control: request bodies, query strings, route parameters, headers, cookies, files, webhooks, messages from queues, third-party API responses.

PrincipleMeaning
Validate on the serverClient-side validation is for user experience only; attackers skip it
Allow-lists over block-listsDefine what is allowed (type, length, format, range, enum); block-lists of "bad characters" always miss something
Validate type, length, format and rangeA quantity is an integer from 1 to 99; an email matches a sensible pattern and is under 254 characters
Reject unknown fieldsPrevents mass assignment (Lesson 259)
Normalise firstTrim, Unicode-normalise (Lesson 33), lowercase emails, then validate
Limit sizesBody size, string length, array length, file size, nesting depth, to prevent denial of service
Validate business rulesThe user owns the address they chose; the discount code is valid for this basket

Schema libraries make this systematic: Zod (Lesson 114), class-validator (Lesson 210), JSON Schema.

Validation is not the fix for injection or XSS on its own: a name like O'Brien is valid input but contains a quote. Valid data must still be parameterised in SQL and encoded in HTML. Validation reduces attack surface; correct handling at each output is what makes data safe.

Security headers

Headers that tell browsers to enable protections:

HeaderExampleProtects against
Strict-Transport-Security (HSTS)max-age=31536000; includeSubDomainsDowngrade to HTTP, cookie theft on public Wi-Fi
Content-Security-PolicySee belowXSS, data injection, clickjacking
X-Content-Type-OptionsnosniffBrowsers guessing file types (a text upload run as script)
X-Frame-Options or CSP frame-ancestorsDENY / 'none'Clickjacking: your page in an invisible iframe tricking clicks
Referrer-Policystrict-origin-when-cross-originLeaking full URLs (with tokens or IDs) to other sites
Permissions-Policycamera=(), microphone=(), geolocation=()Features used by injected or third-party code
Cross-Origin-Opener-Policysame-originOther windows getting a handle to yours
Cookie flagsHttpOnly; Secure; SameSite=Lax (Lesson 200)Token theft and CSRF

X-XSS-Protection is obsolete; modern browsers removed the feature, and the recommended value is 0 or omitting it. Use CSP instead.

Content Security Policy (CSP)

CSP tells the browser which sources of scripts, styles, images, connections and frames are allowed. Anything else is blocked, so even if an attacker injects <script> or an inline event handler, it does not run.

Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-r4nd0m123';
  style-src 'self';
  img-src 'self' data: https://images.jobprep.example;
  connect-src 'self' https://api.jobprep.example;
  font-src 'self';
  object-src 'none';
  base-uri 'self';
  form-action 'self';
  frame-ancestors 'none';
  upgrade-insecure-requests
DirectiveControls
default-srcFallback for any type not listed
script-srcWhere JavaScript can come from
style-src, img-src, font-src, connect-src (fetch, WebSocket), frame-src, media-srcOther resource types
object-src 'none'Blocks old plugins
base-uri 'self'Stops <base> tag hijacking of relative URLs
form-actionWhere forms may submit
frame-ancestorsWho may frame your page (modern replacement for X-Frame-Options)

Inline scripts: a strict CSP blocks inline <script> blocks and onclick= attributes, which is where most XSS lives. To allow your own inline scripts, use a nonce: a random value generated for each response, put in the header ('nonce-abc') and on your script tags (<script nonce="abc">). Attackers cannot guess it. Avoid 'unsafe-inline' and 'unsafe-eval' for scripts, which defeat the protection. 'strict-dynamic' lets scripts loaded by a trusted (nonced) script run too, which helps with bundlers and tag loaders.

Rolling out CSP safely: start with Content-Security-Policy-Report-Only plus a reporting endpoint, fix violations, then enforce. Next.js and other frameworks have documented ways to add nonces per request.

Setting headers with Helmet

In Express, the helmet package sets sensible defaults for most of these headers:

TypeScript
import express from "express";
import helmet from "helmet";

export function buildSecureApp() {
  const app = express();
  app.disable("x-powered-by");
  app.use(
    helmet({
      contentSecurityPolicy: {
        directives: {
          defaultSrc: ["'self'"],
          scriptSrc: ["'self'"],
          objectSrc: ["'none'"],
          frameAncestors: ["'none'"],
          upgradeInsecureRequests: []
        }
      },
      strictTransportSecurity: { maxAge: 31536000, includeSubDomains: true }
    })
  );
  app.use(express.json({ limit: "100kb" }));
  app.get("/", (_req, res) => {
    res.send("ok");
  });
  return app;
}

Tested: responses included Content-Security-Policy with these directives merged with Helmet's defaults (so it also contained, for example, script-src-attr 'none' and style-src 'self' https: 'unsafe-inline'; set useDefaults: false or override styleSrc if you want a stricter style policy), Strict-Transport-Security: max-age=31536000; includeSubDomains, X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN, Referrer-Policy: no-referrer, X-XSS-Protection: 0 (the recommended "off" value), and no X-Powered-By header. A JSON body over 100 KB was rejected with 413. In NestJS, app.use(helmet()) in main.ts; behind nginx, headers can also be set there (Lesson 248).

Check your headers with browser DevTools or online scanners such as securityheaders.com and Mozilla's HTTP Observatory.

How to say it in an interview

"I validate every external input on the server with schemas, using allow-lists for type, length, format and range, rejecting unknown fields, normalising first and limiting sizes, but I treat validation as reducing attack surface, while parameterisation and output encoding are what make data safe in each context. I set security headers centrally with Helmet or the proxy: HSTS, a strict Content Security Policy with per-response nonces instead of unsafe-inline, nosniff, frame-ancestors none against clickjacking, a referrer policy and a permissions policy, rolling CSP out in report-only mode first. X-XSS-Protection is obsolete."

Key words

WordMeaning
Input validationChecking that input matches what is allowed
Allow-list / block-listPermit known good / reject known bad
HSTSForces HTTPS for a domain
Content Security PolicyBrowser rules for which content sources may load and run
NonceA random per-response value allowing specific inline scripts
ClickjackingTricking clicks through an invisible framed page
HelmetExpress middleware that sets security headers

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.