please I am trying to protect some routes with the NextJS middleware if I am not authenticated, I am using next-auth for authentication and from the documentation this is what it says the middleware.ts file should be like
如果我没有通过身份验证,我正在尝试使用NextJS中间件保护一些路由,我正在使用Next-auth进行身份验证,从文档中看,这就是MIDDLEWAR.TS文件应该是什么样子
export { default } from "next-auth/middleware";
export const config = {
matcher: "/room/:id*"
};
The issue rn is even when I am authenticated and I try to go to the room route, it redirects me to a page to sign in again and even when I do that it just redirects me back again, sort of like a loop now. I don't know what I might be doing wrong. Anyone knows what might be causing this ?
Rn的问题是,即使当我通过身份验证并尝试进入房间路径时,它也会将我重定向到一个页面以再次登录,即使我这样做了,它也只是再次重定向我,有点像现在的循环。我不知道我可能做错了什么。有人知道这可能是什么原因吗?
This is my next-auth API :
这是我的Next-auth接口:
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { PrismaClient } from "@prisma/client";
import { generateRandomString } from "@/utils/random";
const prisma = new PrismaClient();
const handler = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code"
}
}
})
],
secret: process.env.JWT_SECRET!,
callbacks: {
async signIn({ user, profile }) {
const existingUser = await prisma.user.findUnique({
where: { email: user.email! }
});
if (!existingUser) {
const randomSuffix = generateRandomString();
const firstName = user.name?.split(" ")[0].toLocaleLowerCase();
await prisma.user.create({
data: {
email: user.email!,
name: user.name!,
username: `${firstName}#${randomSuffix}`,
image: user.image || profile?.image || null
}
});
}
return true;
},
async jwt({ token, user }) {
if (user) {
token.id = user.id;
}
return token;
}
}
});
export { handler as GET, handler as POST };
更多回答
优秀答案推荐
我是一名优秀的程序员,十分优秀!