Development

Creating Rest API with NextJS

coderesult
30 August 2022

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.

pages/api

Adding a logic for different HTTP methods

Adding 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 :

export default function handler(req, res) {  
	if (req.method === 'GET') {    
    	// Process a POST request  
    } else {    
    	// Handle any other HTTP method  
    }
}

Getting the query or body parameters

Getting the query or body parameters

In a simpler version it would be like :

export default function handler(req, res) {
  const {
       query: { id },
       body: { name }
    } = req;
res.status(200).json({ id, name, registered: true })
}
In previous versions of NextJS you need to set JSON.parse(req.body) but if you use NextJS v12, you don’t need that as long as you haven’t explicitly set bodyParser: false in the exported configuration for the corresponding API route (see https://nextjs.org/docs/api-routes/api-middlewares).

Custom config

Creating custom config for the endpoint

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 false.

Creating dynamic routes

Generally speaking there 2 approaches for creating dynamic routes:

First approach :

  • /api/users.ts
  • /api/users/[userId].ts

Second approach :

  • /api/users/index.ts
  • /api/users/[userId].ts

If you only create [userId].ts and omit to createindex.ts or users.ts, Dynamic Routes do not have an undefined state and your request will not match /api/users/[userId].js under any circumstance

CORS

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.

Conclusion

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.


Follow me on Instagram, Facebook or Twitter if you like to keep posted about tutorials, tips and experiences from my side.

You can support me from Patreon, Github Sponsors, Ko-fi or Buy me a coffee