Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 439
Moritz Laube Avatar asked Oct 10 '19 09:10

Moritz Laube


2 Answers

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.

like image 109
HMilbradt Avatar answered Oct 07 '22 04:10

HMilbradt


We had a similar problem in our project. Even, We created a nuxt project from scratch and checked to see if there was a situation we skipped. We noticed that, while nuxt building, it copies the .env variables into the utils.js in the nuxt folder. Through the document here, we changed the modules section in nuxt.config.js as follows,

modules: ['@ nuxtjs / apollo', '@ nuxtjs / axios', ['@ nuxtjs / dotenv', { only: ['']}]],

Then we noticed that .env variables are not exposed.

I hope it helped.

Our nuxt version is "nuxt": "^ 2.13.0".

Also, some discussion over here.

like image 32
Berkay Kaan Avatar answered Oct 07 '22 04:10

Berkay Kaan