API Routes

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

    Any file inside the folder 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:

    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. } else {
    4. // Handle any other HTTP method
    5. }
    6. }

    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 the .

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

    learn about the built-in middlewares for the request.

    Response Helpers

    learn about the built-in methods for the response.

    Add TypeScript to your API Routes.