
Environment Variables in NextJS
🌍 Environment Variables in Next.js
Environment variables in Next.js allow you to securely store sensitive information like API keys, database credentials, and configuration settings.
📌 1. Creating Environment Variables
Next.js uses .env
files to manage environment variables. There are three types:
.env.local
→ Used for local development (ignored by Git)..env.development
→ Used only in development mode..env.production
→ Used only in production mode.
Example .env.local
file:
NEXT_PUBLIC_API_URL=https://api.example.comDATABASE_SECRET=mysecretkey
📌 2. Using Environment Variables in Next.js
🔹 Server-Side Usage (Secure)
For sensitive variables (not exposed to the client), use:
export default function handler(req, res) { res.json({ secret: process.env.DATABASE_SECRET });}
✅ Safe, as it only runs on the server
🔹 Client-Side Usage (Public)
For variables that should be accessible in the browser, prefix them with NEXT_PUBLIC_
:
const apiUrl = process.env.NEXT_PUBLIC_API_URL;console.log(apiUrl); // Accessible in the client
✅ Only variables with NEXT_PUBLIC_
are exposed to the browser
📌 3. Environment Variables & Next.js Build
Changes to
.env.local
require restarting the server (npm run dev
).Variables are embedded at build time in
getStaticProps
andgetStaticPaths
.
Example:
export async function getStaticProps() { return { props: { apiUrl: process.env.NEXT_PUBLIC_API_URL } };}
📌 4. Best Practices
✔️ Never commit .env.local
→ Add it to .gitignore
.
✔️ Use NEXT_PUBLIC_
only for non-sensitive data.
✔️ Restart the server after making changes to .env
files.