Skip to content
Back

SSR Auth: Redirect happens before cookie is set

  • 0
  • Web
Oli
9 Sep, 2025, 23:05

I followed these docs https://appwrite.io/docs/tutorials/nextjs-ssr-auth/step-7 However, when having successfully logged in via google, I get immediately redirected to the signin. But, I should getting forwared to the profile page.

TypeScript
// // src/app/oauth/route.ts

import { config } from "@/lib/config";
import { createAdminClient } from "@/lib/server/appwrite";
import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  const userId = request.nextUrl.searchParams.get("userId");
  const secret = request.nextUrl.searchParams.get("secret");

  if (!userId || !secret) {
    return new NextResponse("OAuth2 did not provide token", { status: 400 });
  }

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

  if (!session || !session.secret) {
    return new NextResponse("Failed to create session from token", {
      status: 400,
    });
  }

  (await cookies()).set(config.appwrite.sessionName, session.secret, {
    path: "/",
    httpOnly: true,
    sameSite: "strict",
    expires: new Date(session.expire),
    secure: true,
  });

  return NextResponse.redirect(`${request.nextUrl.origin}/profile`);
}
TypeScript
// src/app/(protected)/profile/layout.tsx

import Header from "@/components/Header";
import { getLoggedInUser } from "@/lib/server/appwrite";
import { redirect } from "next/navigation";

export default async function ProtectedLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const user = await getLoggedInUser();
  if (!user) {
    redirect("/signin"); // --> THIS seems to kick in bevor the cookie has been set
  }

  return (
    <div className="min-h-screen flex flex-col gap-y-8">
      <Header />
      <main className="container mx-auto max-w-[1400px]">{children}</main>
    </div>
  );
}

Not sure what I am doing wrong here

TL;DR
Issue: Redirect to sign-in page happens before the cookie is set after successful login via Google. Solution: - Place the redirection in the `ProtectedLayout` component after checking if the user is logged in. This ensures that the redirection will occur after the cookie is properly set. - Modify the redirect line to `await redirect("/signin");` to ensure proper timing of the redirect.
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