1

我在 Next.js 中构建了一个简单的 API,并使用 next-auth 进行身份验证。

到目前为止,我必须在每个 API 路由中使用这样的东西:

  const session = await getSession({ req });
  if (session) {
    ... do something ...
  } else {
    ... send back a 401 status
  }

这似乎违背了 DRY 原则。有没有一种聪明的方法可以在一个地方对多个路由应用保护,例如 Laravel 路由组?

4

2 回答 2

3

做一个中间件!

如果您不使用 TS,请忽略输入

import { NextApiRequest, NextApiResponse } from 'next/types'
import { getSession } from 'next-auth/client'

export const protect = async (
  req: NextApiRequest,
  res: NextApiResponse,
  next: any
) => {
  const session = await getSession({ req })
  if (session) {
    console.log(session)
    next()
  } else {
    res.status(401)
    throw new Error('Not authorized')
  }
}
于 2021-02-15T08:01:40.280 回答
1

创建一个获取会话的中间件,否则返回 401。

请参阅关于api 中间件的NextJS 文档。您还可以在 github 存储库中
查看他们的示例。

于 2021-02-10T22:56:14.867 回答