API routes in NextJS

To create api endpoints, you just need to create a file in pages/api directory. As you can see in below example, we have a simple endpoint with name user. When we hit /api/user, nextjs server will respond with json object with id property set to 123.

//file name - user.js
import type { NextApiRequest, NextApiResponse } from 'next'

type Data = {
  id: number
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  res.status(200).json({ id: 123 })
}

Dyanimc Routes

To create dynamic routes, use this file syntax - api/user/[userid].js

//file name - api/user/[userid].js
import type { NextApiRequest, NextApiResponse } from 'next'

export default function handler(req, res) {
    const { userid } = req.query
    res.end(`Id: ${userid}`)
  }

API middleware

NextJS comes with built in middlewares as mentioned below.
  • req.cookies - stores all cookies sent by the client
  • req.query - stores all query parameters sent by the client
  • req.body - NextJs parses the request based on content type and stores the object.
By default, NextJS will parse the request as explained above but sometimes you want to handle raw requests. You can use config object change parser settings.

export const config = {
  api: {
    bodyParser: false,
  },
}

NextJS also supports Connect or Express middleware.

Response Object helpers

  • res.status(code)
  • res.json(body)
  • res.send(body)
  • res.redirect('/path')
  • res.revalidate(url) - revalidate a page on demand using getStaticProps

Web development and Automation testing

solutions delivered!!