In Next.js, you can set up environment variables for both the development and production environments. Environment variables are often used to store sensitive information or configuration settings that can vary between development and production environments.
Here’s a step-by-step guide on how to set up environment variables dynamically in Next.js:
Development Environment:
- Create a
.env.local
file:- In the root of your Next.js project, create a file named
.env.local
. - Add your development environment variables to this file. For example:
- In the root of your Next.js project, create a file named
NEXT_PUBLIC_API_KEY=your-development-api-key
- The
NEXT_PUBLIC_
prefix is used to make the variable accessible on the client-side.
Access Environment Variables in Code:
- You can access these variables in your code using
process.env.NEXT_PUBLIC_API_KEY
. For example:
const apiKey = process.env.NEXT_PUBLIC_API_KEY;
console.log(apiKey);
Production Environment:
- Vercel and Serverless Deployments:
- If you are deploying your Next.js app to Vercel or using a serverless deployment, you can set environment variables directly in the Vercel dashboard.
- Go to your Vercel dashboard, navigate to your project, and go to the “Settings” tab.
- Under the “Environment Variables” section, add your production variables.
- Traditional Deployments:
- For traditional deployments, create a
.env.production
file for production environment variables. - Add your production variables to this file:
- For traditional deployments, create a
NEXT_PUBLIC_API_KEY=your-production-api-key
These variables will be used when you deploy your application to a production environment.
Dynamic Variable Based on Environment:
If you want to dynamically set variables based on the environment, you can create a JavaScript file that exports different values based on the NODE_ENV
. For example, create a file named config.js
:
const isProduction = process.env.NODE_ENV === 'production';
const config = {
API_KEY: isProduction ? process.env.NEXT_PUBLIC_API_KEY_PROD : process.env.NEXT_PUBLIC_API_KEY_DEV,
// Other configuration variables
};
export default config;
In this example, you would set NEXT_PUBLIC_API_KEY_PROD
and NEXT_PUBLIC_API_KEY_DEV
in your environment files accordingly.
Remember to keep sensitive information, such as API keys, secure. Avoid committing them to version control systems, and use environment variables to keep them separate from your code.