Fix missing environment variables for production

It’s common to forget setting a new environment variable after deployment, so I’ll share a strategy that I’m using:

1- Use fetch method

Let’s start with this example of missing NEW_KEY value:

So how this works? ENV is a hash-like accessor for environment variables so we can use hash methods but we need only fetch for the moment.

Now it’s time to add more description to the error:

We have a descriptive warning, but it’s not enough we want to know if there is a missing variable after the deployment.

2- Rails custom configuration

When we start a Rails application, “config/application.rb” is required before booting the server if you are curious to know about Rails initialization process check the official guide.

With this information, we can use Rails custom configuration (check this guide for more information) to have the following configuration:

If we try to start a Rails server without setting the ENV variable we will get our custom Error.

Next, we need just to access the defined variable in the source code as follows:

That’s it, with this approach no more worries about missing ENV variables! 🙂

Tagged , , ,