I am trying to implement NextAuth with Credentials (email and password).
I have set up my mongodb for this. I also set up /api/proile/
route to post login credentials and tested it out with Postman, returns user correctly.
But the problem starts with after logging in. when I log in, credentials return in the vscode terminal (I console log in /api/auth/[...nextauth].js
with console.log(credentials)
but in the browser it authorizes the user, i can access and view protected routes and stuff, but when I log the session in front-end, it displays as null
for user information as you can see in the picture below;
here is my /api/auth/[...nextauth].js
code;
import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
import { connectToDatabase } from '../../../util/mongodb';
const options = {
providers: [
Providers.Credentials({
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'text' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials, req) {
console.log(credentials);
const res = await fetch('http://localhost:3000/api/profile/', {
method: 'POST',
body: JSON.stringify(credentials),
headers: {
'Content-Type': 'application/json',
},
});
const user = await res.json();
// const user = { id: '1', name: 'Suat Bayrak', email: '[email protected]' };
if (user) {
return user;
} else {
return null;
}
},
}),
],
pages: {
signIn: '/signin',
},
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
updateAge: 24 * 60 * 60,
},
database: `mongodb+srv://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}@nextjs-academia- sb.ki5vd.mongodb.net/test`,
};
export default (req, res) => NextAuth(req, res, options);
by the way, when I use static user credentials like i commented in the code above, it works perfectly fine and returns session info correctly...
Also here is my /pages/signin.js
import { signIn } from 'next-auth/client';
import { useState } from 'react';
import { useRouter } from 'next/router';
export default function SignIn() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loginError, setLoginError] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
console.log('submitted!');
signIn('credentials', {
email: email,
password: password,
// email: '[email protected]',
// password: '1234',
callbackUrl: 'http://localhost:3000/about',
redirect: false,
}).then(function (result) {
console.log(result);
if (result.error !== null) {
if (result.status === 401) {
setLoginError(
'Your username/password combination was incorrect. Please try again'
);
} else {
setLoginError(result.error);
}
} else {
console.log(result);
router.push(result.url);
}
});
};
return (
<form onSubmit={handleSubmit}>
<label>
Email
<input
name='email'
type='text'
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</label>
<label>
Password
<input
name='password'
type='password'
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</label>
<button type='submit'>Sign in</button>
</form>
);
}
also here is my github repo for this whole code; GitHub Repo
UPDATE: At first login, user info displays on the terminal but after I refresh the page, it says undefined
import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
const options = {
providers: [
Providers.Credentials({
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'text' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials, req) {
console.log(credentials);
let user;
const res = await fetch('http://localhost:3000/api/profile/', {
method: 'POST',
body: JSON.stringify(credentials),
headers: {
'Content-Type': 'application/json',
},
});
const arrayToJson = await res.json();
user = arrayToJson[0];
if (user) {
return user;
} else {
return null;
}
},
}),
],
pages: {
signIn: '/signin',
},
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
updateAge: 24 * 60 * 60,
},
callbacks: {
async signIn(user) {
return user.userId && user.isActive === '1';
},
async session(session, token) {
session.user = token.user;
return session;
},
async jwt(token, user) {
if (user) token.user = user;
return token;
},
},
database: `mongodb+srv://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}@nextjs-academia-sb.ki5vd.mongodb.net/test`,
};
export default (req, res) => NextAuth(req, res, options);
so the problem was at callbacks
section of the code. Now its working fine