乐闻世界logo
搜索文章和话题

How to use different env files with nextjs?

3个答案

1
2
3

In Next.js, managing configurations for different environments (development, testing, production) can be achieved by utilizing different .env files. Next.js automatically loads environment variables and follows specific rules for loading .env files tailored to distinct environments. Here are the steps to implement this:

  1. Create .env files: In the root directory of your Next.js project, create the following .env files to define environment variables:

    • .env.local: This file overrides variables in other .env files and is not tracked by Git version control, typically used for sensitive information.
    • .env.development: Loaded exclusively when running next dev (i.e., in development mode).
    • .env.production: Loaded exclusively when running next start (i.e., in production mode).
    • .env.test: Used during automated testing; manual configuration of the loading mechanism is required.
    • .env: The default environment variables file, loaded in all environments but overridden by specific environment files.
  2. Set environment variables: In each .env file, define necessary environment variables in the following format:

    plaintext
    # .env.local API_SECRET=local_secret # .env.development API_URL=https://dev.example.com/api # .env.production API_URL=https://prod.example.com/api
  3. Load environment variables: Next.js automatically handles loading these variables without additional configuration. Access them in your code using process.env:

    javascript
    console.log(process.env.API_URL); // Output reflects the value from the corresponding .env file based on the current environment
  4. Use environment variables: Directly leverage process.env in Next.js pages, API routes, getServerSideProps, or getStaticProps for server-side code.

  5. Expose environment variables to the browser: To use environment variables in the browser, prefix the variable name with NEXT_PUBLIC_:

    plaintext
    NEXT_PUBLIC_ANALYTICS_ID=xyz123

    This enables safe usage in client-side JavaScript:

    javascript
    console.log(process.env.NEXT_PUBLIC_ANALYTICS_ID); // Accessible on the client side

Example:

Suppose you have an API URL that differs between development and production environments. Configure it as follows:

  • In .env.development file:

    plaintext
    API_URL=https://dev.api.example.com
  • In .env.production file:

    plaintext
    API_URL=https://api.example.com

When running next dev in development mode, process.env.API_URL will be https://dev.api.example.com. When running next start in production mode, the environment variable will be https://api.example.com.

By implementing this approach, you can load environment variables based on the current runtime environment without modifying your code, which enhances project configuration management and code maintainability.

2024年6月29日 12:07 回复

For anyone interested in using .yml files to easily manage environment variables, here's how I do it.

Install the yenv plugin in devDependencies.

Add the following configuration in next.config.js:

javascript
const path = require("path"); const yenv = require("yenv"); const { PHASE_DEVELOPMENT_SERVER } = require("next/constants"); module.exports = (phase) => { const isDev = phase === PHASE_DEVELOPMENT_SERVER; const NEXT_ENV = isDev ? "development" : process.env.APP_ENV; const rawEnv = yenv(path.resolve(".env.yml"), { raw: true, env: NEXT_ENV }); return { ...some other config, env: getEnvVars(rawEnv, isDev).raw, compress: true, }; }; function getEnvVars(rawEnv, dev) { const NEXT_PUBLIC = /^NEXT_PUBLIC_/i; const raw = Object.keys(rawEnv) .filter((key) => NEXT_PUBLIC.test(key)) .reduce((env, key) => { env[key] = rawEnv[key]; return env; }, {}); // Stringify all values so we can feed into Webpack DefinePlugin const stringified = { "process.env": Object.keys(raw).reduce((env, key) => { env[key] = JSON.stringify(raw[key]); return env; }, {}), }; return { raw, stringified }; }

Simply add different build commands based on the environment in your package.json scripts.

json
"scripts": { "dev": "node server.js", "build:production": "APP_ENV=production next build", "build:staging": "APP_ENV=staging next build", "start": "NODE_ENV=production node server.js" }

Now you can call npm run build:production to configure the production environment variables and npm run build:staging for staging environment variables.

This provides the benefit of having any number of environments tailored to your use case. You only need to add one build command and update the .env.yml environment variables.

2024年6月29日 12:07 回复

Here are two ways to manage different .env files in Next.js:

1. Using the env-cmd package

Specify the path to the environment file in your scripts, for example:

shell
"scripts": { "start": "env-cmd path/to/prod/env/file next start", "start:dev": "env-cmd path/to/prod/env/file next dev", "build:dev": "env-cmd path/to/dev/env/file next build", "build:test": "env-cmd path/to/test/env/file next build", "build:stage": "env-cmd path/to/stage/env/file next build", "build": "env-cmd path/to/stage/prod/file next build" },

2. Using the dotenv package

Add the following to your next.config.js file:

shell
require("dotenv").config({ path: `${process.env.ENVIRONMENT}` }); module.exports = { // your configs }

Specify the environment variable in your scripts, for example:

shell
"scripts": { "start": "ENVIRONMENT=path/to/prod/env/file next start", "start:dev": "ENVIRONMENT=path/to/dev/env/file next dev", "build:dev": "ENVIRONMENT=path/to/dev/env/file next build", "build:test": "ENVIRONMENT=path/to/test/env/file next build", "build:stage": "ENVIRONMENT=path/to/stage/env/file next build", "build": "ENVIRONMENT=path/to/stage/prod/file next build" },

Note: Do not place your .env* files in the root folder, as Next.js will automatically select from your .env* files and only supports production and development stages. Thus, it will ignore other .env.my-stage files.

2024年6月29日 12:07 回复

你的答案