#App Router and getToken
7 messages · Page 1 of 1 (latest)
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
Callbacks are asynchronous functions you can use to control what happens when an action is performed.
Hi thanks but I dont want to copy it to the user for security reasons 🙂 So my question is how to access the jwt
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
}
you can get it via cookies()