Next.js Developer interview question · Most asked

How do environment variables work in Next.js, and what is exposed to the browser?

Summary

Variables in .env* files are available on the server via process.env. Only variables prefixed with NEXT_PUBLIC_ are inlined into the client bundle at build time, so never put secrets in NEXT_PUBLIC_ variables.

Longer Answer

NEXT_PUBLIC_ values are baked in at build time, so changing them requires a rebuild (unless you read them at runtime on the server and pass them down). Use the server-only package to make modules containing secrets fail the build if imported into client code.

Key Points

  • process.env on the server
  • NEXT_PUBLIC_* inlined in client bundle at build
  • Never expose secrets with that prefix
  • server-only guards secret modules

More most-asked Next.js Developer questions

← All Next.js Developer questions