Facing Issues in Session Management in Client side

I am using Better Auth for my new project. But I'm facing issue with session management and redirection. My goal is to redirect the user to the login page and log out automatically. I tried this function to get the session data, but it gives null value. const { data: sessionData } = await authClient.getSession(); I have tried to use this, but I cannot understand it fully. In Next.js middleware, it's recommended to only check for the existence of a session cookie to handle redirection. To avoid blocking requests by making API or database calls. You can use the getSessionCookie helper from Better Auth for this purpose: The getSessionCookie() function does not automatically reference the auth config specified in auth.ts. Therefore, you need to ensure that the configuration in getSessionCookie() matches the config defined in your auth.ts. import { NextRequest, NextResponse } from "next/server";import { getSessionCookie } from "better-auth/cookies"; export async function middleware(request: NextRequest) {const sessionCookie = getSessionCookie(request); if (!sessionCookie) {return NextResponse.redirect(new URL("/", request.url));} return NextResponse.next();} export const config = {matcher: ["/dashboard"], // Specify the routes the middleware applies to}; How can automatically logout the user? Currently backend sends unauthorised response, but I am not able to handle it in client. It should redirect to login page again. Any suggestions?
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?