Environment variables are a fundamental aspect of modern web development, allowing developers to configure applications based on the environment they are running in (development, testing, production, etc.).
- Environment variables provide a flexible and secure way to manage configuration settings for your application.
- These settings can include API endpoints, database connection strings, feature flags, and more.
- By using environment variables, you can ensure that sensitive information is not hardcoded into your application's source code, enhancing both security and maintainability.
Setting Up Environment Variables in Next.js
Next.js supports loading environment variables from .env files, which follow a specific naming convention to differentiate between different environments.
Syntax:
// Filename .env
NEXT_PUBLIC_API_URL=https://api.gfg.com
DATABASE_URL=postgres://user:password@localhost:5001/dname
Note: The name of variables to be accessed from the client side / Public variables must be initialized with NEXT_PUBLIC_
Below are some naming conventions according to the requirement of env variables in the application
- .env: Loaded for all environments.
- .env.local: Loaded for all environments, but not included in version control.
- .env.development: Loaded in development environment.
- .env.production: Loaded in production environment.
- .env.test: Loaded in test environment.
Accessing Environment Variables
The environment variables can be accessed inside the application using the process.env prefix.
Syntax:
inside js/ts files:
const API = process.env.NEXT_PUBLIC_API_URL
const DB = prosess.env.DATABASE_URL
inside configuration files:
// Filename - next.config.js
module.exports= {
env: {
apiKey: process.env.API_KEY,
},
}
Steps to Implement Environment Variables in Next.js
Follow the below steps to set up the environment variable in Next.js application.
Step 1: To create a new Next.js App, run the below command in your terminal:
npx create-next-app GFGStep 2: After creating your project folder (i.e. GFG ), move to it by using the following command: