Search code examples
node.jsenvironment-variablesnpm-package

Send request to the appropriate API in a multi-environment pubilc package


I am currently working on a public npmjs package. This package will send requests to one of my APIs. I also have multiple environments, meaning that I want my package to send requests to different URLs depending if it's being used on production or staging.

I would typically use an environment variable, but since it's meant to be used in other projects, I'm not sure about the right way to go.

One of my thoughts was to have the environment variables defined at build time, but I don't really like this idea because it means that I need to publish different versions for staging/production and I don't want staging releases to appear on npmjs.

I would be interested to hear about how other developers have handled cases similar to this one/best practices.

Thanks in advance!


Solution

  • Here is what I ended up doing.

    I added two commands in my package.json

    "build:prod": "BUILD_ENV=prod && yarn build",
    "build:staging": "BUILD_ENV=staging && yarn build",
    

    and used webpack to define env variables at runtime. For that first, I load the configuration associated with the specified build environment

    const buildEnv = process.env.BUILD_ENV;
    const configuration = require(`./config/${buildEnv}.json`);
    

    And then apply them to the environment variables used in my project

      plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            MY_ENV_VARIABLE: JSON.stringify(configuration.myVariable),
          },
        }),
      ],
    

    And then, in addition to this, I updated the CI to change the name of the package if the release is for staging.

    sed -i 's/"@username\/my-package"/"@username\/staging-package"/' package.json
    

    This enables me to have a different package for staging and production.