skip to Main Content

My app is running on a VPS, with Docker Compose. I have a .env file in the file’s directory, at the same level as the docker-compose.yml.

In my docker-compose, I set the environment variables like this:

screenshot of the docker-compose.yml

Everything is working fine when I run the app locally, but the problem is for the deployed app:

I can access the variables only on the Server side, in the getServerSideProps function. However, I get undefined on the client side (I am trying to access the ones starting by NEXT_PUBLIC_).

My workaround was to pass the value of the env variable I need from getServerSideProps to my page as a props, but it is very unconvenient and certainly not the right solution.

Do you know what can cause this issue?

Also, on the VPS, when I inspect the container of the NextJS app (docker exec -it …), I type "env" and I see that the environment variables are there so I don’t understand why they are not received on the client side.

2

Answers


  1. as document says, if your env var has prefix "NEXT_PUBLIC_" it can be visible on client side, but if this is not the case for example after building without docker and testing build files with "npm start" the problem exist , might be because of wrong environment used by command, if not it must be problem with docker side!
    by the way you can use env-cmd library also

    Login or Signup to reply.
  2. Just going off of the documentation it says:

    The value will be inlined into JavaScript sent to the browser because of the NEXT_PUBLIC_ prefix. This inlining occurs at build time, so your various NEXT_PUBLIC_ envs need to be set when the project is built.

    The environment variables you are setting in the docker compose are not available at build time, only at runtime.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search