Menu

Security Essentials

Lesson 4: Security Essentials

What are the everyday security habits?

Area Practice
Secrets Store in environment variables; never prefix secrets with NEXT_PUBLIC_
Server code Mark data and secret-handling modules with import 'server-only'
Input Validate every action and route input with a schema
Output Avoid dangerouslySetInnerHTML; sanitise if you must render HTML
Headers Send security headers such as CSP, HSTS, and X-Content-Type-Options
Dependencies Update Next.js promptly when security releases are announced

Example: environment variables

# .env.local (never committed)
DATABASE_URL="postgresql://..."
BETTER_AUTH_SECRET="long-random-string"
NEXT_PUBLIC_SITE_URL="https://learnhub.in"   # Safe: visible in the browser
Variable Available in Bundled into browser JS?
DATABASE_URL Server only No
NEXT_PUBLIC_SITE_URL Server and client Yes, inlined at build time

Example: security headers

// next.config.ts
const securityHeaders = [
  { key: 'X-Content-Type-Options', value: 'nosniff' },
  { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
  { key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' },
  { key: 'X-Frame-Options', value: 'DENY' },
];

const nextConfig: NextConfig = {
  async headers() {
    return [{ source: '/(.*)', headers: securityHeaders }];
  },
};

A Content Security Policy (CSP) with nonces can be added in proxy.ts; see the Next.js CSP guide for the full pattern.

How Next.js helps

  • Server Actions compare the request's Origin and Host headers to block cross-site calls, and are only callable through POST.
  • Action IDs are unguessable and unused actions are removed from the build.
  • React escapes text in JSX automatically, which prevents most XSS.
  • Next.js publishes scheduled security releases. Watch the Next.js blog or GitHub advisories and upgrade when one is announced.

Common mistakes

Mistake Effect Fix
NEXT_PUBLIC_ on an API secret Secret visible to everyone Remove the prefix; call the API from the server
Rendering user content with dangerouslySetInnerHTML Stored XSS Render as text, or sanitise with a library such as DOMPurify
Staying on an old minor version for months Known vulnerabilities stay open Schedule regular updates; patch immediately for critical advisories
Logging full request bodies Passwords and tokens end up in logs Redact sensitive fields

Key takeaways

  • Secrets stay on the server; only NEXT_PUBLIC_ values reach the browser.
  • Validate input, escape output, send security headers, and keep Next.js up to date.

Try it: Audit LearnHub's environment variables and next.config.ts: remove any NEXT_PUBLIC_ secret, add the security headers above, and check them in the browser's Network tab.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details