How to use environment variables with nuxtjs on Platform.sh

Goal

To use environment variables in a nuxtjs app on Platform.sh

Problem

Nuxt currently provides a very handy way of injecting environment variables which uses webpack substitution to inject your env vars at build time.

This works most of the time, but on Platform.Sh the build process is environment-agnostic. A build can, and will be reused on different environments. This means that environment variables are not available in the build hook. So nuxt is not able to compile them.

Building nuxt in the deploy hook, is also not possible, since the file system is read only.

Work around: nuxt-env

Luckily, there is a work around.

There’s a nuxtjs plugin called nuxt-env. This allows you to define the environment variables that you want to access at runtime.

First, make sure you have nuxt-env installed by running yarn add nuxt-env on your local pc, and commit that yarn.lock file to your repository

Then, you can add the env vars you want to injects to your nuxt.config.js file

// nuxt.config.js

// Tell nuxt-env which env vars you want to inject
modules: [
  'other-nuxt-module',
  ['nuxt-env', {
    keys: [
      'TEST_ENV_VAR', // Basic usage—equivalent of { key: 'TEST_ENV_VAR' }
      { key: 'OTHER_ENV_VAR', default: 'defaultValue' } // Specify a default value
      { key: 'THIRD_ENV_VAR', secret: true } // Only inject the var server side
      { key: 'ANOTHER_ENV_VAR', name: 'MY_ENV_VAR' } // Rename the variable
    ]
  }]
]

1 Like

Apparently, the latest version of nuxtjs allows you to do it without the nuxt-env module

https://nuxtjs.org/blog/moving-from-nuxtjs-dotenv-to-runtime-config