Secure API Authentication with NextJs Series
4. Routing Microservice to the Same Port (optional)
If you are not building your API with NextJs, your API and website will be on different ports, and therefore, different domains. To set cookies from your API, they need to be sent from the same domain. The RFC 6265 explains why:
The user agent will reject cookies unless the Domain attribute specifies a scope for the cookie that would include the origin server. For example, the user agent will accept a cookie with a Domain attribute of “example.com” or of “foo.example.com” from foo.example.com, but the user agent will not accept a cookie with a Domain attribute of “bar.example.com” or of “baz.foo.example.com”.
We’ll assume your NextJs app is running on port 3000, and your API on port 4000. To receive cookies and have them set in the browser, your API requests must use the same domain, localhost:3000
. We will create a development server that based on certain rules, will reroute requests from port 3000
to the port our API is running on.
Using express
and http-proxy-middleware
, we’ll make all requests that start with /api
be rerouted to localhost:4000
. So we don’t have to alter our APIs to include this base path, in pathRewrite
, we are removing api
from the request.
The full development server is below, create a file in the root folder of your project called server.js
. You can then start your application with node server.js
. This should only be used for development and not production. In production, it's best practice to use the same domain or a subdomain for your API to get the full benefits of NextJs.
If you are using microservices and want to route all your requests through the same port, you can use Nginx and Docker. This makes local development much easier as you can use the same base URL for all services.