skip to Main Content

What are the best practices for accessing environment variables in a production build when it’s generally considered bad practice to push .env files to the production repo?

I’m currently working on a project where I need to access environment variables (such as API keys and database credentials), but I’m not sure how to do this without including the .env files in the production repository.

If I push them, then that leaves me open for an attack if someone accesses the repo. But if I don’t, then the resulting code that is compiled won’t have access to those necessary credentials.

What are some best practices for handling this situation? Are there any tools or methods that can help with accessing environment variables in a production build without pushing them directly to production?

const connection = {
    host: "127.0.0.1",
    // All of these will result in undefined
    user: process.env.DB_PROD_USER,
    pass: process.env.DB_PROD_PASS,
    table: process.env.DB_PROD_TABLE
};

3

Answers


  1. Yes. I did this few days ago and I think it’s a better solution.

    const baseURL = process.env[process.env.NODE_ENV];
    

    This is my object contain different url:

    env: {
      development: "your_development_url",
      production: "your_production_url",
    },
    
    Login or Signup to reply.
  2. You use actual environment variables, defined in the production environment itself (not the repo or the code). How you do that depends on the environment.

    If you’re running an actual server yourself (physical or VPS), you’d have them in the environment settings for the process that will run the code or the user account that the code will be running under. (Ideally using a tool that allows you to have those encrypted at rest and only decrypted into memory when running.)

    If you’re using a hosted solution, it will have a way to provide the environment variables that should be available to your code when the environment runs. Here’s an example from render.com’s configuration page:

    web UI showing fields for defining environment variables in render.com

    Here’s one from Deno Deploy:

    web UI showing fields for defining environment variables in Deno Deploy

    Login or Signup to reply.
  3. My approach is to use .env files in my local environment and load them with the npm package dotenv.

    I ignore the .env files in the .gitignore so they won’t be added to the repo.

    On the server, these environmental variables already exist, the server admin manages these, but you could make a copy of the .env files on the server if necessary with ssh and vim, or ftp, though it wouldn’t be best practice.

    I also have a copy of the .env files with the values empty as a template in the repo with a readme of where to copy the files and where/who to get the values from for other devs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search