Back

[SOLVED] getLoggedInUser of Google OAuth SSR gives null once logged in success

  • 0
  • Auth
  • Web
  • Cloud
richardoey
27 Jun, 2024, 13:42

I'm really sure there is bug. Step to reproduce:

  1. download this project https://github.com/appwrite/demos-for-react/tree/master/nextjs/server-side-rendering
  2. Change OAuth sign in, from Github with Google
TypeScript
"use server";

import { createAdminClient } from "./appwrite";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { OAuthProvider } from "node-appwrite";

export async function signInWithGoogle() {
  const { account } = await createAdminClient();

  const origin = headers().get("origin");
  const successUrl = `${origin}/oauth`;
  const failureUrl = `${origin}/signin`;

  const redirectUrl = await account.createOAuth2Token(
    OAuthProvider.Google,
    successUrl,
    failureUrl
  );

  redirect(redirectUrl);
}
  1. npm run dev
  2. Sign in with google
  3. You will redirect to sign in page because of below lines. Means, getLoggedInUser is null.
TypeScript
// app/account/page.tsx
const user = await getLoggedInUser();
if (!user) redirect("/signin");
  1. Refresh the page, then you will be redirected to /account page.

Maybe there is some delay, with the session, i'm not sure, but I have checked my local browser, and session in Appwrite console exist.

TL;DR
Issue: Google OAuth Single Server Rendering (SSR) returns null for getLoggedInUser after successful login. Solution: Update the `/app/oauth/route.ts` file in the project by adding the cookie to the NextResponse before returning it, as shown in the code snippet provided in the thread. This should resolve the issue of getLoggedInUser returning null after logging in successfully.
Ryan
27 Jun, 2024, 13:52

I think I ran into a similar problem the other day. It's how Next handles redirects from what I can tell. The way I fixed it was by adding the cookie to the NextResponse as well at the end before returning it in /app/oauth/route.ts

TypeScript
const response = NextResponse.redirect(`${request.nextUrl.origin}/account`);
response.cookies.set(SESSION_COOKIE, session.secret);
return response;
richardoey
27 Jun, 2024, 13:56

Wahh, thank you for your help. It works like you said. need to add the cookie. Thanks a lot @Ryan

richardoey
27 Jun, 2024, 13:57

[SOLVED] getLoggedInUser of Google OAuth SSR gives null once logged in success

Ryan
27 Jun, 2024, 13:57

No worries, I'll see if I can put in a PR/issue to update the repo

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