Next.js app security: what to check
Next.js apps run code in two places: on the server and in the browser. Most security problems a survey finds come from something crossing that line by mistake, such as a secret used in a client component.
Next.js sends few security headers by default, so they are usually added in next.config.js or by the host.
What to check on Next.js
-
Are secret API keys exposed in your front end?
Secrets must stay in server code: Route Handlers, Server Actions or server components.
-
Are your security headers set?
Add them with the headers() function in next.config.js, for the source "/(.*)".
-
Are your cookies protected?
Session cookies set by your auth library need Secure, HttpOnly and SameSite.
-
Does your server announce its software versions?
Next.js can announce itself in an X-Powered-By header; the poweredByHeader option turns it off.
-
Are your JavaScript libraries out of date?
Front-end packages with known vulnerabilities show up in the code the browser receives.
Where settings go on Next.js
- Security headers
- In Next.js, return the header from the headers() function in next.config.js (or next.config.ts) for the source "/(.*)"; on Vercel you can also add it under "headers" in vercel.json.
- Secret keys
- Variables starting with NEXT_PUBLIC_ are built into the public bundle. Rename the variable without that prefix and use it only in server code: a Route Handler, a Server Action or a server component.
Common questions
Are environment variables in Next.js private?
Only those without the NEXT_PUBLIC_ prefix, and only while they are used in server code.
Does Next.js add security headers for me?
Not the main ones, such as Content-Security-Policy. Add them in next.config.js or at your host.