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. They are server-side only bundles and won’t increase your client-side bundle size.

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

  1. export default function handler(req, res) {
  2. res.statusCode = 200
  3. res.setHeader('Content-Type', 'application/json')
  4. res.end(JSON.stringify({ name: 'John Doe' }))
  5. }

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:

  1. export default function handler(req, res) {
  2. if (req.method === 'POST') {
  3. // Process a POST request
  4. } else {
  5. // Handle any other HTTP method
  6. }
  7. }

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

Caveats

Related

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

API Middlewares

learn about the built-in middlewares for the request.

Response Helpers

learn about the built-in methods for the response.

TypeScript

Add TypeScript to your API Routes.