How to Set Up Environment Variables in a Next.js App (Best Practices & Guide)

Learn how to properly set up and manage environment variables in a Next.js app. This guide covers best practices for security, .env file configuration, loading variables in client and server components, and troubleshooting common issues.


Why we need the environment variables?

Some of benefits:

  • Flexible for Multiple Environments – Easily switch between development, staging, and production configurations without changing code.

  • Improved Security – Keeps API keys, database credentials, and sensitive data out of the source code, reducing security risks.

  • Easy Deployment – Environment variables allow smooth deployment across different platforms (Vercel, AWS, Docker, etc.) without modifying the codebase.

  • Better Maintainability – Centralized configuration management makes it easier to update settings without modifying multiple files.

  • Customizable Builds – Define different settings for feature flags, third-party integrations, or logging levels based on the environment.

Seamless CI/CD Integration – Easily inject variables into GitHub Actions, Vercel, or other CI/CD pipelines for automated deployment workflows.

Quick start

Now we will go quick through how to handle the environment variables in Next.js.

Create a .env file

Create a .env file on the root of source code folder to store all env variables:

json
BRAND_NAME="xxxxxxxxxxxxxxxxxxxxxxxxxxx" MONGODB_DB_NAME="xxxxxxxxxxxxxxxxxxxxxxxxxxx" MONGODB_DB_USERNAME="xxxxxxxxxxxxxxxxxxxxxxxxxxx" MONGODB_DB_PASSWORD="xxxxxxxxxxxxxxxxxxxxxxxxxxx" MONGODB_DB_CLUSTER_URL="xxxxxxxxxxxxxxxxxxxxxxxxxxx" NEXTAUTH_SECRET="xxxxxxxxxxxxxxxxxxxxxxxxxxx" NEXTAUTH_DEBUG="xxxxxxxxxxxxxxxxxxxxxxxxxxx" NEXTAUTH_URL="xxxxxxxxxxxxxxxxxxxxxxxxxxx" VERIFICATION_CODE_EXPIRE_TIME="xxxxxxxxxxxxxxxxxxxxxxxxxxx" HUBSPOT_ID="xxxxxxxxxxxxxxxxxxxxxxxxxxx"

Add the config file

Add config.ts file on the root of folder and paste this code below:

js
/* eslint-disable import/no-anonymous-default-export */ export default { BRAND_NAME: process.env.BRAND_NAME || "Build2EarnFast", // Mongo DB MONGODB_DB: { NAME: process.env.MONGODB_DB_NAME, USERNAME: process.env.MONGODB_DB_USERNAME, PASSWORD: process.env.MONGODB_DB_PASSWORD, CLUSTER_URL: process.env.MONGODB_DB_CLUSTER_URL, }, // NextAuth NEXTAUTH: { DEBUG: process.env.NEXTAUTH_DEBUG === "true", SECRET: process.env.NEXTAUTH_SECRET, URL: process.env.NEXTAUTH_URL || "http://localhost:3000", }, // Hubspot HUBSPOT: { ID: process.env.HUBSPOT_ID, }, };

How to use

Now you can use all the variables on your code:

jsx
import config from "@/config"; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html> <body className="flex h-full flex-col"> ... <Script src={`https://js.hs-scripts.com/${config.HUBSPOT.ID}.js`} strategy="lazyOnload" defer /> </body> </html> ); }