Fixing missing environment variables in Nuxt 3
Recently I needed to use the quickjs-emscripten library in a Nuxt 3 app. Long story short, the library checks for an environment variable using process.env
:
exports.QTS_DEBUG = false || Boolean(typeof process === "object" && process.env.QTS_DEBUG);
The library is being sensible here - because the process
object doesn't exist in the browser, but only in node, it first check if process
exists as an object in the current context. This should be enough of a sanity check but unfortunately when developing with Nuxt process
actually does exist as an object.
Nuxt is creating this process object for its own purposes, so when the quickjs-emscripten
package tests for it it is there and away it goes trying to find the env.QTS_DEBUG
property on it - and there it chokes because env
is not defined!
This non-existent env
even occurs if you have a .env
file in your project that is used by Nuxt - it exposes the environment variables through other means, not process.env
.
So how to fix? Well, the package maintainers could update to check if process.env
is defined. But in lieu of that solution, we can define global variables in our nuxt.config.ts
file:
export default defineNuxtConfig({ vite: { define: { "process.env.QTS_DEBUG": false, }, },})
Bam, we're good!