Next.js Discord

Discord Forum

Oauth Callback Route Handler redirect requires refresh to load authed state

Unanswered
Buller's Shearwater posted this in #help-forum
Open in Discord
Buller's ShearwaterOP
When I'm redirected from my route handler, the cookie is set in the browser, but the serverside call I try to make is unable to fetch the user.

The Oauth provider redirects to my Appwrite backend, which redirecs me back to my route handler.

This only happens when I'm actually leaving the page and coming back, for example to approve a request on the providers website. If I am pre-approved, and stay on my website, the user gets authentiated and the page refreshes with the logged in state.

This is what my route handler looks like:

src/app/callback/oauth
import { revalidatePath } from "next/cache";
import { cookies } from "next/headers";
import { NextResponse, type NextRequest } from "next/server";
import { SESSION_COOKIE_NAME } from "~/constants/auth";

import { createAdminClient } from "~/lib/server/appwrite";
import { createDefaultCookie } from "~/utils/cookies";

export const GET = async (request: NextRequest) => {
  const url = new URL(request.nextUrl);
  const userId = url.searchParams.get("userId");
  const secret = url.searchParams.get("secret");

  const error = url.searchParams.get("error");

  if (error) {
    return new Response(null, {
      status: 302,
      headers: {
        Location: "/login",
      },
    });
  }

  if (!userId || !secret) {
    return new Response(null, {
      status: 400,
    });
  }

  const { account } = await createAdminClient();

  const session = await account.createSession(userId, secret);

  cookies().set(
    SESSION_COOKIE_NAME,
    session.secret,
    createDefaultCookie(session),
  );
  revalidatePath("/", "layout");
    return NextResponse.redirect("/onboarding?success=true");

};


src/app/layout.tsx
  const user = await getLoggedInUser();

2 Replies

Buller's ShearwaterOP
src/lib/server/auth.ts
"use server";
import { cache } from "react";
import { createSessionClient } from "~/lib/server/appwrite";

export const getLoggedInUser = cache(async () => {
  try {
    const { account } = await createSessionClient();
    return await account.get();
  } catch (error) {
    return null;
  }
});
Buller's ShearwaterOP
Only way I managed to fix it is to open the auth process in a window using the window.open API react-new-window.