API Middlewares

Examples

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:

  1. export const config = {
  2. api: {
  3. bodyParser: {
  4. sizeLimit: '1mb',
  5. },
  6. },
  7. }

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:

  1. export const config = {
  2. api: {
  3. bodyParser: false,
  4. },
  5. }

bodyParser.sizeLimit is the maximum size allowed for the parsed body, in any format supported by bytes, like so:

  1. export const config = {
  2. api: {
  3. bodyParser: {
  4. sizeLimit: '500kb',
  5. },
  6. },
  7. }

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.

  1. export const config = {
  2. api: {
  3. externalResolver: true,
  4. },
  5. }

Connect/Express middleware support

You can also use Connect compatible middleware.

For example, configuring CORS for your API endpoint can be done leveraging the cors package.

First, install cors:

  1. npm i cors
  2. # or
  3. yarn add cors

Now, let’s add cors to the API route:

  1. import Cors from 'cors'
  2. // Initializing the cors middleware
  3. const cors = Cors({
  4. methods: ['GET', 'HEAD'],
  5. })
  6. // Helper method to wait for a middleware to execute before continuing
  7. // And to throw an error when an error happens in a middleware
  8. function runMiddleware(req, res, fn) {
  9. return new Promise((resolve, reject) => {
  10. fn(req, res, (result) => {
  11. if (result instanceof Error) {
  12. return reject(result)
  13. }
  14. return resolve(result)
  15. })
  16. })
  17. }
  18. async function handler(req, res) {
  19. // Run the middleware
  20. await runMiddleware(req, res, cors)
  21. // Rest of the API logic
  22. res.json({ message: 'Hello Everyone!' })
  23. }
  24. export default handler

Go to the API Routes with CORS example to see the finished app

Extending the req/res objects with TypeScript

For better type-safety, it is not recommended to extend the req and res objects. Instead, use pure functions to work with them:

  1. // utils/cookies.ts
  2. import { serialize, CookieSerializeOptions } from 'cookie'
  3. import { NextApiResponse } from 'next'
  4. /**
  5. * This sets `cookie` using the `res` object
  6. */
  7. export const setCookie = (
  8. res: NextApiResponse,
  9. name: string,
  10. value: unknown,
  11. options: CookieSerializeOptions = {}
  12. ) => {
  13. const stringValue =
  14. typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value)
  15. if ('maxAge' in options) {
  16. options.expires = new Date(Date.now() + options.maxAge)
  17. options.maxAge /= 1000
  18. }
  19. res.setHeader('Set-Cookie', serialize(name, String(stringValue), options))
  20. }
  21. // pages/api/cookies.ts
  22. import { NextApiRequest, NextApiResponse } from 'next'
  23. import { setCookie } from '../../utils/cookies'
  24. const handler = (req: NextApiRequest, res: NextApiResponse) => {
  25. // Calling our pure function using the `res` object, it will add the `set-cookie` header
  26. setCookie(res, 'Next.js', 'api-middleware!')
  27. // Return the `set-cookie` header so we can display it in the browser and show that it works!
  28. res.end(res.getHeader('Set-Cookie'))
  29. }
  30. export default handler

If you can’t avoid these objects from being extended, you have to create your own type to include the extra properties:

  1. // pages/api/foo.ts
  2. import { NextApiRequest, NextApiResponse } from 'next'
  3. import { withFoo } from 'external-lib-foo'
  4. type NextApiRequestWithFoo = NextApiRequest & {
  5. foo: (bar: string) => void
  6. }
  7. const handler = (req: NextApiRequestWithFoo, res: NextApiResponse) => {
  8. req.foo('bar') // we can now use `req.foo` without type errors
  9. res.end('ok')
  10. }
  11. export default withFoo(handler)

Keep in mind this is not safe since the code will still compile even if you remove withFoo() from the export.