Search code examples
environment-variablesnuxt.jsdotenvvercel

Nuxt environment variables exposed in client when uploaded to Zeit/Now


I am deploying a Nuxt App with Zeit/Now. In the development phase I was using a .env file to store the secrets to my Contentful CMS, exposing the secrets to process.env with the nuxt-dotenv package. To do that, at the top of the nuxt.config I was calling require('dotenv').config().

I then stored the secrets with Zeit/Now and created a now.json to set them up for build and runtime like so:

{
    "env": {
        "DEMO_ID": "@demo_id"
    },
    "build": {
        "env": {
          "DEMO_ID": "@demo_id"
        }
    }
}

With that setup, the build was only working for the index page and all of the Javascript did not function. Only when I added the env-property to the nuxt.config.jsfile, the app started working properly on the Zeit-server.

require('dotenv').config()

export default {
...
env: {
   DEMO_ID: process.env.DEMO_ID
  },
...
  modules: [
    '@nuxtjs/dotenv'
  ],
...
}

BUT: When I then checked the uploaded Javascript files, my secrets were exposed, which I obviously don't want.

What am I doing wrong here? Thanks for your help.


Solution

  • You aren't necessarily doing anything wrong here, this is just how Nuxtjs works.

    Variables declared in the env property are used to replace instances of process.env.MY_ENV, but because Nuxt is isomoorphic, this can be both on the server and client.

    If you want these secrets accessible only on the server, then the easiest way to solve this is to use a serverMiddleware.

    As serverMiddleware is decoupled from the main Nuxt build, env variables defined in nuxt.config.js are not available there.

    This means your normal ENV variables should be accessible, since the server middleware are run on Node.

    Obviously, this means these secrets won't be available client side, but this works if you have something like a Stripe secret key that you need to make backend requests with.