[Next.js] Add Middleware to an API Route Created with next-connect

We'll learn how to create a middleware function for next-connect. This middleware will work at the route level, for example, for every request that hits the /api/next-connect-middleware endpoint, or at the HTTP verb level, GET /api/next-connect-middleware

import nextConnect from 'next-connect'

const withAuthentication = (req, res, next) => {
  if (!req.headers.authentication) {
    return res.status(401).json({message: 'error'})
  }

  return next()
}

const handler = nextConnect()
  .use(withAuthentication)
  .get(withAuthentication , (req, res) => res.json({message: 'get'}))

export default handler

 

posted @ 2022-04-03 17:36  Zhentiw  阅读(110)  评论(0编辑  收藏  举报