DEV Community

Deepak Kumar
Deepak Kumar

Posted on

Best practises for loading environment variable in NextJS application

How to load environment variables in a NextJS application ?

  • First, create a new .env file in the root directory of your Next.js application. Add the environment variables you want to use in your application in the format ENV_VARIABLE_NAME=env_value.

For example:

API_URL=https://example.com/api
API_KEY=abc123
Enter fullscreen mode Exit fullscreen mode
  • Next, please install the dotenv npm package dependency:
npm install --save-dev dotenv
Enter fullscreen mode Exit fullscreen mode
  • Now, in your Next.js application, create a new file named next.config.js in the root directory. This file will be used to load the environment variables from the .env file.
const dotenv = require('dotenv');
dotenv.config();

module.exports = {
  // Your Next.js configuration 
};

Enter fullscreen mode Exit fullscreen mode
  • Now you can use the environment variables in your nextjs project. For example, to access the API_URL environment variable:
const apiUrl = process.env.API_URL;
console.log(apiUrl); // prints https://example.com/api
Enter fullscreen mode Exit fullscreen mode

For more approach on how to load env file in nextjs application, you can refer this page - Link

Things to keep in mind when working with env files.

  • You should never commit your .env file to git. Env secrets generally contains sensitive information such as API keys and passwords, database secrets.
  • You should add it to your .gitignore file to prevent it from being committed.

Here are the best practices you can consider for setting env secrets for your application :

  1. Use a secure method to store your secrets:

    • Avoid storing your secrets in plain text files or hardcoding them in your code. Instead, use a secure method such as environment variables, key vaults, or configuration files.
  2. Limit access to your secrets

    • Restrict access to your secrets to only those who need them. Use access controls and permissions to ensure that only authorized users can access your secrets.
  3. Avoid storing sensitive data in plain text

    • If you need to store sensitive data such as passwords or API keys, encrypt them before storing them in your secrets store.
  4. Rotate your secrets regularly:

    • Regularly rotating your secrets (e.g. passwords, api secret keys) helps to prevent unauthorised access and improve security.
    • Set up automated processes to rotate your secrets at regular intervals.
  5. Use strong, complex passwords:

    • When creating passwords for your secrets, use strong, complex passwords that are difficult to guess.
    • Use a password manager to generate and store passwords securely.
  6. Use a version control system:

    • You can use a version control system to manage changes to your secrets, and keep a record of who made changes and when.

Top comments (0)