网页
综合
更新时间 2026-10-15 00:00:00
API Routes
自动蜘蛛
nextjs.org
正文约 5041 字
If you are using the App Router, you can use Server Components or Route Handlers instead of API Routes.
API routes provide a solution to build a public 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 returns a JSON response with a status code of 200:
To handle different HTTP methods in an API route, you can use req.method in your request handler, like so:
API Routes provide built-in request helpers which parse the incoming request (req):
Every API Route can export a config object to change the default configuration, which is the following:
bodyParser is automatically enabled. If you want to consume the body as a Stream or with raw-body, you can set this to false.
One use case for disabling the automatic bodyParser is to allow you to verify the raw body of a webhook request, for example from GitHub.
bodyParser.sizeLimit is the maximum size allowed for the parsed body, in any format supported by bytes, like so:
externalResolver is an explicit flag that tells the server that this route is being handled by an external resolver like express or connect. Enabling this option disables warnings for unresolved requests.
responseLimit is automatically enabled, warning when an API Routes' response body is over 4MB.
If you are not using Next.js in a serverless environment, and understand the performance implications of not using a CDN or dedicated media host, you can set this limit to false.
responseLimit can also take the number of bytes or any string format supported by bytes, for example 1000, '500kb' or '3mb'. This value will be the maximum response size before a warning is displayed. Default is 4MB. (see above)
The Server Response object, (often abbreviated as res) includes a set of Express.js-like helper methods to improve the developer experience and increase the speed of creating new API endpoints.
The included helpers are:
When sending a response back to the client, you can set the status code of the response.
The following example sets the status code of the response to 200 (OK) and returns a message property with the value of Hello from Next.js! as a JSON response:
When sending a response back to the client you can send a JSON response, this must be a serializable object. In a real world application you might want to let the client know the status of the request depending on the result of the requested endpoint.
The following example sends a JSON response with the status code 200 (OK) and the result of the async operation. It's contained in a try catch block to handle any errors that may occur, with the appropriate status code and error message caught and sent back to the client:
Sending an HTTP response works the same way as when sending a JSON response. The only difference is that the response body can be a string, an object or a Buffer.
The following example sends an HTTP response with the status code 200 (OK) and the result of the async operation.
Taking a form as an example, you may want to redirect your client to a specified path or URL once they have submitted the form.
The following example redirects the client to the / path if the form is successfully submitted:
You can make your API Routes more type-safe by importing the NextApiRequest and NextApiResponse types from next, in addition to those, you can also type your response data:
The body of NextApiRequest is any because the client may include any payload. You should validate the type/shape of the body at runtime before using it.
API Routes support dynamic routes, and follow the same file naming rules used for pages/.
Now, a request to /api/post/abc will respond with the text: Post: abc.
API Routes can be extended to catch all paths by adding three dots (...) inside the brackets. For example:
You can use names other than slug, such as: [...param]
Matched parameters will be sent as a query parameter (slug in the example) to the page, and it will always be an array, so, the path /api/post/a will have the following query object:
And in the case of /api/post/a/b, and any other matching path, new parameters will be added to the array, like so:
Now, a request to /api/post/a/b/c will respond with the text: Post: a, b, c.
Catch all routes can be made optional by including the parameter in double brackets ([[...slug]]).
For example, pages/api/post/[[...slug]].js will match /api/post, /api/post/a, /api/post/a/b, and so on.
The main difference between catch all and optional catch all routes is that with optional, the route without the parameter is also matched (/api/post in the example above).
The query objects are as follows:
While the Pages Router does support streaming responses with API Routes, we recommend incrementally adopting the App Router and using Route Handlers if you are on Next.js 14+.
Here's how you can stream a response from an API Route with writeHead:
Last updated October 15, 2026
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。