i have a 3 page in middleware array
export { default } from 'next-auth/middleware';
export const config = { matcher: [‘/product’,’/shipping’] };
and when user ‘unauthenticated’ everything works well,after login redirect to home page(as intended ) but later, when I return to the protected pages already authorized by the user, it again transfers to login page http://localhost:3000/?callbackUrl=http%3A%2F%2Flocalhost%3A3000%2Fproduct
.
If you reload the page, you can access all protected pages, of course, if the user authorized.
import { LoginForm } from '@/components';
import { getServerSession } from 'next-auth';
import { redirect } from 'next/navigation';
import { authOptions } from '../../api/auth/[...nextauth]/route';
const Login =async() => {
const session = await getServerSession(authOptions);
if (session) redirect('/');
return <LoginForm />;
};
export default Login;
import bcrypt from 'bcryptjs';
import { NextAuthOptions } from 'next-auth';
import NextAuth from 'next-auth/next';
import CredentialsProvider from 'next-auth/providers/credentials';
import { connectMongoDB } from '../../../../../lib/db';
import User from '../../../../../models/user';
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: 'credentials',
credentials: { email: {}, password: {} },
async authorize(credentials) {
const email = credentials?.email;
try {
await connectMongoDB();
const user = await User.findOne({ email });
if (!user) {
return null;
}
const passwordMatch = await bcrypt.compare(credentials?.password || '', user.password);
if (!passwordMatch) {
return null;
}
return user;
} catch (e) {
console.log(e);
}
},
}),
],
callbacks: {
async jwt({ token, user, session, trigger }) {
console.log('jwt callback', { token, user, session });
if (trigger === 'update' && session?.name) {
token.name = session.name;
}
// await connectMongoDB();
// const NewUser = await User.findById(token.id);
// NewUser.name = token.name;
// await NewUser.save();
if (user) {
return {
...token,
id: user.id,
company: user.company,
};
}
return token;
},
async session({ session, token, user }) {
console.log('session callback', { session, token, user });
return {
...session,
user: {
...session.user,
id: token.id,
company: token.company,
},
};
},
},
session: {
strategy: 'jwt',
},
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: '/',
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
Дима Куринной is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.