I am using Next Auth and have a standalone Node.js API running. I am using Next Auth using credentials and use axios to send the username and password to the API.
On the API side, if the username and password are correct, I set a session using express-session and save it to the database.
If the response status is 201 in Next.js I want to then add the express-session token from the API to my Next.js session.
The below code is working in that I authenticate and when I console.log session in protected pages I see the express-session token that was set on the server. This token is also stored in mongoDB. But is it correct? Is the purpose of this to protect routes on the frontend only ie: checking that there is a session in Next.js
If on the protected pages I need to make an API request, would I then check that session token against the database token for the logged in user?
And lastly, where does JWT fit in here, is this how Next.js is handling the client side auth sessions, using JWT?
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import axios from "axios";
export default NextAuth({
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
},
providers: [
CredentialsProvider({
async authorize(credentials) {
try {
const response = await axios.post(`http://localhost:8000/login`, {
email: credentials.email,
password: credentials.password,
});
if (response.status === 201) {
const user = {
email: credentials.email,
accessToken: response.data.token,
};
return user;
} else {
return null;
}
} catch (err) {
console.log(err.response);
}
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.accessToken = user.accessToken;
}
return token;
},
async session({ session, token, user }) {
session.accessToken = token.accessToken;
return session;
},
},
});