Secure API Authentication with NextJs: Routing Microservices to the Same Port

Jake Owen
1 min readNov 6, 2021

--

Secure API Authentication with NextJs Series

1. HTTP Only Cookie

2. Set-Cookie from API

3. Development Server

4. Routing Microservice to the Same Port (optional)

5. Client-Side vs Server-Side API Calls

6. Access Token vs Refresh Tokens

On production, your APIs will most likely be routed from the same domain as your website, or a subdomain, e.g. api.domain.co.uk. If you want to mimic this on localhost, you can use Nginx and Docker. Create a new directory nginx, within the directory, create two files, Dockerfile and nginx.config.

nginx
|
|---Dockerfile
|---nginx.conf

nginx.conf

upstream credential {
server host.docker.internal:4000 weight=1;
}

upstream account {
server host.docker.internal:4001 weight=1;
}

server {
location /credential {
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass <http://credential>;
}

location /account {
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass <http://account>;
}
}

Dockerfile

FROM nginx
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d/default.conf

To run:

docker build -t nginx-proxy .

docker run -p 8000:80 -t nginx-proxy

--

--

No responses yet