Search code examples
next.jsapi-gateway

Nextjs API routes as API Gateway


In my microservices project I need a new layer as an API Gateway to change/add/check some data on almost all requests that are coming from the frontend (clientside) to my backend APIs. Mostly I would use this to check if a valid JWT is provided or a request is not malformed.

As the frontend a nextjs server is used in my project. Nextjs has the feature of API routes (https://nextjs.org/docs/api-routes/introduction).

I am wondering if you need a dedicated API Gateway if you just want to do basic stuff like checking if a request has a valid request body or a valid JWT is provided. After those checks I would forward or redirect the request to another microservice backend API endpoint.

If I use the Nextjs API route instead of a dedicated API Gateway:

  • I dont need to manage an entirely new microservice in my project (the API Gateway for example build with Nodejs/Express)
  • I dont need to bother with the same origin policy

For me this approach looks less complicated and since I have the nextjs server running anyway the API routes can be used with little to no effort.

Am I missing something?

Is it a good idea to use nextjs API routes as an API Gateway? Or should you stay with a dedicated API Gateway?


Solution

  • I have used this approach in the past for similar reasons. Works a charm.

    Things to consider:

    • You will still need to validate your jwt token on the backend so proxy it through.
    • If you are using OIDC oauth, consider using a library like nextJS auth0 library to protect your jwt tokens out in the wild in an encrypted cookie.
    • You can use something like express-http-proxy to do some heavy lifting around proxying api requests through to your backend from nextjs.
    • If you are using a logging framework like sentry, make sure to include frontend -> nextjs server -> backend as part of any distributed tracing correlation so you can trace errors through the layers.

    Best of luck