I am trying to access my environment variables in my application made with Next.js.
From the Next.js docs. I need to put the environment variables in a .env.local
file and access them with process.env.<ENV_VARIABLE>
. I have done all this, but it is still returning undefined
.
Relevant file paths:
root/.env.local
root/db/index.ts
.env.local:
ENV_VAR=test
NEXT_PUBLIC_ENV_VAR=publicTest
db/index.ts:
console.log(process.env.ENV_VAR)
console.log(process.env.NEXT_PUBLIC_ENV_VAR)
In every thread I’ve come across on Stack Overflow so far the accepted answer is to use NEXT_PUBLIC_
for the environment variable, but this had no effect. The index.ts file returns undefined
for both variables.
From another thread I have added reactStrictMode: true
to nextConfig in next.config.cjs, but that also had no effect.
I had dotenv installed, but after looking at aanother thread and one on GitHub, I uninstalled dotenv twice, once with npm uninstall dotenv
and again with npm r dotenv
. These commands also had no effect.
I use ts-node --esm db/index.ts
to run the index.ts file.