I'm using:
nextJS: 13.1.6
nextAuth 4.19.2
I'm using the new app/ directory, which is still in Beta.
My problem is that I'm trying to retrieve information about the user in a page, then do logic based on that information. For example, to use the userID, and grab extra info from the database (then prerender the page on the server side).
In [..nextauth.js], I've added extra information in the jwt and session callbacks like so:
callbacks: {
async jwt({token, user}) {
if (user?.id) {
token.id = user.id
}
if (user?.userName) {
token.userName = user.userName;
}
if (user?.fullname) {
token.fullname = user.fullname;
}
return token
},
async session({session, token, user}) {
session.userID = token.id;
session.userName = token.userName;
session.fullname = token.fullname;
//I also tried it this way, according to the docs at:
// https://next-auth.js.org/configuration/callbacks
session.user.userID = token.id;
session.user.fullname = token.fullname;
return session;
}
},
In the client side, I am able to retrieve data such as userName like this:
"use client"; // this is a client component.
import { useSession, signIn, signOut } from "next-auth/react"
export default function LoginPlaceholder() {
const { data: session } = useSession();
if(session) {
console.log(session);
return <>
Welcome, {session.userName}
<button onClick={() => signOut()}>Sign out</button>
</>
}
return <>
<br/>
Not signed in <br/>
<button onClick={() => signIn()}>Sign in</button>
</>
}
However, on the server side, I am unable to retrieve additional information.
export default async function EditUsernamePasswordPage(props) {
const data = await getData();
//this is how to get session data in the Next.js 13 apps folder
//https://twitter.com/nextauthjs/status/1589719535363715072?lang=en
const session = await getServerSession();
console.log(session);
return <pre>{JSON.stringify(session, null, 2)}</pre>;
}
Returns data like this (all of the extra information is missing):
{
user: {
name: 'John Smith Jr',
email: '[email protected]',
image: undefined
}
}
In my [...nextauth].js authorize(credentials) script, I'm returning a user object that looks like this:
{
id: '123456',
userName: 'myUserName',
email: '[email protected]',
fullname: 'John Smith Jr',
name: 'John Smith Jr'
}
How can I get access to data such as userID on the server side?