Home > OS >  Unexpected token while access an env variable
Unexpected token while access an env variable

Time:11-27

I'm trying to add environment variable inside .env file in my nuxt project.

My Nuxt.js version is 2.15.3

Here is a snippet from my nuxt.config.js:

export default {
  publicRuntimeConfig: {
    baseURL: process.env.BASE_URL
  },
  ssr: false,
  target: 'static',
}

Here is my .env file:

BASE_URL=https://my-url.smth

But when I run npm run dev then nuxt gives error:

ERROR in ./.env 1:14 Module parse failed: Unexpected token (1:14) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.

I was guided by this article https://nuxtjs.org/tutorials/moving-from-nuxtjs-dotenv-to-runtime-config/

Also it DOES NOT work with the old way through the @nuxtjs/dotenv.

CodePudding user response:

EDIT: the solution was to wrap the variable into double quotes like this BASE_URL="https://my-url.smth".


I've wrote an in-depth answer on the subject.
As mentioned in it, please do not use the @nuxtjs/dotenv package.

If you still have an issue, we'll probably need more details or at least a repro to help you more efficiently.

CodePudding user response:

I see you mentioned @nuxtjs/dotenv, so load the .env via @nuxtjs/dotenv

nuxt.config.js

    buildModules: [
        ['@nuxtjs/dotenv', {
            only: [
                'BASE_URL',
            ]
        }],
    ],

if you are using vite instead of webpack (maybe via nuxt-vite), please add a prefix VITE_ for your env variables

  • Related