Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass env variables to nuxt in production?

Tags:

vue.js

nuxt.js

nuxt.config.js

modules: [
    '@nuxtjs/dotenv'
  ],

server/index.js

const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const host = process.env.HOST || '0.0.0.0'
const port = 8080
app.set('port', port)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

const Storage = require('@google-cloud/storage')
const dotenv = require('dotenv')


async function getEnv() {
  if (config.dev) {
    dotenv.config({ path: '.env' })
    console.log('Environment local .env file loaded.')
    console.log(process.env.LOCALE)

    return
  }

  try {

    const bucketName = 'env-var'

    const dotEnvSourcePath = `.env`
    const dotEnvDestinationPath = `/tmp/${dotEnvSourcePath}`
    const storage = new Storage({})

    await storage
      .bucket(bucketName)
      .file(dotEnvSourcePath)

      .download({ destination: dotEnvDestinationPath })
    console.log(
      `gs://${bucketName}/${dotEnvSourcePath} downloaded to ${dotEnvDestinationPath}.`
    )


    dotenv.config({ path: dotEnvDestinationPath })


  } catch (err) {
    console.error('ERROR:', err)
  }
}

async function afterEnvProcess() {
  // Init Nuxt.js
  const nuxt = new Nuxt(config)

  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  // Give nuxt middleware to express
  app.use(nuxt.render)

  // Listen the server
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
  const fs = require('fs')

  const dotEnvExists = fs.existsSync('.env')
}

getEnv()
  .then(r => afterEnvProcess())
  .catch(e => console.log(e))

I get the values for process.env.<variable> as undefined when running the app in production. When running in development, I get the values correctly. It seems the env variables are not getting passed to the nuxt env property.

EDIT 1: I can see the correct values in google cloud logs when I console log the env variables with process.env. but at the same time those console log statements show undefined in the browser console

like image 874
Rounak Jain Avatar asked Jan 01 '19 07:01

Rounak Jain


2 Answers

Most people use dotenv package but I dislike this solution, because it adds the need for managing an extra file different for production and development, while you can automate webpack to use the right values without extra hassle.

A simpler way :

//package.json
  "scripts": {
    "dev": "NODE_ENV=dev nuxt"
  }
//nuxt.config.js
  env: {
    baseUrl:
      process.env.NODE_ENV === 'dev'
        ? 'http://localhost:3000'
        : 'https://my-domain.com'
  }

This will allow you to use the right value by calling process.env.baseUrl. Note that you can verify this with console.log(process.env.baseUrl) but not console.log(process.env), at least in Chrome.

like image 70
Samuel Faure Avatar answered Oct 22 '22 16:10

Samuel Faure


nuxt.config.env Gotcha!

For future Googler's including myself, there's an annoying gotcha which nuxt.config.js doesn't explain very well.

process.env.SOMETHING is literally replaced during the build with the config.env.SOMETHING value

before build

    if (process.env.SOMETHING == 'testing123')

after build

    if ('testing123' == 'testing123')

This also doesn't work with objects! only literals.

// This won't work for you!
mounted() {
  console.log('process.env', process.env)
}

https://nuxtjs.org/api/configuration-env/

like image 36
Ben Winding Avatar answered Oct 22 '22 15:10

Ben Winding