ssr: Cookies not setting properly supabase ssr

Bug report

I have already checked and cant see the same issue.

  • [x ] I confirm this is a bug with Supabase, not with my own application.
  • [x ] I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

I am using supabase-ssr package to log on.

I thought this was only an issue in dev mode as when I ran build mode on Friday it worked, but perhaps I had not properly deleted the cookie when I was testing so am getting the error again now.

Basically the auth-token cookie is not setting properly. If I log on twice, it sets but the first time i log on only sb-__-auth-token-code-verifier is set. I am unsure if it is something on my side which is causing the error or if there is something timing out in the setting of the second cookie. My code is below. Note I am using a otp sent to emails for this.

To Reproduce

This is to get the code:

export async function signuplogin(prevState: any, formData: FormData) {
  console.log(formData);
  const validatedFields = schema.safeParse({
    email: formData.get("email"),
  });
  console.log(validatedFields);

  if (!validatedFields.success) {
    console.log(validatedFields.error.flatten().fieldErrors.email);
    return {
      message: validatedFields.error.flatten().fieldErrors,
    };
  }
  console.log(formData);
  const email = formData.get("email") as string;
  return signInOTP({ email });

}

This is the server component for createClient:

import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { cookies } from "next/headers";

export const createClient = (cookieStore: ReturnType<typeof cookies>) => {
  return createServerClient<Database>(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          return cookieStore.get(name)?.value;
        },
        set(name: string, value: string, options: CookieOptions) {
          try {
            cookieStore.set({ name, value, ...options });
          } catch (error) {
            // The `set` method was called from a Server Component.
            // This can be ignored if you have middleware refreshing
            // user sessions.
          }
        },
        remove(name: string, options: CookieOptions) {
          try {
            cookieStore.set({ name, value: "", ...options });
          } catch (error) {
            // The `delete` method was called from a Server Component.
            // This can be ignored if you have middleware refreshing
            // user sessions.
          }
        },
      },
    }
  );
};

This is to check the OTP code:

export async function precheckOTP(prevState: any, formData: FormData) {
  console.log(formData);
  const validatedFields = schema.safeParse({
    code: formData.get("code"),
  });
  console.log(validatedFields);

  if (!validatedFields.success) {
    console.log(validatedFields.error.flatten().fieldErrors.code);
    return {
      message: validatedFields.error.flatten().fieldErrors,
    };
  }
  console.log(formData);
  const code = formData.get("code") as string;
  const user = formData.get("user") as string;
  return checkOTP({ token: code, user: user });
}


const checkOTP = async ({ token, user }: { token: string; user: string }) => {
  const cookieStore = cookies();
  const supabase = createClient(cookieStore);
  const email = atob(user);

  try {
    const { error } = await supabase.auth.verifyOtp({
      email,
      token,
      type: "email",
      options: {
        redirectTo: "/dashboard",
      },
    });

    if (error) {
      return {
        message: { error: "Something went wrong. Please try again." },
      };
    }
  } catch (error) {
    console.log(error);
    return {
      message: { error: "Something went wrong. Please try again." },
    };
  }

  return redirect("/dashboard");
};

I am redirected to the dashboard.

However the cookies are not being set properly. The first time:

sb--auth-token-code-verifier is set properly. The second time I log on sb--auth-token is set

(Note this is called when someone is on protected:

export async function updateSession(request: NextRequest) {
  let response = NextResponse.next({
    request: {
      headers: request.headers,
    },
  });

  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          return request.cookies.get(name)?.value;
        },
        set(name: string, value: string, options: CookieOptions) {
          request.cookies.set({
            name,
            value,
            ...options,
          });
          response = NextResponse.next({
            request: {
              headers: request.headers,
            },
          });
          response.cookies.set({
            name,
            value,
            ...options,
          });
        },
        remove(name: string, options: CookieOptions) {
          request.cookies.set({
            name,
            value: "",
            ...options,
          });
          response = NextResponse.next({
            request: {
              headers: request.headers,
            },
          });
          response.cookies.set({
            name,
            value: "",
            ...options,
          });
        },
      },
    }
  );

  await supabase.auth.getUser();

  return { supabase, response };
}

I have tried with our without this: await supabase.auth.getUser();

But then what happens is I get thrown from the route a moment later or if I try to navigate and I am thrown out of the protected route. I then have to log in again in which case the second cookie is set.

Expected behavior

That the cookies would all set in the first instance and the user is not required to log on twice for them to set

Screenshots

If applicable, add screenshots to help explain your problem.

System information

  • OS: [e.g. macOS,]
  • Browser (if applies) [e.g., safari and firefox]
  • Version of supabase-js: [e.g. 2.42.3] (ssr 0.0.10)
  • Version of Node.js: [e.g. 18.17.0]

