On several pages of my website, I require the user to be logged in. To achieve this, I have implemented middleware to check if the user is authenticated and blocked access to certain pages until the user logs in. Below is the code snippet from my file:
export {default} from "next-auth/middleware";
export const config = {
matcher: ["/api/:path*", "/new"]
}
Even though a user is already logged in and tries to access the /new route, they are prompted to login again. The expected behavior is for authenticated users to access the route without re-logging in. The issue seems to be with the /api/* path.
I am using Prisma as the adapter for authentication. Here is my next-auth configuration file:
// /api/auth/[...nextauth]/options.ts
import { prisma } from "@/lib/database";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { type NextAuthOptions } from "next-auth";
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
secret: process.env.NEXTAUTH_SECRET,
session: {
maxAge: 30 * 60,
},
debug: process.env.NODE_ENV === "development" ? true : false,
pages: {
signIn: "/auth/login",
},
providers: [
GithubProvider({
clientId: process.env.APP_GITHUB_CLIENT_ID as string,
clientSecret: process.env.APP_GITHUB_CLIENT_SECRET as string,
}),
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
}),
],
};
I import this configuration into /api/auth/[...nextauth]/route.ts
as shown below:
import NextAuth from "next-auth/next";
import { authOptions } from "./options";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
Here is my schema.prisma
file:
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
relationMode = "prisma"
}
model Todo {
id String @id @default(cuid())
todo_name String
todo_description String?
completed Boolean? @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User? @relation(fields: [userId], references: [id])
userId String?
@@index([userId])
}
<!-- More model definitions -->
model VerificationToken {
identifier String
token String @unique
expires DateTime
@@unique([identifier, token])
}
Your assistance on this matter would be greatly appreciated.