DEV Community

Discussion on: How to Set Environment Variables in Next.js

Collapse
 
kunalgulati_72 profile image
Kunal

Such is so simple!!! Love it !!

I have a question. Is the key "process.env.API_KEY" accessible to Client (user) ?
If not, how does nextJS allows the code on client-side to insert this value in fetch requests made from client side?

The documentation states "In order to keep server-only secrets safe, Next.js replaces process.env.* with the correct values at build time".
In context of security, I am trying to understand how does NextJS make it work
nextjs.org/docs/basic-features/env...

Collapse
 
elaineleung profile image
Elaine

Not sure whether you found the answer to your question yet, but in any case, for the client side you would need to add a "NEXT_PUBLIC_" prefix to the variable. So for "API_KEY", you'd have to change it to NEXT_PUBLIC_API_KEY in the .env file, which also means it would be process.env.NEXT_PUBLIC_API_KEY when used. More on this here: nextjs.org/docs/basic-features/env...

Collapse
 
ayomiku222 profile image
Ayomiku Olatunji John

This solved my problem. Thanks Elaine

Thread Thread
 
elaineleung profile image
Elaine

Good to hear!