API Routes
API routes provide a 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
returns a json
response with a status code of 200
:
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:
req
: An instance of , plus some pre-built middlewaresres
: An instance of , plus some helper functions
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') {
} else {
}
}
To fetch API endpoints, take a look into any of the examples at the start of this section.
- Masking the URL of an external service (e.g.
/api/secret
instead of ) - Using Environment Variables on the server to securely access external services.
- 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 .
- API Routes can’t be used with next export
For more information on what to do next, we recommend the following sections:
API Routes Request Helperslearn about the built-in helpers for the request.