NuxtN
Nuxt5mo ago
4 replies
mariial

Env variables not working

Using Nuxt 3.18.1.
Hi! I've been struggling with an env variable. I can't seem to make it work when running the preview (npm run build && npm run preview). Locally, it works as it should. Basically, I want a variable to be true on dev and false on prod. For testing purposes, I have it set to true in .env.production, so I can see in an if statement if it works. Here's my current code:

.env.development: NUXT_PUBLIC_USE_MOCK_DATA=true
.env.production: NUXT_PUBLIC_USE_MOCK_DATA=true

nuxt.config.js:
runtimeConfig: {
    public: {
      useMockData: process.env.NUXT_PUBLIC_USE_MOCK_DATA || "false"
    }
  }


/api/example/[id].ts:
const config = useRuntimeConfig(event);
const useMockRaw = config.public.useMockData as unknown as string;
const useMockData = useMockRaw.toLowerCase() === "true";

  if (useMockData) {
    console.log("Using mock stock data");
    // something else with mock data
    }
  } else {
    const thirdPartyKey = config.thirdPartyKey;

    data = await $fetch(
      `https://www.example.com/?key=${thirdPartyKey}`,
      {
        headers: { "User-Agent": "request" }
      }
    );
  }


I run npm run build && npm run preview and useMockData is always false/falsey.

Could I please get some help with this? I'm trying to understand how env variables work. I've read through documentation and research but I can't seem to get it right.
TIA!
Was this page helpful?