nextjs version - 14.1.4

Additional context

Add any other context about the problem here.

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 21
  • Comments: 43 (2 by maintainers)

Most upvoted comments

This doesn’t directly solve OP’s problem, but just throwing this out there in case anyone’s banging their head against the table. Make sure you don’t have any logout links inadvertently getting prefetched. My supabase auth cookie was getting assigned correctly, but then NextJS would prefetch the logout link on my account page, causing the server to immediately delete the cookie.

tldr; it may be worth checking for version incompatibilities between the Supabase libraries being used.

i had this issue and resolved by making sure all supabase actions were using @supabase/ssr. It’s possible you are using @supabase/auth-helpers-nextjs elsewhere in your app. Improper setting in the cookie likely stems from using different supabase client creation methods in different parts of your app.

any fix on this? having the same issue

Can take a look at this

Anyone have an idea or have the same issue? It is constantly happening so its either something in my sign up flow (which as far as I can tell is identical to the docs but I could be wrong), or an issue on supabase side… either way would 1) need better docs or 2) is a bug in the ssr package which we have all been repeatedly told to upgrade to

I encountered a similar issue. In my reset-password flow, I got the correct values in request.cookies in my API endpoint, but after redirecting to a new page, the cookies were gone. I managed to solve this by setting the request.cookies in the Next.js cookie store manually.

This is the code for that.

import { cookies } from 'next/headers'

export async function GET(req: NextRequest) {
    // Some logic ...

    // Manually updating all cookies
    const cookieStore = cookies()
    for (const cookie of req.cookies.getAll()) {
        cookieStore.set(cookie.name, cookie.value)
    }

    return NextResponse.redirect('<redirect-url>')
}

While this might not be the exact issue for the OP, here is a reminder to double-check your host redirections.

I experienced very similar symptoms in my local application, and the root cause turned out to be surprisingly simple. In my callback hook, I was redirecting to http://localhost:3000 instead of http://127.0.0.1:3000.

As a result, the session tokens were being set correctly on 127.0.0.1:3000, but after the redirect to localhost:3000, I had to log in again.

I have the same problem and I am using the latest version of the superbase client and also not using @supabase/auth-helpers-nextjs… My Quick fix(which still doesn’t work for all my users) is to set the cookie manually

@mattrigg9 I got caught by the exact same thing, thanks for the tip.

In my case this was only happening in production since “Prefetching is not enabled in development, only in production.”

Same issue, any solutions? Next.js 14.2.5 doen’t resolve this problem for me

My silly mistake was that I was signing the user in from the server via server actions. I used the Supabase client from the client side and everything started working.

My solution was similar to @PatrickHallek’s

Needed to update the values for site_url and additional_redirect_urls to use localhost in myconfig.toml

This doesn’t directly solve OP’s problem, but just throwing this out there in case anyone’s banging their head against the table. Make sure you don’t have any logout links inadvertently getting prefetched. My supabase auth cookie was getting assigned correctly, but then NextJS would prefetch the logout link on my account page, causing the server to immediately delete the cookie.

You sir are a godsend, thank you!

@mattrigg9 you are a hero. thank you!

This doesn’t directly solve OP’s problem, but just throwing this out there in case anyone’s banging their head against the table. Make sure you don’t have any logout links inadvertently getting prefetched. My supabase auth cookie was getting assigned correctly, but then NextJS would prefetch the logout link on my account page, causing the server to immediately delete the cookie.

God thank you, I rarely use NEXTJS and I always forget to remove the prefetch behaviour

In my case, I used export const dynamic = 'force-dynamic' in a layout that blocked cookies on the first render.

Thanks a lot @Sof2222!

For reference I upgraded from "next": "14.2.4", to "next": "14.2.5", and it fixed the issue

For anyone having the issues - I think it is a nextjs issue. Updating nextjs solved it and I have not had this issue the past week (have been testing)

I’m not familiar with Next, but has anyone tried migrating to the new ssr 0.4.x version and using the setAll and getAll methods? It’s supposed to better handle Next quirkiness. New docs are available here

still have an error event update to latest version of @supabase/ssr.

I did a quick fix that solved the error. In the process of sign-in, I save a cookie reference for refresh and access tokens (sb-access-token, sb-refresh-token)

const cookieStore = cookies();

const { data, error } = await repository.auth.signInWithPassword({
    email,
    password,
  });
  
  cookieStore.set('sb-access-token', data?.session?.access_token);
  cookieStore.set('sb-refresh-token', data?.session?.refresh_token);

When I try to capture user information in my API routes I’ve an auxiliary function:

