i am trying to protect /users
route with oAuth in next-auth while it's working before adding prisma adapter but after prisma adapter, it's not working as expected as the main issue is: when I go to /users
, it redirects me to login with google
but when login successfuly it stuck again on login with google
.
Note: login is working fine but not /users
folder structure:
│auth.ts
│middleware.ts
├(all below are inside app)
│ error.tsx
│ favicon.ico
│ globals.css
│ layout.tsx
│ loading.jsx
│ NavBar.tsx
│ not-found.tsx
│ page.tsx
│
├───admin
│ layout.tsx
│ page.tsx
│
├───api
│ ├───auth
│ │ │ Provider.tsx
│ │ │
│ │ ├───token
│ │ │ route.ts
│ │ │
│ │ └───[...nextauth]
│ │ route copy.ts
│ │ route.ts
│ │
│ ├───products
│ │ │ route.tsx
│ │ │ schema.ts
│ │ │
│ │ └───[id]
│ │ route.tsx
│ │
│ └───users
│ │ route cmnts.tsx
│ │ route.tsx
│ │
│ └───[id]
│ route cmnts.tsx
│ route.tsx
│
├───components
│ AddtoCart.tsx
│ ProductCard.module.css
│ ProductCard.tsx
│
├───fonts
│ GeistMonoVF.woff
│ GeistVF.woff
│
├───products
│ ├───[slug]
│ │ page.tsx
│ │
│ └───[[...slug]]
│ page.tsx
│
├───upload
│ page.tsx
│
└───users
│ page.tsx
│ UserTable.tsx
│
├───new
│ page.tsx
│
└───[id]
│ not-found.tsx
│ page.tsx
│
└───photos
│ page.tsx
│
└───[photoId]
page.tsx
</pre>
auth.ts [root directory]:
export const authOptions : NextAuthOptions = {
adapter: PrismaAdapter(prisma),
providers : [
GoogleProvider( {
clientId: process.env.GOOGLE_CLIENT_ID || "",
clientSecret: process.env.GOOGLE_CLIENT_SECRET || ""
})
],
session: {
strategy: "database"
},
callbacks: {
async redirect({ url, baseUrl }) {
// Redirect to the `/users` route after successful authentication
if (url.startsWith("/api/auth/callback")) {
return `${baseUrl}/users`; // Adjust the redirect path here
}
return baseUrl;
},
}
}
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
middleware.ts [root directory]:
export { default } from "next-auth/middleware";
export const config = {
matcher: ["/users/:id*","/users","/dashboard/:path*"],
};
route.ts
export { GET, POST } from "@/auth";
navbar.tsx:
const NavBar = () => {
const { status, data: session } = useSession();
return (
<div className="flex space-x-8 bg-slate-300 p-3">
<Link href="/" className="mr-5">
Home
</Link>
<Link href="/users">Users</Link>
{status === "loading" && <div>Loading...</div>}
{status === "authenticated" && <div>{session.user!.name}
<Link href="/api/auth/signout?callbackUrl=/" className="ml-4">Sign Out</Link>
</div>}
{status === "unauthenticated" && (
<Link href="/api/auth/signin">Login</Link>
)}
</div>
);
};