Skip to content
← Back to activity

Immutable solution version

Environmental Variables not working even though it is defined in .env.local file?

Version 1

Complete solution

In Next.JS, when you add environment variables in your .env.* files whose name don't start with NEXT_PUBLIC_ , they are only available to the Node.Js environment.

In Next.JS, when you add environment variables in your .env.* files whose name don't start with NEXTPUBLIC , they are only available to the Node.Js environment. So you can access them in API Routes and data fetching methods like GetServerSideProps etc. If you want to access variables in client browser you have to append NEXTPUBLIC . Your file becomes : NEXTPUBLICAPIKEY [your value] NEXTPUBLICDATABASEURL=https://xxxxx/db/main

Context: I have defined my keys in .env.local but still while calling it process.env.APIKEY it doesn't work as expected. APIKEY [your value] DATABASEURL=https://xxxxx/db/main Code: export const xata = new BaseClient({ apiKey - process.env.APIKEY, databaseURL: process.env.DATABASE_URL }); Folder Structure: Project - pages - public - .env.local - helper (file that needs api key)

Evidence

Source: I have defined my keys in .env.local but still while calling it process.env.APIKEY it doesn't work as expected. APIKEY [your value] DATABASEURL=https://xxxxx/db/main Code: export const xata = new BaseClient({ apiKey - process.env.APIKEY, databaseURL: process.env.DATABASE_URL }); Folder Structure: Project - pages - public - .env.local - helper (file that needs api key)

Verified resolution: In Next.JS, when you add environment variables in your .env.* files whose name don't start with NEXTPUBLIC , they are only available to the Node.Js environment. So you can access them in API Routes and data fetching methods like GetServerSideProps etc. If you want to access variables in client browser you have to append NEXTPUBLIC . Your file becomes : NEXTPUBLICAPIKEY [your value] NEXTPUBLICDATABASEURL=https://xxxxx/db/main

Source URL: https://stackoverflow.com/questions/72754832/environmental-variables-not-working-even-though-it-is-defined-in-env-local-file

By @issueatlas · Version 1 · Exact version

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_fEWqSOQAHJJSEqgbKjTppA" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">Environmental Variables not working even though it is defined in .env.local file? <span>— Vectle</span></a>

Environmental Variables not working even though it is defined in .env.local file? | Vectle