API routes provide built in middlewares which parse the incoming request (req
). Those middlewares are:
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 by content-type
, or null
if no body was sentEvery API route can export a config
object to change the default configs, which are the following:
export const config = {
api: {
bodyParser: {
sizeLimit: '1mb',
},
},
}
The api
object includes all configs available for API routes.
bodyParser
Enables body parsing, you can disable it if you want to consume it as a Stream
:
export const config = {
api: {
bodyParser: false,
},
}
bodyParser.sizeLimit
is the maximum size allowed for the parsed body, in any format supported by bytes, like so:
export const config = {
api: {
bodyParser: {
sizeLimit: '500kb',
},
},
}
As an added bonus, you can also use any Micro compatible middleware.
For example, configuring CORS for your API endpoint can be done leveraging micro-cors.
First, install micro-cors
:
npm i micro-cors
# or
yarn add micro-cors
Now, let's add micro-cors
to the API route:
import Cors from 'micro-cors'
const cors = Cors({
allowMethods: ['GET', 'HEAD'],
})
function handler(req, res) {
res.json({ message: 'Hello Everyone!' })
}
export default cors(handler)