Skip to content
← All writing

· 8 min read

Hardening a Next.js Site: CSP, Rate Limits, Bot Traps and a Dependency Audit

  • Security
  • Next.js
  • DevOps
  • Web Security

A portfolio is still an attack surface#

A personal site looks harmless, but it usually has a contact form that sends email, renders content from files, and runs on a framework with its own vulnerabilities. Rebuilding this site this month, I applied the same checklist I would use for a client application. Here is what it covers and why.

1. Security headers#

Every response carries a strict set of headers, configured once in next.config.ts:

const securityHeaders = [
  { key: 'Content-Security-Policy', value: csp },
  { key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' },
  { key: 'X-Content-Type-Options', value: 'nosniff' },
  { key: 'X-Frame-Options', value: 'DENY' },
  { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
  { key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=()' },
  { key: 'Cross-Origin-Opener-Policy', value: 'same-origin' },
];

The Content Security Policy does most of the work:

default-src 'self'; object-src 'none'; base-uri 'self';
frame-ancestors 'none'; form-action 'self' mailto:; connect-src 'self'

Everything loads from the site's own origin: no third-party scripts, no external fonts at runtime (fonts are self-hosted at build time), and eval is blocked in production. Statically generated pages still need inline scripts for hydration, so script-src allows 'unsafe-inline'; a nonce-based policy would remove that but forces every page to render dynamically. For a static site with no third-party scripts and no user-generated HTML, that trade-off is reasonable, and the other directives limit the damage of any injection.

poweredByHeader: false also removes the X-Powered-By header, so the site does not advertise its framework.

2. The contact API: assume every request is hostile#

The contact form posts JSON to a single route handler. Before any email is sent, a request has to pass several checks:

  1. Origin check. The Origin header must be the site itself; Sec-Fetch-Site must be same-origin when present. This blocks cross-site form abuse.
  2. Content type and size. Only application/json, and bodies over 8 KB are rejected before parsing.
  3. Rate limiting. Three messages per IP per 15 minutes. The limiter is in memory and self-cleaning, so on serverless it is per instance; a platform firewall rule is the right complement.
  4. Bot traps. A hidden honeypot field that humans never see, and a minimum fill time: forms submitted in under 2.5 seconds are treated as bots. Both return a fake success so bots learn nothing.
  5. Validation. Length limits on every field and an allow-list for the "intent" value.
  6. Output encoding. Every value is HTML-escaped before it goes into the email, and control characters are stripped from anything that ends up in a header such as the subject line.

The last point is easy to miss. An earlier version inserted the sender's name into the email HTML unescaped, which is a classic HTML-injection bug, just in an inbox instead of a browser.

const escapeHtml = (s: string) =>
  s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
   .replace(/"/g, '&quot;').replace(/'/g, '&#39;');

// Strip CR/LF and other control characters from header values.
const oneLine = (s: string) => s.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim();

API responses are also marked Cache-Control: no-store and X-Robots-Tag: noindex.

3. Rendering Markdown safely#

Blog posts are Markdown files. Even when you write every post yourself, rendering raw HTML from content is a habit worth breaking: content pipelines change, and so do authors. The pipeline is now:

unified()
  .use(remarkParse)
  .use(remarkGfm)          // tables, task lists
  .use(remarkRehype)
  .use(rehypeSanitize)     // drop raw HTML, scripts, event handlers
  .use(rehypeSlug)         // heading ids, added after sanitising
  .use(rehypeAutolinkHeadings)
  .use(rehypeStringify);

The order matters: sanitise first, then add the trusted extras such as heading anchors. Post slugs are also validated against ^[a-z0-9-]+$ before touching the filesystem, which rules out path traversal.

4. Privacy by design#

The site deliberately does not publish a phone number, date of birth or downloadable CV. CV requests go through the contact form or email, so every copy goes to a real person, for a real role, in its current version. The form states that details are only used to reply and are not stored on the site.

5. The dependency audit that mattered most#

Headers and input validation protect against mistakes in my own code. They do nothing against vulnerabilities in the framework itself. Running npm audit during this rebuild flagged the installed Next.js version with several critical advisories, including remote-code-execution issues in the image optimisation and OG image code paths and cache-poisoning issues in static rendering.

The fix was a patch-level upgrade within the same major version, followed by a full rebuild and a re-test of every route. Two takeaways:

  • Audit on every build, not once a year. npm audit --omit=dev belongs in CI, failing the build on high or critical issues in production dependencies.
  • Reduce the surface you do not need. The site now serves only local images through the optimiser, allows no remote image hosts and disables SVG optimisation entirely.

6. Small things that add up#

  • A /.well-known/security.txt file tells researchers where to report issues.
  • Theme preference is the only thing stored in the browser, and failures to read it are handled gracefully.
  • Links that open new tabs use rel="noopener noreferrer".

Checklist#

  • Strict security headers, including CSP and HSTS
  • Every API route: origin check, size limit, rate limit, validation, output encoding
  • Sanitised rendering of any Markdown or rich text
  • No secrets or personal data in the client bundle
  • npm audit in CI, and prompt framework upgrades
  • security.txt with a contact address

None of this is exotic. It is the baseline any public web application should meet, and a personal site is a good place to show that you hold yourself to it.