Environment Variables and Secrets

Environment variables allow configuration to vary between development, staging, and production. Examples include database URLs, API secrets, OAuth credentials, and public application configuration.

Variables intended only for server execution should not be exposed to browser code. Next.js uses the NEXT_PUBLIC_ prefix for values that are intentionally exposed to client-side JavaScript.

For example, a database password must never be prefixed with NEXT_PUBLIC_. Doing so indicates that the value is intended to become part of the client bundle.

Never Expose Secrets

Anything prefixed with NEXT_PUBLIC_ should be treated as public. Never place database credentials, private signing keys, or service secrets there.

Using Environment Variables
const databaseUrl = process.env.DATABASE_URL;

const publicApiUrl = process.env.NEXT_PUBLIC_API_URL;

if (!databaseUrl) {
  throw new Error('DATABASE_URL is not configured');
}
💡 Server-only secrets can be accessed from server-side code. Public configuration can use the NEXT_PUBLIC_ prefix when browser exposure is intentional.
Key Takeaways
  • Keep private secrets server-only.
  • Use NEXT_PUBLIC_ only for intentionally public values.
  • Production secrets should be supplied through the deployment environment.