Environment Variables

📘 Next.js 👁 32 views 📅 Dec 22, 2025
⏱ 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:

NEXT_PUBLIC_API_URL=https://api.example.com DATABASE_URL=mongodb+srv://user:password@cluster.mongodb.net/mydb NEXTAUTH_SECRET=your_secret_key

Notes:

  • .env.local is ignored by Git automatically.

  • Do not commit secrets to version control.


2. Variable Naming Conventions

PrefixDescription
NEXT_PUBLIC_Accessible in client-side code
No prefixAccessible only on server-side

Example

NEXT_PUBLIC_BASE_URL=http://localhost:3000 API_SECRET_KEY=abcd1234
  • 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)

export async function GET() { const secret = process.env.API_SECRET_KEY; return new Response(JSON.stringify({ secret })); }

Client-Side (Browser)

export default function Home() { return <p>API URL: {process.env.NEXT_PUBLIC_API_URL}</p>; }

Only variables with NEXT_PUBLIC_ are available on the client.


4. Environment-Specific Files

Next.js supports multiple .env files:

FileUsage
.env.localLocal development, ignored by Git
.env.developmentDevelopment environment
.env.productionProduction environment
.env.testTest environment

Variables are merged in the following order: local → environment-specific → .env.


5. Example: Using API URL

const apiUrl = process.env.NEXT_PUBLIC_API_URL; export async function fetchPosts() { const res = await fetch(`${apiUrl}/posts`); return res.json(); }

6. Reload Required

If you add or change environment variables, you must restart the development server for changes to take effect.

npm run dev

7. Best Practices

  • 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


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.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes