NextJS is a powerful tool with lots of capabilities. In this tutorial, I will show you how to create api endpoints that you can use inside or outside your NextJS application without the need for an external tool or library.
Adding a logic for different HTTP methods
In your request handler you can get the information about the request. In a simpler version it would be like :
Getting the query or body parameters
In a simpler version it would be like :
When you export config for an endpoint it will override the default values. Let’s say if you want to consume the body as a
Stream or with
raw-body, you can set bodyParser to
Creating dynamic routes
Generally speaking there 2 approaches for creating dynamic routes:
First approach :
Second approach :
If you only create
[userId].tsand omit to create
users.ts, Dynamic Routes do not have an
undefined state and your request will not match
/api/users/[userId].js under any circumstance
By default, API routes don’t specify CORS headers so are
same-origin only. You can customize such behavior by wrapping the request handler with the CORS middleware.
NextJS offers a powerful yet simple solution for creating an Backend-For-Frontend layer with no need for an external NodeJS application.
This way instead of sending requests directly to microservices, we can send a request to NextJS and hide some stuff from the browser or do some clean-up in the data and keep the presentation layer tidy.