1

I have defined my keys in .env.local but still while calling it process.env.API_KEY it doesn't work as expected.

API_KEY=xx_xxxxxxxxxxxx

DATABASE_URL=https://xxxxx/db/main

Code:

export const xata = new BaseClient({
  apiKey: process.env.API_KEY,
  databaseURL: process.env.DATABASE_URL
});

Folder Structure:

Project
     - pages
     - public
     - .env.local
     - helper (file that needs api key)

1 Answer 1

2

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. 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 NEXT_PUBLIC_.

Your file becomes :

NEXT_PUBLIC_API_KEY=xx_xxxxxxxxxxxx

NEXT_PUBLIC_DATABASE_URL=https://xxxxx/db/main
Sign up to request clarification or add additional context in comments.

6 Comments

Accessing Variables in the client browser via NEXT_PUBLIC_, will the keys be vulnerable ?
Yes. The way to get around that is using your custom API Routes. A link smashingmagazine.com/2021/12/…
Just check, NEXT_PUBLIC_API_KEY also doesn't work. Show NEXT_PUBLIC_API_KEY undefined
Regarding security : You do not use NEXT_PUBLIC_ but also do not directly call any API which requires the key. Instead you call your Next.js API Routes and they interact with the API using the API Key. This works because as mentioned in the answer Node.js env including the API Routes have access to keys even without NEXT_PUBLIC_.
How are you accessing the key?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.