Q35: How are Environment Variables handled in the Pages Router?

Environment variables defined in .env.local are private to the server runtime by default. To expose environment variables to the browser client, prefix their names with NEXT_PUBLIC_ (e.g. NEXT_PUBLIC_API_URL).

Accessing Environment Variables
// Available ONLY on the server (getStaticProps / getServerSideProps / API routes)
const dbPassword = process.env.DB_PASSWORD;

// Inlined into client JavaScript bundles (accessible in React components)
const publicUrl = process.env.NEXT_PUBLIC_ANALYTICS_KEY;
💡 NEXT_PUBLIC_ variables are replaced with their inline literal values during build compilation.
Key Takeaways
  • Server-only by default (process.env.DB_PASS).
  • Prefix with NEXT_PUBLIC_ to inline variables into client JavaScript bundles.
Knowledge Check

What happens if you reference process.env.SECRET_KEY (without NEXT_PUBLIC_) inside a client React component function?