Skip to content

Latest commit

 

History

History
77 lines (59 loc) · 3.23 KB

introduction.md

File metadata and controls

77 lines (59 loc) · 3.23 KB
description
Next.js supports API Routes, which allow you to build your API without leaving your Next.js app. Learn how it works 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. 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 returns a json response with a status code of 200:

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

For an API route to work, you need to export a function as default (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 function handler(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.

Caveats

Related

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