Back

Google Login Session Cookie Help

  • 0
  • Auth
  • Cloud
NHero
24 Sep, 2024, 13:54

can someone tell, after i use google login in server side i set the cookie and return the redirect response but in my middleware session is still undefined and it re redirects to /login and when i refresh the page the session is available in middleware how can i fix that ?

my middleware code for redirecting

TypeScript
const user = await getLoggedInUser()
const isLoginPage = req.nextUrl.pathname === "/login"
const isRegisterPage = req.nextUrl.pathname === "/register"

if (!user && !isLoginPage && !isRegisterPage) {  
  
  const url = req.nextUrl.clone()
  url.pathname = "/login"
  return NextResponse.redirect(url)

}

my /api/oauth which is success url for account.createOAuth2Token()

TypeScript
cookies().set(SESSION_COOKIE, session.secret, {
  path: "/",
  httpOnly: true,
  sameSite: "strict",
  secure: true,
});

const res = NextResponse.redirect("http://localhost:3000/home")

return res;

getLoggedInUser()

TypeScript
export async function getLoggedInUser() {
  try {
    const { account } = await createSessionClient()
    const user = await account.get()
    
    return user;
  } catch (err) {
    return null;
  }
}
TL;DR
Developers are facing issues with Google login session cookies in middleware. The session is initially undefined and redirects to /login, but the session becomes available after a page refresh. The issue can be fixed by ensuring the proper handling of the user's login status and session within the middleware to prevent premature redirects.
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more