Next.js Discord

Discord Forum

App router: API endpoint use runtime env var?

Answered
Himalayan posted this in #help-forum
Open in Discord
HimalayanOP
With the App Router, can a Next API endpoint handler use a runtime environment variable? If so, how is this done? Thanks!
Answered by Himalayan
Ah! I think I know the problem, it's because I prefixed the env vars with NEXT_PUBLIC_ which I believe is for making the env vars available to the client, which isn't necessary here. Removing the NEXT_PUBLIC_ seems to have fixed it! Thank you for your help 🙂
View full answer

18 Replies

have a .env file in the root path, and just use it like process.env.Variable
@averydelusionalperson https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables
HimalayanOP
Thanks for your reply. That will use env vars that are compiled at build time. I need to use runtime env vars
I believe next.js api routes does use the runtime env vars
even if you don't have .env file, it will use he environment variables from system ig
@averydelusionalperson I believe next.js api routes does use the runtime env vars
HimalayanOP
Sadly this doesn't seem to be the case. Removing the env var from the .env file during build, then adding it back for runtime results in the api route receiving undefined for the env var value 😦
ahh, where are you storing the environment variables if not for .env?
HimalayanOP
I am storing them in an .env.local file
hmm, it should work, it isn't?
next.js docs also recommend
.env.local
HimalayanOP
Ah! I think I know the problem, it's because I prefixed the env vars with NEXT_PUBLIC_ which I believe is for making the env vars available to the client, which isn't necessary here. Removing the NEXT_PUBLIC_ seems to have fixed it! Thank you for your help 🙂
Answer
oh, noice
if your problem is solved, consider marking the answer as solution
it can be any message
Original message was deleted
^
HimalayanOP
Thank you, I will! 🙂
🫡