Making API from nextjs client side to separate backend in docker setup
Unanswered
Yellowhead catfish posted this in #help-forum
Yellowhead catfishOP
I know this question is asked a lot already, but after searching the internet for hours, I still haven't found a solution. In a setup with Docker and two separate backends, one Next.js and one Express, the Next.js server-side can easily access the Express backend through its container name. However, the Next.js client-side cannot do this because the container name is not exposed in the browser environment. Another option is using the host machine and forwarding the ports of both servers to it. The Next.js server can connect to the Express server through 'host.internal.docker,' but this is still only accessible within the Docker context. Therefore, the Next.js client-side won't work with it.
What is the most sensible choice here for calling the API from the Next.js client-side to the Express container? Should I create two API endpoints and switch depending on the environment?
What is the most sensible choice here for calling the API from the Next.js client-side to the Express container? Should I create two API endpoints and switch depending on the environment?
2 Replies
@Yellowhead catfish I know this question is asked a lot already, but after searching the internet for hours, I still haven't found a solution. In a setup with Docker and two separate backends, one Next.js and one Express, the Next.js server-side can easily access the Express backend through its container name. However, the Next.js client-side cannot do this because the container name is not exposed in the browser environment. Another option is using the host machine and forwarding the ports of both servers to it. The Next.js server can connect to the Express server through 'host.internal.docker,' but this is still only accessible within the Docker context. Therefore, the Next.js client-side won't work with it.
What is the most sensible choice here for calling the API from the Next.js client-side to the Express container? Should I create two API endpoints and switch depending on the environment?
Cape lion
If you only have a few endpoints that are needed from the client-side to the express-side, you can create a "proxy" API route (or server action) in Next.js that will just
fetch to the express backend.This means your express backend does not need to be public (i.e. if you haven't implemented any form of authentication & authorization on it), and any checks can be done on the Next.js route/server action