How to use Next.js API routing

Learn about this powerful technology provided by Next.js to create API endpoints in Next.js applications

In addition to creatingPage route, Which means that the page is provided to the browser as a web page, and Next.js can createAPI route.

This is a very interesting feature because it means that Next.js can be used to create a front-end for the data stored and retrieved by Next.js itself, and to transmit JSON through get requests.

API routing is located at/pages/api/Folder and map to/apiEndpoint.

This function isvery muchUseful when creating applications.

In these routes, we write Node.js code (not React code). This is a paradigm shift, you can move from the front end to the back end, but it is very seamless.

Say you have one/pages/api/comments.jsFile, whose goal is to return the comments of blog posts in JSON format.

Suppose you have a list of comments stored incomments.jsonfile:

    "comment": "First"
    "comment": "Nice post"

This is a sample code that returns a list of comments to the client:

import comments from './comments.json'

export default (req, res) => { res.status(200).json(feeds) }

It will listen/api/commmentsGET the requested URL, you can try to call it with a browser:

API routing can also be usedDynamic routingLike a web page, please use[]Syntax for creating dynamic API routing, for example/pages/api/comments/[id].jsIt will retrieve comments specific to the post ID.

Inside[id].jsYou can retrieveidGet value by looking insidereq.querypurpose:

import comments from '../comments.json'

export default (req, res) => { res.status(200).json({ post:, comments }) }

Here, you can see the above code is running:

In dynamic pages, you need to importuseRouterFromnext/router, And then use to get the router objectconst router = useRouter(), And then we can getidValue

On the server side, this is easy because the query is attached to the request object.

If you perform a POST request, all requests work in the same way-all operations are performed through this default export.

To separate POST from GET and other HTTP methods (PUT, DELETE), please findreq.methodvalue:

export default (req, res) => {
  switch (req.method) {
    case 'GET':
    case 'POST':
      res.status(405).end() //Method Not Allowed

In additionreq.querywithreq.methodWe have seen that we can access cookies by referencereq.cookies, The request body is inreq.body.

Under the hood, all this is done bymicro-It is a library that supports asynchronous HTTP microservices developed by the team that supports Next.js.

You can use any Micro middleware in our API routing to add more features.

Download mine for freeNext.js manual

More tutorials next: