I am using Github Provider
of next-auth
package for signIn in a NextJs 14 Project. This is my authConfig:
import Github from "next-auth/providers/github";
import NextAuth, { NextAuthOptions } from "next-auth";
import User from "@/models/User";
const authOptions: NextAuthOptions = {
providers: [
Github({
clientId: process.env.GITHUB_ID ?? "",
clientSecret: process.env.GITHUB_SECRET ?? "",
}),
],
callbacks: {
async signIn({ user, account, profile, email, credentials }): Promise<boolean> {
......
},
async jwt({ token, user, account, session }) {
if (account) {
token.provider = account.provider;
}
if(account && account.provider == 'github') {
const dbUser = await User.findOne({ github_id: account.providerAccountId }).exec();
token.user_id = dbUser._id.toString();
}
return token;
},
async session({ session, token, user }) {
session.user.user_id = token.user_id as string;
session.user.isAdmin = true;
return session;
},
},
session: {
strategy: "jwt", // default
},
}
export {
authOptions
}
The issue is when fetch session in server component or api route using getServerSession()
the isAdmin
and user_id
fields are missing:
const session = await getServerSession();
console.log(session);
// {
// user: {
// name: 'username',
// email: undefined,
// image: 'image.png'
// }
}
What I need is upadte the session with field user_id
which is the mongoDB _id of user with matching github user id.
Above code update the session and i can see updated session at api endpoint: api/auth/session
.
{
"user": {
"name": "username",
"image": "image.png",
"user_id": "66d54f8d0828ddbf7c0a1256",
"isAdmin": true
},
"expires": "2025-08-02T07:17:33.804Z"
}
I need above result when called from getServerSession
.