retrieveAuthOrSessionUser = async () => {
    let userFinal = null;
    const cookieStore = cookies();
    const accessToken = cookieStore.get('sb-access-token');
    const refreshToken = cookieStore.get('sb-refresh-token');

    const {
      data: { user },
      error,
    } = await this.supabase.auth.getUser();

    if (error) {
      const { data: dataSession } = await this.supabase.auth.setSession({
        access_token: accessToken?.value ?? '',
        refresh_token: refreshToken?.value ?? '',
      });
      userFinal = dataSession?.user;
    } else {
      userFinal = user;
    }

    const { id } = userFinal ?? {};

    return {
      id: id ?? '',
    };
  };

Remember to erase the cookies on the process of sign-out

  const supabaseCookies = cookies().getAll();

  supabaseCookies.map((cookie) => {
    if (cookie.name.includes('sb-')) {
      cookies().delete(cookie.name);
    }
  });

isn’t the best scenario or code, but does the job. Hope this Helps.

@koolerjaebee I have not encountered this myself, having only recently implemented this solution, but what you’re saying is quite possible. I will try to circle back to this in the next few days to test and see if I can find a solution. My workaround is not ideal, because clearly it’s not what supabase intended, so I’m hoping they will chime in at some point.

Were you just setting the JWT expiration time really low to test? And then the behavior you’re describing would happen consistently?

So I did quite a bit more investigation (still have no clue where the issue is) - tested in both safari and firefox. Same issue - first logon pass it doesnt set the auth cookie properly, the second it does (and it stays set too).

The auth-token is definitly coming through from request in the first instance - it is just not being set properly and i don’t really know where it is being set… I have tried to go through the code but I cannot see anywhere I would be eg. removing it (and if it was, it stays after the second log on everytime anyway). (only the auth-token-code-verifier is being set first pass)

I did upgrade a while back from using auth-helper and js, so there could potentially be some legacy code from that, but I cannot find anything obvious at least and don’t have those imports in my code anymore either.

I have added a bunch of console.logs to the updateSession function to try and follow and see where the issues are. I also tried to set it manually (but when I set it manually it was actually removed (i saw the remove statements) the first pass then set properly the second. While the get function is definitly called many times (and especially on the first pass get finds auth-token) it is not finding auth-token upon page refresh… (so I am guessing it is uing the headers originally, as it also does go to the dashboard but is just not being set properly).

I cannot see anywhere I am deleting this cookie and have searched everywhere I am accessing the cookies too.

I am not sure where the set functions are being called though - I don’t get any console.logs from there at all… The remove I only ever saw 1 console log which was when I tried to set it myself manually. (even when the cookies are definitly being set). Is that on a different part of the supabase client maybe?

export async function updateSession(request: NextRequest) {
  let response = NextResponse.next({
    request: {
      headers: request.headers,
    },
  });
  // console.log("request.cookies", request.cookies);
  // console.log("response", response);
  console.log("request", request);
  console.log(
    "auth cookie investigation",
    request.cookies.get("sb-...-auth-token")?.value
  );
  const cookieval = request.cookies.get(
    "sb-...-auth-token"
  )?.value;
  const cookievaljson = JSON.parse(cookieval || "{}");
  console.log("auth cookie investigation json", cookievaljson.access_token);
  console.log(
    "auth cookie investigation options",
    request.cookies.get("sb-...-auth-token")
  );

  // request.cookies.set({
  //   name: "sb-cmhsbvzpocwhojvycyin-auth-token",
  //   value: cookievaljson.access_token || "",
  // });
  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          console.log("cookies name", name);
          console.log("cookies value", request.cookies.get(name)?.value);

          return request.cookies.get(name)?.value;
        },
        set(name: string, value: string, options: CookieOptions) {
          console.log(
            `Setting cookie ${name} to ${value} with options ${JSON.stringify(
              options
            )}`
          );
          request.cookies.set({
            name,
            value,
            ...options,
          });
          response = NextResponse.next({
            request: {
              headers: request.headers,
            },
          });
          response.cookies.set({
            name,
            value,
            ...options,
          });
          console.log("response after setting cookie", response);
        },
        remove(name: string, options: CookieOptions) {
          console.log("cookies removing name", name);
          console.log("cookies removing options", options);
          request.cookies.set({
            name,
            value: "",
            ...options,
          });
          response = NextResponse.next({
            request: {
              headers: request.headers,
            },
          });
          response.cookies.set({
            name,
            value: "",
            ...options,
          });
        },
      },
    }
  );

  const user = await supabase.auth.getUser();
  console.log("User:", user);
  // console.log("Supabase:", supabase);

  return { supabase, response };
}

Ok - I am unable to repro this, I am following the docs here and here , have tried both a magiclink and OTP. afaik whether you auth.signup/signin with OTP you should get a session in the returned data , are you able to call auth.getUser() in the protected route after signup (1st or 2nd time)? and what do you get?

Also if anyone else more familiar wants to jump in please feel free to.