Introduction to API Routes
API routes are the solution to building your API with Next.js.
How does this work?
Files dat are inside the folder pages/api
is mapped to /api/*
, where it will be treated as the API endpoint instead of as a page
. They will not increase client-side bundle size since they are server-side only bundles.
If you want your API route to work, you have to export a function as default, which is basically the request handler, and this will receive two parameters:
req
is an instance ofhttp.IncomingMessage
.It will also receive a few pre-built middlewares.
res
is an instance ofhttp.ServerResponse
.This will also receive a few helper functions.
If you want to handle different HTTP methods in your API route, you can use req.method
in your request handler.
A good and simple example
export default function handler(req, res) {
if (req.method === 'POST') {
// process a POST request
} else {
// handle any other HTTP method
}
}