NextAuth session (App router)
Unanswered
Rough harvester ant posted this in #help-forum
Rough harvester antOP
I need to update a session.
This calls a
When the
const { data: session, update } = useSession();
...
async () => {
if (nameInputRef.current?.value) {
console.log("Setting name in session to ", nameInputRef.current?.value)
await update({ ...session, user: { ...session.user, name: nameInputRef.current?.value } })
setTutorialStage(1);
} else {
nameInputRef.current?.focus();
}
}This calls a
POST request to /api/auth/session. I had to manually create a route in /api/auth/session as the session kept initially loading well but then returning undefined. The route (/api/auth/session/route.ts) I created is this:import { auth } from '@/auth';
import { authConfig } from '@/auth.config';
import NextAuth from 'next-auth';
import getServerSession from 'next-auth';
import { NextResponse } from 'next/server';
export async function GET(request: Request) {
const session = await getServerSession(authConfig).auth();
console.log(session);
return NextResponse.json(session);
}When the
POST request is called, there isn't a route defined for it as I'm not sure how to update the token. I know it'll be something along the lines ofexport async function POST(request: Request) {
// update the session
}1 Reply
Rough harvester antOP
and following youtube tutorials I've added the following to the callbacks:
But I'm honestly not sure how it works and the docs are appalling.
export const authConfig: NextAuthConfig = {
...
callbacks: {
...
async jwt({ token, user, trigger, session }) {
if (user) {
token.userId = user.id; // Assuming 'user.id' is the userID from your user model
token.name = (trigger == "update" && session.name) ? session.name : user.name;
token.email = user.email;
token.role = user.role;
}
return token;
},
async session({ session, token }) {
if (session.user && token.userId) {
// console.log("session.user: ", session.user)
// console.log("token.userId: ", token.userId)
session.user = {
id: token.userId as string, // Replace or extend the user object with the userId
name: token.name, // Retain existing session.user.name if necessary
email: token.email || "", // Retain existing session.user.email if necessary
role: token.role as string,
};
}
return session;
},But I'm honestly not sure how it works and the docs are appalling.