Next.js Discord

Discord Forum

Environment variables are undefined in route file

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
Following is my config/route.ts file and when I run this via Docker, the environments variables are not found. I am injecting SUPABASE_URL and SUPABASE_ANON_KEY in the docker container via command line.

export async function GET(request: Request) {
    console.log(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY)
    return Response.json({
        url: process.env.SUPABASE_URL,
        key: process.env.SUPABASE_ANON_KEY
    })
}

Response
{}

What am I doing wrong?

11 Replies

You're logging them to console, and checking the HTTP Response from what I can see currently 😄
check the console
Asian black bearOP
I added the console.log after I failed to see the value in the HTTP response. It is not visible on the console as well.
can you provide logs from your dev server start? Like:

   â–² Next.js 14.0.1
   - Local:        http://localhost:3000
   - Environments: .env.local
   - Experiments (use at your own risk):
     · instrumentationHook
Asian black bearOP
From the running Docker container:

(node:8) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)

> chat@0.1.0 start /app
> next start

   â–² Next.js 14.0.2
   - Local:        http://localhost:3000

 ✓ Ready in 785ms
(node:39) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
Your app is not loading .env files - probably there is no such file in container image 😄
Asian black bearOP
There is no .env on the server as the variables are injected in the container via --env-file .env in the docker run command.

I have been doing this for a really long time. Don't know what the problem is with this new app that I have recently created.
it looks like next's node server have no access to container's env variables - honestly it would be hard to help without reproduction/repository access, even the vercel examples are using .env files inside docker containers 😄
Asian black bearOP
I think I get it! In the Docker image since I had to start two processes, I put those into a script and invoking it via CMD ["sh", "script.sh"].

This is actually creating a new shell session and the environment variables are probably not injected into this new session.
nice! thanks for sharing solution
Asian black bearOP
Turned out it was not the case! Since it is a GET function, Next.js was caching it. I had to convert it to a POST method to opt out.
https://github.com/vercel/next.js/discussions/58962