session is null using nextAuth
Unanswered
Finnish Spitz posted this in #help-forum
Finnish SpitzOP
i'm try to make a login form that will strore to db, i am success to store them into mysql but, when i am checking the session, it return null
5 Replies
Finnish SpitzOP
api/auth/[...nextauth]/route.js
export const authOptions = {
session : {
strategy: 'jwt'
},
adapter: PrismaAdapter(prisma),
providers: [
CredentialsProvider({
name: 'Sign in Broo',
credentials: {
email: { label: "email", type: "email", placeholder: "jsmith" },
password: { label: "Password", type: "password" }
},
pages :{
signIn : '/signin'
},
async authorize(credentials) {
const res = await fetch('http://localhost:3000/api/login',{
method: 'POST',
headers:{
"Content-Type" : "application/json",
},
body: JSON.stringify({
email: credentials?.email,
password: credentials?.password
})
})
const user = await res.json()
if(user)
return user
else return null
}
})
],
secret : process.env.NEXTAUTH_SECRET,
debug : process.env.NODE_ENV === 'development'
}
api/login
import { NextResponse } from "next/server";
import prisma from '../../libs/prismadb'
import bcrypt from "bcrypt";
export async function POST(req) {
const res = await req.json(); // {res:{email...}}
const { email, password } = res;
if (!email || !password)
return NextResponse.json({ OK: false, message: "Missing input field(s)" });
const exist = await prisma.user.findUnique({
where: {email},
});
if (!exist) {
return NextResponse.json({OK: false, message: "User did not found"})
}
//If user is exist
const match = await bcrypt.compare(password, exist.password);
if(match)
return NextResponse.json({OK: true, message: "Success to login", userData: exist})
else
return NextResponse.json({OK: false, message: "Failed to login", userData: null})
}
i am not sure for my code hehe
formComponent frontend
const handleForm = async (event:any) => {
event.preventDefault();
const res = await fetch('http://localhost:3000/api/login',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email,password }),
})
const result = await res.json()
console.log(result)
if(result.OK)
router.push('/')
else
alert('Can not Login')
};
authContext.js
"use client";
import { SessionProvider } from "next-auth/react"
export default function AuthContext({ children }){
return <SessionProvider>{children}</SessionProvider>;
}