zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

JSAPI to with an connect add Next
2023-09-14 08:59:12 时间

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