How to use cookies between two docker containers (docker compose)

Viewed 169

Graph of network structure

I am following the flows inspired by these Ben Awad videos: https://www.youtube.com/watch?v=iD49_NIQ-R4 https://www.youtube.com/watch?v=25GS0MLT8JU.
The general pattern is access-token in memory, refresh token as httponly cookie*. This seems pretty secure and dev friendly.
However since both my node frontend and my api backend are dockerized: during SSR I want to use the local connection to the backend, not through the DNS. By default this is a bridge network. This comes with a problem. Since the internal uri of the backend is http://backend, not http://localhost:8000 (or DNS name in production), the cookie does not apply to that domain, even though it really is the same app as we got the cookie from.

So: what is the best solution, and how do I implement it?

Ideas for solutions:

  • To not use local connection and let the frontend container use host network
  • To "rename" the local connection from http://backend to http://localhost
  • To somehow set two cookies, one for http://backend and one for localhost
  • Store the refresh token somewhere thats not a cookie
1 Answers

You can use Nginx to solve this problem, since the header of your frontend will include a cookie for verification when a request is sent to your backend server, you can bind each server to a different port on the host machine, then add a CNAME record on your domain control panel to direct all request sent to (let's as) api.mydomain.com, to serve mydomain.com then in your Nginx config, you can do something like this

Nginx Config

server {

    server_name mydomain.com;
    listen 80;
    location '/' {
        proxy_pass 'http://localhost:8000/';
    }

}


server {
    listen 80;
    server_name api.mydomain.com;
    location '/' {
        proxy_pass 'http://localhost:7000/';
    }

}

then you can use the svelte externalFetch to change the path on the server side, so when the request hit the server, instead of fetching the specified URL, you can override it with the local host URL, like this:

src/hooks.ts

export async function externalFetch(request) {
    if (request.url.includes('api.mydomain.com')) {
      const localPath = new URL(request.url.pathname, 'http://localhost:7000')
      request = new Request(localPath.href, request);
    }
}
Related