getSession and getServerSession don't match #9513
-
i'm trying to use my session data in server actions, and i've run into a problem I can not figure out. When using client side getSession, i'm able to return the entire session data as i would expect it based on my config. But when I try and use getServerSession in a server action, it seems to have a default, premade set of fields. If I have a field that matches the name, it will populate it with correct data, but if i dont it will be undefined. Any help would be appreciated, if you need any further info let me know i'm new to this. Here is my next-auth config// Next-Auth
import NextAuth from 'next-auth';
import EmailProvider from 'next-auth/providers/email';
// Custom Next-Auth Adapter
import { PlanetscaleAdapter } from 'jinma/next-auth/PlanetscaleAdapter';
// import functions
import { getAuthUserByid } from 'jinma/db/dbReads/getAuthUserByid';
export const authOptions = {
providers: [
EmailProvider({
server: process.env.NEXT_AUTH_EMAIL_SERVER,
from: process.env.NEXT_AUTH_EMAIL_FROM,
}),
],
adapter: PlanetscaleAdapter(),
debug: true, // Consider setting to false in production for security
session: {
strategy: 'jwt',
maxAge: 60 * 60 * 24 * 30 * 3, // Max Age set to 3 Months
},
callbacks: {
async jwt({ token, user }) {
if (user) {
// Keep JWT lean with only essential identification data
token.id = user.id;
token.email = user.email;
token.role = user.role || ['guest'];
token.lastTokenRefresh = Date.now();
} else if (
token.lastTokenRefresh &&
Date.now() - token.lastTokenRefresh > 30 * 24 * 60 * 60 * 1000
) {
// Refresh token data from the database
const updatedUser = await getAuthUserByid(token.id);
token.email = updatedUser.email;
token.role = updatedUser.role;
token.lastTokenRefresh = Date.now();
}
return token;
},
/*
I tried this jsut to see if it was a thing. Does not seem to be.
async serverSession({ session, token }) {
// Fetch additional user data and modify session as needed
const userDetails = await getAuthUserByid(token.id);
session.user.id = userDetails.id;
// ... add other fields
return session;
},
*/
async session({ session, token }) {
// Start with basic user info from the token
session.user.email = token.email;
session.user.role = token.role;
session.user.id = token.id;
// Fetch additional user data from the database
const userDetails = await getAuthUserByid(token.id);
console.log('userDetails inside next auth config', userDetails);
// Add non-sensitive additional data to the session object
session.user.name = userDetails.name; // Assuming 'name' is a field in your user details
session.user.avatar = userDetails.avatar;
return session;
},
async signIn({ user, account, profile, email }) {
const existingUser = await getAuthUserByid(user.id);
if (!existingUser) {
// Handle new user creation with a default role
await createUser({ email, role: 'guest' });
}
return true;
},
async redirect({ url, baseUrl }) {
// Ensure redirection is within the site
return url.startsWith(baseUrl) ? `${baseUrl}/portal` : baseUrl;
},
},
pages: {
signIn: '/', // Custom sign-in page
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST }; Here is my server action'use server';
import { dbConn } from '../dbConn';
// next-auth
import { getServerSession } from 'next-auth';
// utils
import { fDateTimeToSQL } from 'jinmin/utils/format-time';
export async function testServerSession(data) {
const session = await getServerSession();
if (session && session.user && session.user.id) {
updateData['authorId'] = session.user.id;
} else {
throw new Error(
'No valid session found. Please log in to update the blog post.'
);
}
// REST OF FUNCTION
} What client session & console log inside the next-auth config looks like data looks likesession: {
id: 1,
name: 'John Doe',
email: 'johndoe@example.com',
avatar: 'https://example.com/avatar.jpg',
role: ['user']
} What server side console log of session looks likesession: {
user: {
name: 'John Doe',
email: 'johndoe@example.com',
image: 'undefined'
}
} (the data inside server side session is correct if it matches the field name. i extra tested this by adding an image field with data and the undefined went to holding the data. but i cant seem to put the fields I want in there, i only have these 3) Thank you very much in advanced for your time, I appreciate it. Let me know what else i can provide to help figure this out. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I thought I tried it already, but It seems my problem was not passing in authOptions to getServerSesion. I thought i tried that alrady so was confused, but tried it again and seems to have fixed it. |
Beta Was this translation helpful? Give feedback.
I thought I tried it already, but It seems my problem was not passing in authOptions to getServerSesion. I thought i tried that alrady so was confused, but tried it again and seems to have fixed it.