rsnext/docs/api-routes/api-middlewares.md
Luis Alvarez D d1fdd2bbf8 Add descriptions to documentation pages (#9901)
* Added descriptions

* Added descriptions to API Reference

* Added descriptions to API Routes

* Added descriptions to basic features

* Added descriptions to the routing docs

* Update exportPathMap.md

Co-authored-by: Joe Haddad <timer150@gmail.com>
2020-01-03 13:16:51 -05:00

1.9 KiB

description
API Routes provide built-in middlewares that parse the incoming request. Learn more about them here.

API Middlewares

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 sent

Custom config

Every 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',
    },
  },
}

Micro support

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)