API Routes Request Helpers
API Routes provide built-in request helpers which parse the incoming request ():
req.cookies
- An object containing the cookies sent by the request. Defaults to{}
req.query
- An object containing the query string. Defaults to{}
req.body
- An object containing the body parsed bycontent-type
, ornull
if no body was sent
Every API Route can export a config
object to change the default configuration, which is the following:
The api
object includes all config options available for API Routes.
One use case for disabling the automatic bodyParsing
is to allow you to verify the raw body of a webhook request, for example from GitHub.
export const config = {
api: {
bodyParser: false,
},
bodyParser.sizeLimit
is the maximum size allowed for the parsed body, in any format supported by , 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.
export const config = {
api: {
externalResolver: true,
},
}
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)
export const config = {
api: {
responseLimit: '8mb',
}
For better type-safety, it is not recommended to extend the req
and res
objects. Instead, use functions to work with them:
// pages/api/foo.ts
import { NextApiRequest, NextApiResponse } from 'next'
import { withFoo } from 'external-lib-foo'
type NextApiRequestWithFoo = NextApiRequest & {
foo: (bar: string) => void
}
const handler = (req: NextApiRequestWithFoo, res: NextApiResponse) => {
req.foo('bar') // we can now use `req.foo` without type errors
res.end('ok')
}
Keep in mind this is not safe since the code will still compile even if you remove withFoo()
from the export.