Environment variables are used to store sensitive data or configuration values outside your code. In Next.js, they help you keep secrets like API keys, database URLs, and authentication credentials safe and configurable across different environments (development, staging, production).
Create a .env.local file in the root of your project:
Notes:
.env.local is ignored by Git automatically.
Do not commit secrets to version control.
| Prefix | Description |
|---|---|
NEXT_PUBLIC_ | Accessible in client-side code |
| No prefix | Accessible only on server-side |
NEXT_PUBLIC_BASE_URL → usable in browser and server
API_SECRET_KEY → server-only
Only variables with
NEXT_PUBLIC_are available on the client.
Next.js supports multiple .env files:
| File | Usage |
|---|---|
.env.local | Local development, ignored by Git |
.env.development | Development environment |
.env.production | Production environment |
.env.test | Test environment |
Variables are merged in the following order: local → environment-specific →
.env.
If you add or change environment variables, you must restart the development server for changes to take effect.
Never expose sensitive secrets to the client
Use NEXT_PUBLIC_ prefix only for non-sensitive values
Store secrets in .env.local and .env.production
Avoid committing .env.local to version control
Environment variables in Next.js make your application configurable, secure, and environment-aware. Using server-side and client-side variables correctly ensures security and flexibility in your projects.
Take quizzes related to this topic and see where you stand!
Start Quiz Now