Environment Variables
⏱ Estimated reading time: 2 min
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).
1. Creating Environment Variables
Create a .env.local file in the root of your project:
Notes:
-
.env.localis ignored by Git automatically. -
Do not commit secrets to version control.
2. Variable Naming Conventions
| Prefix | Description |
|---|---|
NEXT_PUBLIC_ | Accessible in client-side code |
| No prefix | Accessible only on server-side |
Example
-
NEXT_PUBLIC_BASE_URL→ usable in browser and server -
API_SECRET_KEY→ server-only
3. Using Environment Variables in Next.js
Server-Side (App Router / API Routes)
Client-Side (Browser)
Only variables with
NEXT_PUBLIC_are available on the client.
4. Environment-Specific Files
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.
5. Example: Using API URL
6. Reload Required
If you add or change environment variables, you must restart the development server for changes to take effect.
7. Best Practices
-
Never expose sensitive secrets to the client
-
Use
NEXT_PUBLIC_prefix only for non-sensitive values -
Store secrets in
.env.localand.env.production -
Avoid committing
.env.localto version control
Conclusion
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.
Register Now
Share this Post
← Back to Tutorials