#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
•Question 10 of 47easy

How to use environment variables in Next.js?

Managing environment variables.

What You'll Learn

  • Server vs client variables
  • .env files
  • Runtime configuration

Environment Files

code.jsJavaScript
.env                # All environments
.env.local          # Local overrides (gitignored)
.env.development    # Development only
.env.production     # Production only

Server-Side Variables

$ terminalBash
# .env
DATABASE_URL=postgresql://...
API_SECRET=my-secret-key
code.txtTSX
// Only accessible on server
const db = new Database(process.env.DATABASE_URL);

Client-Side Variables

$ terminalBash
# Must prefix with NEXT_PUBLIC_
NEXT_PUBLIC_API_URL=https://api.example.com
NEXT_PUBLIC_GA_ID=UA-XXXXX
code.txtTSX
// Accessible in browser
const apiUrl = process.env.NEXT_PUBLIC_API_URL;

Type Safety

code.txtTSX
// env.d.ts
declare namespace NodeJS {
  interface ProcessEnv {
    DATABASE_URL: string;
    NEXT_PUBLIC_API_URL: string;
  }
}

Runtime Config

code.txtTSX
// next.config.js
module.exports = {
  env: {
    customKey: 'my-value',
  },
};