Next.js Security outlines best practices for protecting web applications against Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and unauthorized data access.
React and Next.js automatically sanitize JSX string interpolations to prevent basic XSS attacks. However, extra security configurations are required for production applications.
Configure strict CSP headers inside middleware.ts to control which script sources can execute in your application:
// middleware.ts
import { NextResponse } from 'next/server';
export function middleware() {
const response = NextResponse.next();
// Define Content Security Policy directives
const cspHeader = `
default-src 'self';
script-src 'self' 'unsafe-inline' https://cdn.example.com;
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data: https:;
font-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
`;
// Set security response headers
response.headers.set('Content-Security-Policy', cspHeader.replace(/\s{2,}/g, ' ').trim());
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
return response;
}
Next.js keeps environment variables private on the server by default. Only variables prefixed with NEXT_PUBLIC_ are exposed to client JavaScript bundles:
# Private Server-only variable (Safe for DB credentials)
DATABASE_SECRET_KEY="secret_key_12345"
# Public Client-accessible variable (Exposed to browser!)
NEXT_PUBLIC_ANALYTICS_ID="GA-99999"
dangerouslySetInnerHTML)Avoid using dangerouslySetInnerHTML unless input strings have been sanitized using HTML sanitizer libraries like DOMPurify:
// app/components/SafeContent.tsx
import DOMPurify from judge-sanitizer; // Utility sanitizer
export default function SafeContent({ rawHtml }: { rawHtml: string }) {
// Always sanitize untrusted HTML before rendering!
const cleanHtml = DOMPurify.sanitize(rawHtml);
return <div dangerouslySetInnerHTML={{ __html: cleanHtml }} />;
}
NEXT_PUBLIC_: Double-check that API secrets are never prefixed with NEXT_PUBLIC_.Securing Next.js applications involves configuring HTTP security headers, keeping environment variables private, and sanitizing user inputs.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With