我希望在 NextJS
middleware.ts
中使用条件,并且使用环境变量来决定匹配器字段的哪些部分。 ["/folder/(.*)"]
或 ["/no-match"]
。
据我了解,这是有效的 JavaScript,因为我在独立页面中得到了预期的结果测试。
export { default } from "next-auth/middleware"
export const config = {
matcher:
process.env.NEXT_PUBLIC_AUTH_USERS === "true"
? ["/folder/(.*)"]
: ["/no-match"],
}
注意:
"true"
因为布尔环境参数是字符串。
我收到错误:
Unsupported node type "ConditionalExpression" at "config.matcher".
The default config will be used instead.
Read More - https://nextjs.org/docs/messages/invalid-page-config
它说条件不允许,那么我还有其他方法可以使用这个逻辑吗?
更改为其中一个选项效果很好。
您可以自定义授权回调以进行条件检查。就我而言,如果在开发中,我想使用环境变量来跳过登录。我在遇到与您相同的错误后找到了这篇文章。
请参阅 https://next-auth.js.org/configuration/nextjs#callbacks 了解更多信息。
就您而言,您可以执行以下操作:
import {
withAuth
} from "next-auth/middleware";
export default withAuth({
callbacks: {
authorized: ({
token
}) => !!token && process.env.NEXT_PUBLIC_AUTH_USERS === "true"
},
}, );
export const config = {
matcher: ["/folder/(.*)"]
}
如果用户登录则设置Token,否则为空。