#App Router and getToken

7 messages · Page 1 of 1 (latest)

livid swan
#

Hi,
I am storing an accessToken in my JWT using the JWT callback. How can I access it in my app router? getServerSession only returns the session. I cant find any documentation how to get the Token using app router? I dont know how to get the req for getToken({req}) like in page router.

quaint helm
#

almost. session.user

import {getServerSession} from "next-auth/next";
import {options} from "@/app/options";

export default async function Home() {
    const session = await getServerSession(options)
    const user = session?.user

    return (
        <main
            style={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                height: "70vh",
            }}
        >
            <div>
                <div>{`${JSON.stringify(user)}`}</div>
                {user ? <div>Logged in</div> : <div>Not logged in</div>}
                {user ? <LogoutButton/> : <LoginButton/>}
            </div>
        </main>
    );
}
#

notice that user contains subset of a JWT token for security concern by default.
thus you need to manually copy if needed in Session callback as well as JWT callback like this:

        callbacks: {
            jwt: async ({token, user, account, profile, isNewUser}) => {
                // Add role to the user info in the token right after sign in
                console.log('in jwt', user)
                if (user) {
                    token.user = user;
                    const u = user as any
                    token.role = u.role;
                }
                return token;
            },
            session: ({ session, token }) => {
                console.log("in session", { session, token });
                return {
                    ...session,
                    user: {
                        ...session.user,
                        role: token.role,
                    },
                };
            },
        }

in my case above , role property is manually copied

livid swan
#

Hi thanks but I dont want to copy it to the user for security reasons 🙂 So my question is how to access the jwt

quaint helm
#

sorry. not user but session as the official doc sample says below:

async session({ session, token, user }) {
    // Send properties to the client, like an access_token and user id from a provider.
    session.accessToken = token.accessToken
    session.user.id = token.id
    
    return session
  }