我是next.js新手,我想知道是否可以通过中间件保护整个API路由。因此,例如,如果我想保护/api/users
,可以在中间件中创建/api/users/_middleware.ts
并处理身份验证,而不必担心实际api端点中的身份验证吗?如果是这样的话,我该怎么做呢?我现在使用的库是@auth0\nextjs-auth0
,所以我猜它会像这样吗?(此外,如果我编码错误,请原谅,我是在堆栈溢出编辑器中这样做的)
export default authMiddleware(req,res)=>{
const {user,error,isLoading} = whateverTheNameOfTheAuth0HookIs()
if(user)
{
// Allow the request to the api route
}
else
{
// Deny the request with HTTP 401
}
}
我的大致想法正确吗?
发布于 2022-12-03 09:15:53
下一代v4为此引入了中间件。基本用例非常简单。您可以添加具有以下内容的middleware.js文件:
export { default } from "next-auth/middleware"
export const config = { matcher: ["/dashboard"] }
其他用例可以在文档中找到。
发布于 2022-02-10 20:16:06
您可以使用中间件,类似于文档中的这个例子。
对于pages
中的子目录,您可以创建一个_middleware.ts
文件.它将为该目录中的所有页面运行。看起来是这样的:
import { NextRequest, NextResponse } from 'next/server'
export function middleware(req: NextRequest) {
const basicAuth = req.headers.get('authorization')
if (basicAuth) {
// do whatever checks you need here
const hasAccess = ...
if (hasAccess) {
// will render the specified page
return NextResponse.next()
}
}
// will not allow access
return new Response('No access', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Secure Area"',
},
})
}
您可以在文档中找到更多信息。
https://stackoverflow.com/questions/71071601
复制相似问题