I'm encountering an error while implementing Next.js middleware for session authentication. The error message I'm receiving is "Cannot read properties of undefined (reading 'substring')". Despite my efforts, I'm unable to resolve this issue and need assistance in understanding its root cause and how to fix it.
middleware.js
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "./app/api/auth/[...nextauth]/route";
export default async function Middleware(request){
const session = await getServerSession(request, authOptions);
if(request.nextUrl.pathname != "/"){
return NextResponse.redirect(new URL("/", request.url));
}
}
export const config={
matcher: "/welcome"
}
route.js
import { connectDB } from "@/app/database";
import User from "@/app/models/user";
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRECT,
}),
],
callbacks: {
async session({ session }) {
const sessionUser = await User.findOne({email: session.user.email})
session.user = sessionUser
return session;
},
async signIn({ profile }) {
try {
await connectDB();
const userExist = await User.findOne({ email: profile.email });
if(!userExist){
const user = User.create({
email: profile.email,
username: profile.name,
image: profile.image,
isfirst: true
})
}
return true;
} catch (error) {
console.log(error);
return false;
}
},
},
};
const handler = NextAuth(authOptions)
export { handler as GET, handler as POST };
I expected that upon accessing any route, the middleware would check the user's session status. If authenticated, it would seamlessly redirect them to the welcome page ("/welcome").