API Routes

Good to know:

  • API routes should still be defined in the pages/api/* directory and not moved to the app directory.
  • We are considering what API routes would look like in the app directory and will update this page in the future.
  • Some use cases where an API route was used to keep access tokens secure when calling an external API from the client can now be done directly in Server Components.

Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a route.

For example, the following API route pages/api/user.ts returns a json response with a status code of 200:

An example folder structure of an API route
pages/api/user.ts
import { NextApiRequest, NextApiResponse } from 'next'

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ name: 'John Doe' })
}

You can learn more about API routes in the stable Next.js docs.