3 min read
ā¢Question 10 of 47easyHow 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 onlyServer-Side Variables
$ terminalBash
# .env
DATABASE_URL=postgresql://...
API_SECRET=my-secret-keycode.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-XXXXXcode.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',
},
};