Trigger Session update ( to update user data)
Hey im updating user data after signin with google basically I assign a username and a checkbox to agree TOS. User is always redirected this onboarding page as long as he has 'pending' role.
basically, after he submit his data i update him to a user role and he can browse the app now.
How can I trigger/refresh session data to get the current state of the user from db?
middleware :
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
import { betterFetch } from "@better-fetch/fetch";
import { auth } from "./lib/auth";
const authRoutes = ["/sign-in"];
const onBoarding = ["/on-boarding"];
type Session = typeof auth.$Infer.Session;
export async function middleware(request: NextRequest) {
const sessionCookie = getSessionCookie(request);
const { data: session } = await betterFetch<Session>(
"/api/auth/get-session",
{
baseURL: request.nextUrl.origin,
headers: {
// Get the cookie from the request headers
cookie: request.headers.get("cookie") || "",
},
}
);
const pathName = request.nextUrl.pathname;
const isAuthRoute = authRoutes.includes(pathName);
const isOnBoardingRoute = onBoarding.includes(pathName);
if (pathName === "/") {
return NextResponse.next();
}
if (!sessionCookie) {
if (isAuthRoute) {
return NextResponse.next();
}
return NextResponse.redirect(new URL("/sign-in", request.url));
}
// check if user role is pending redirect them to onboarding to set username
if (session?.user.role === "pending" && !isOnBoardingRoute) {
return NextResponse.redirect(new URL("/on-boarding", request.url));
}
if (isAuthRoute) {
return NextResponse.redirect(new URL("/", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
"/((?!api|_next/static|_next/image|.\.png$).)",
"/dashboard",
"/library",
],
// Specify the routes the middleware applies to
};
1 Reply
export async function handleOnBoarding(
unsafeData: z.infer<typeof onBoardingSchema>
) {
const { success, data } = onBoardingSchema.safeParse(unsafeData);
if (!success) {
return { error: true, message: "Invalid input data" };
}
const session = await getSessionUser();
if (!session) {
return { error: true, message: "User session not found" };
}
const user = session.user;
await updateUserOnboarding({
userId: user.id,
username: data.username,
TOS: data.TOS,
});
console.log("User onboarding completed:", data);
redirect("/dashboard");
}
this is my server action for handling the onboarding
oh my bad
i was caching the session it works now when removing the caching setting
session: {
cookieCache: {
enabled: true,
maxAge: 5 * 60, // Cache duration in seconds
},
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg", // or "mysql", "sqlite"
schema: schema,
}),
session: {
cookieCache: {
enabled: true,
maxAge: 5 * 60, // Cache duration in seconds
},
},
user: {
additionalFields: {
role: {
type: "string",
required: true,
},
username: {
type: "string",
required: true,
},
streaks: {
type: "number",
required: true,
},
credits: {
type: "number",
required: true,
},
},
},
/* account: {
accountLinking: {
enabled: true,
trustedProviders: ["google"],
},
}, */
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
},
plugins: [jwt()],
});