Next.js Discord

Discord Forum

Are .env variables accessible outside of the app folder? (NEXTJS 14)

Unanswered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
I have a .env.local in my root folder, and I'm attempting to reference the variables here in /src/utils/local/insertPlans.js. When I console.log my .env.local variables in this file they're undefined, logging the .env.local entirely they don't show up. However when accessing these variables in my next pages / components it works fine.

Is there anything about .js files outside of the app router that I should be accounting for? Do I need to add another .env, or install a package like dotenv for local utils? This script is just a local script to populate my plans database.

1 Reply

Sun bear
You should be able to access env also in other folders.

But you have to make sure you try to access them serverside.

Just as an example.

You have a utils.ts with funcrion testEnv() and want to return process.env.whatever.

If you run that function from a servercomponent you should get the value. If you run it from a client component it will be undefined.

In that case NEXT_PUBLIC might help in case the env is not confidential