cannot access env inside nuxt.config.js

Viewed 1669

I am using Nuxt v2.12.2 in SPA mode and want to use env variables within the default head. I am using @nuxtjs/dotenv however when the page is rendered the baseUrl is undefined.

I am able to access BaseUrl from within page layouts fine, but not from within nuxt.config.js like below.

.env

BASE_URL=https://example.com

nuxt.config.js

const env = import('dotenv')
env.config()

export default {
  mode: 'spa',

  generate: {
    fallback: true
  },

  env: {
    baseUrl: process.env.BASE_URL || 'http://localhost:3000'
  },

  head: {
    meta: [
      {
        hid: 'og:image',
        name: 'og:image',
        content: process.env.baseUrl + '/og/facebook.png'
      }
    ],
  },

  modules: [
    '@nuxtjs/dotenv'
  ]

  ...
}
2 Answers

process.env.baseUrl is not yet set when the head property is set.

One solution is to use a function for head, which would be run after the env is setup:

export default {
  head() {
    return {
      title: this.$route?.title,
      meta: [
        {
          hid: 'og:image',
          name: 'og:image',
          content: process.env.baseUrl + '/og/facebook.png'
        }
      ]
    }
  }
}
Related