Environment Variables in JavaScript

Environment variables in JavaScript are a set of key-value pairs that can be used to store data outside of the JavaScript code. This data can be anything from API keys to database credentials. Environment variables are often used to keep sensitive data secret, as they are not stored in the code itself.

We can import environment variables in the code with process.env object.

export API_KEY=YOUR_API_KEY
Runtime Environment Variables in JavaScript

Dotenv File for Environment Variables

It is tedious to put all your environment variables using export while developing. Therefore you can use dotenv file. It is just a text file that contains environment variables. Dotenv file needs to be loaded into your code. There’s NPM package with the same name that will help you do it. This package puts variables that you have in your dotenv file into process.env object. You just import the package in your main javascript index file. However recently I have been using dotenv-cli. You just use it when you run your dev command and it will load your dotenv file.

DotEnv file should not be committed to github repo or otherwise shared. It should be added to your .gitignore file. In order to let your co-workers know what variable they are supposed to use as environment variables you can create .env.example file and commit it to the repo. .env.example file should list all the necessary environment variables. When your co-worker sets up the project they just simply copy .env.example file to .env file and update it with their environment variables.

Environment Manager Class

As we already saw, environment variables can be used in the code by doing process.env. object. However when you have a lot of environment variables, this doesn’t scale well. Besides some variables may have default values. It is a good practice to use EnvManager class.

export default class EnvManager {
  public static getConfig = (name: string, defaultValue: any) => {
    return process.env[name] ?? defaultValue;
  };

  public static getNodeEnv = (defaultValue?: any) => {
    return this.getConfig("NODE_ENV", defaultValue || "development");
  };

  public static getPort = (defaultValue?: any) => {
    return Number(this.getConfig("PORT", defaultValue));
  };

  public static getDbHost = (defaultValue?: any) => {
    return this.getConfig("DB_HOST", defaultValue);
  };

  public static getDbPort = (defaultValue?: any) => {
    return Number(this.getConfig("DB_PORT", defaultValue));
  };

  public static getDbName = (defaultValue?: any) => {
    return this.getConfig("DB_NAME", defaultValue);
  };

  public static getDbUsername = (defaultValue?: any) => {
    return this.getConfig("DB_USERNAME", defaultValue);
  };

  public static getDbPassword = (defaultValue?: any) => {
    return this.getConfig("DB_PASSWORD", defaultValue);
  };
}

EnvManager with JavaScript Proxy

EnvManager class is a good way to manage environment variables in JavaScript, however, it may get a bit tedious to add a static method to the class whenever we are going to add a new variable. To automate this process we can use JavaScript Proxy. Let’s take a look at how to do that.

export default new Proxy(envManager, {
  get(envManager: EnvManager, field: string) {
    return function (defaultValue?: string | number | boolean) {
      if (field in envManager) {
        // if method exists on envManager (getDbConnectionUrl)
        return envManager[field](defaultValue);
      }
      let envVariable: string | number | undefined =
        process.env[studlyCaseToSnakeCase(field.replace("get", ""))];

      if (envVariable && /^true$/i.test(envVariable)) {
        return true;
      }

      if (envVariable && /^false$/i.test(envVariable)) {
        return false;
      }

      if (envVariable && !isNaN(parseInt(envVariable, 10))) {
        (envVariable = parseInt(envVariable, 10));
      }
      return envVariable || defaultValue;
    };
  },
});

Conclusion

In conclusion, mastering the art of environment variables in JavaScript is not just about safeguarding sensitive data but also about streamlining your development process. By using dotenv files, you can keep your secrets safe and your code clean. The EnvManager class is a fantastic tool to efficiently access these variables, and if you want to take it a step further, the JavaScript Proxy method can automate and simplify the process.

Happy coding!

Share this article

Similar Posts