Note: You are viewing the new Next.js documentation. The old docs are still available here.

API Routes

Examples

API routes provide a straightforward solution to build your API with Next.js.

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

For example, the following API route pages/api/user.js handles a simple json response:

export default (req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify({ name: 'John Doe' }))
}

For an API route to work, you need to export as default a function (a.k.a request handler), which then receives the following parameters:

To handle different HTTP methods in an API route, you can use req.method in your request handler, like so:

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

To fetch API endpoints, take a look into any of the examples at the start of this section.

API Routes do not specify CORS headers, meaning they are same-origin only by default. You can customize such behavior by wrapping the request handler with micro-cors.

API Routes do not increase your client-side bundle size. They are server-side only bundles.

Related permalink

For more information on what to do next, we recommend the following sections: