Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid Refresh Token: Refresh Token Not Found #436

Open
bukinoshita opened this issue Jan 25, 2023 · 91 comments
Open

Invalid Refresh Token: Refresh Token Not Found #436

bukinoshita opened this issue Jan 25, 2023 · 91 comments
Labels

Comments

@bukinoshita
Copy link

Bug report

Describe the bug

I'm currently getting Invalid Refresh Token: Refresh Token Not Found error in my Next.js middleware

const res = NextResponse.next();
  const supabase = createMiddlewareSupabaseClient({ req, res });

  const {
    data: { session },
    error,
  } = await supabase.auth.getSession();

  if (error) {
    throw new Error(error.message);
  }

A clear and concise description of what the bug is.

To Reproduce

I think the issue is pretty similar to this one:

supabase/auth-js#323
Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Go to '…'
  2. Click on '…'
  3. Scroll down to '…'
  4. See error

Expected behavior

To logout the user, or keep them signed in

A clear and concise description of what you expected to happen.

Screenshots

If applicable, add screenshots to help explain your problem.

System information

  • OS: [e.g. macOS, Windows]
  • Browser (if applies) [e.g. chrome, safari]
  • Version of supabase-js: [e.g. 6.0.2]
  • Version of Node.js: [e.g. 10.10.0]

Additional context

Add any other context about the problem here.

@bukinoshita bukinoshita added the bug Something isn't working label Jan 25, 2023
@j4w8n
Copy link

j4w8n commented Jan 26, 2023

One of the places I found this error is when calling getSession, it sees the session as expired, then calls the gotrue api to try and refresh the session. Part of that process is trying to find a user that has the refresh token. If something goes wrong when searching for a user, it'll return this error.

Can you look in your auth.refresh_tokens table and find an entry that matches the token?

@bukinoshita
Copy link
Author

One of the places I found this error is when calling getSession, it sees the session as expired, then calls the gotrue api to try and refresh the session. Part of that process is trying to find a user that has the refresh token. If something goes wrong when searching for a user, it'll return this error.

Yeah, that exactly the call that it's giving me that error.

Can you look in your auth.refresh_tokens table and find an entry that matches the token?

What should I look here? Whenever I get the error, I try to find a refresh token that matches the current token?

Btw, a temporary "solution" was to increase the user session from 1 hour to 1 week, so it minimize the error occurrence.

@j4w8n
Copy link

j4w8n commented Jan 27, 2023

What should I look here? Whenever I get the error, I try to find a refresh token that matches the current token?

Yes

What's the timeframe between when a user signs in and when this error occurs?

@bukinoshita
Copy link
Author

Need to investigate, the application is production — what would be the best way to track this? Should I change the session time to 1 hour again and see if the error happens with more frequency?

@thorwebdev
Copy link
Member

You could try increasing the reuse interval. The client and server might be refreshing fairly close to each other in with that invalidate the token. But yah, if you have a log drain would also be good to see what's happening within the middleware function.

image

@yairhaimo
Copy link

Did you ever solve this issue? Im running into the same problem

@jdgamble555
Copy link

Not sure why, but this happened on my local dev server, and when I restarted, the problem was gone.

J

@dsebastien
Copy link

I am trying to refresh user data by calling auth.getUser() and am facing the same error.

@nathantaal

This comment was marked as off-topic.

@bukinoshita
Copy link
Author

Did you ever solve this issue? Im running into the same problem

Increasing the interval "solved" the issue. I don't think this is the ideal solution, but for me it stopped breaking the application at least.

@RyanCarterTheDev
Copy link

Did you ever solve this issue? Im running into the same problem

Increasing the interval "solved" the issue. I don't think this is the ideal solution, but for me it stopped breaking the application at least.

What did you increase this to?

I'm also running into this issue with auth.getSession() when using createRouteHandlerClient from @supabase/auth-helpers-nextjs

@bukinoshita
Copy link
Author

If I recall correctly the workaround was to increase this to the max
CleanShot 2023-07-18 at 17 22 23@2x

@nathantaal
Copy link

But is this also a solution, or will it only make the issue very less like to happen? So in the example of this max seconds being a week, will will get the error again if we logon to the app only to open it 8 days later..?

@MilesV64
Copy link

MilesV64 commented Jul 31, 2023

Also experiencing this

@seho0808
Copy link

seho0808 commented Aug 4, 2023

Ok, I have a reproducible Scenario where this happens on my server.
If I load balance to multiple instance and when user logs in on browser to use my service,
the load balanced instance can get changed and user's frontend server can be redirected to a different server than
the one he or she logged in. Since the Next js app in a new instance does not have a refresh token for the cookie
that it is getting, it returns "Refresh Token Not Found". This is fine if I can log the user out.

I can't seem to log the user out in a proper way, maybe like the signOut api await supabase.auth.signOut, since this also throws
the token not found error...

I guess I have to automatically clear cookies of users every time I encounter this?

Please let me know if I'm wrong here. I need help.

EDIT: not really sure it is because of multiple instances at this moment. might just be other bug.

@swyxio
Copy link

swyxio commented Aug 5, 2023

@david-plugge is this similar to #343 ?

@titocosta
Copy link

titocosta commented Aug 11, 2023

Now getting same problem. Not quite sure what triggered it in the first place as it was working ok until now. It might be that I logged out the user and since I logged back in, it started giving this error.

Increasing JWT expiry (to several values and up to maximum) and increasing reuse interval in settings/auth did not solve it for me.

This is all with local development in NextJS 13, logging in with Google OneTap.

@silentworks
Copy link
Contributor

We haven't been able to reproduce this issue and will find it hard to fix since we have no way of seeing or testing the issue. Can one of you on the thread provide a reproducible repository with the issue so we can take a look at it.

@jdgamble555
Copy link

@silentworks - One of the ways this has been triggered is by logging in to my website, then running supabase db reset (or stop and start). Since I'm still logged in, and the database is empty, it will result in this error. I believe logging out first before resetting the database fixes this problem, and probably what is expected.

There are other cases, and as I find them (may be randomly in the future), I will post a repo and try and replicate it.

I can't speak for anyone else.

J

@nathantaal

This comment was marked as off-topic.

@seho0808
Copy link

seho0808 commented Aug 17, 2023

We haven't been able to reproduce this issue and will find it hard to fix since we have no way of seeing or testing the issue. Can one of you on the thread provide a reproducible repository with the issue so we can take a look at it.

I think I found a reproducible one which produces a similar result. Could you please try this scenario?

  1. set JWT expiry limit to lowest as possible (which is 1200 currently)
  2. login to supabase auth based app
  3. in developer console, get the document.cookie for our JWT token. keep this somewhere else.
  4. logout of supabase auth based app we logged in from step2.
  5. wait for expiry time. (1200 seconds in this case)
  6. on a fresh app website page that isn't logged in, inject the document.cookie from step3.
  7. refresh so that document.cookie takes effect.
  8. You get bunch of errors on server and client. Below statement prints multiple times in my server for next.js app.
[AuthApiError: Invalid Refresh Token: Refresh Token Not Found] {
1|vhub_fe  |   __isAuthError: true,
1|vhub_fe  |   name: 'AuthApiError',
1|vhub_fe  |   status: 400
1|vhub_fe  | }
  1. The problem here is that none of supabase-js api works so I can't even await supabase.signOut().

Disclaimer here is that my bug happens to have same result, but I never log out of the app nor do I turn off my server. My server is always online, and "Refresh token not found" happens after some time has passed. Also not sure what the expiry was set in cookie for the actual error scenario, but in actual scenario, the error persisted even if I closed the browser and reentered the website.

My current solution to bypass Refresh Token Not Found in production - this simply logs out the user:
(part of middleware.ts)

const res = NextResponse.next();
const supabase = createMiddlewareClient<Database>({ req, res });
const {
  data: { session },
  error,
} = await supabase.auth.getSession();

if (error) {
  res.cookies.delete("my-auth-token-name");
  return ["error", res];
}

@arobert93
Copy link

@seho0808 Thank you for providing the solution. I'm facing the same issue.

@silentworks
Copy link
Contributor

@seho0808 those steps don't make sense as that is intentionally creating an issue. The auth-helpers does auto-refreshing of the token so you logging out would remove the whole effect of the auto-refreshing happening. Please provide an example app repository simulating this issue whilst logged in. Intentionally breaking the flow to create an issue isn't a good way to fix an issue.

@seho0808
Copy link

@seho0808 those steps don't make sense as that is intentionally creating an issue. The auth-helpers does auto-refreshing of the token so you logging out would remove the whole effect of the auto-refreshing happening. Please provide an example app repository simulating this issue whilst logged in. Intentionally breaking the flow to create an issue isn't a good way to fix an issue.

I apologize for a bad example. I couldn't find a way to reproduce it so I shared a closest example to what I can simulate. I will try not to provide such examples from now on. Thank you for the reply!

@wdavidturner
Copy link

I believe the issue is that you have info in your cookies that references a deleted user.

@louishugens
Copy link

the issue is still there. Any solution or workaround?

@wdavidturner I have the same issue, it happens when the auth token expires but the user is still logged in.

@wojtekKrol
Copy link

I have the same error, I deleted user in auth tab while beeing login on my localhost, clearing cookies do nothing

@juliomuhlbauer
Copy link

I think I will just move to next auth for now :(

@chriscarrollsmith
Copy link

chriscarrollsmith commented Feb 4, 2024

I encountered this error during testing due to being logged in with a cookie from a user I deleted from my database. I seem to have fixed it with this workaround, which clears all Supabase-related cookies if this error is thrown:

import { type NextRequest } from 'next/server';
import { createClient } from '@/utils/supabase/middleware';

export async function middleware(request: NextRequest) {
  const { supabase, response } = createClient(request);
  const { error } = await supabase.auth.getSession();
  
  if (error?.message.match("Invalid Refresh Token")) {
    const allCookies = request.cookies.getAll();
    allCookies.forEach(cookie => {
      // Delete all Supabase cookies starting with 'sb-'
      if (cookie.name.startsWith('sb-')) {
        response.cookies.delete(cookie.name)
      }
    });
  }

  return response;
}

@chriscarrollsmith
Copy link

By the way, for reproducibility purposes, here's the context in which I encountered this error:

I have two separate Supabase projects that I test on the same 'http://localhost:3000". When I toggle between them, I often find myself logged in with cookies for the wrong project, and my middlewar throws this error.

@JasonGross
Copy link

Am I correctly understanding that the issue here is that supabase is handling refresh tokens behind the scenes in many cases, but when an expired session is still active,

  1. supabase does not gracefully handle this case, instead throwing an error; and
  2. supabase provides no way to handle this error, because it does not expose an API for interacting directly with the refresh tokens it uses?

@NickG-NZ
Copy link

You nailed it. Note also that the cookie names generated by the SSR package include a random hash. So even if you want to manipulate them manually you can't because you don't know the name.

My preference would be that supabase automatically deletes the expired cookie and returns a null session (indicating the user is not logged in).

Note that this problem can be resolved manually now that the issue with setting a custom cookie name has been fixed. (You can set your own name for the cookie by passing an option to "creatServerClient")

This means if this error occurs, you can just delete the cookie. And follow what ever your normal flow is for unauthenticated users.

Alternatively you can use the solution mentioned above and just remove all cookies starting with "sb-". This is the solution we initially implemented to get around the problem

@ARMATAV
Copy link

ARMATAV commented Feb 12, 2024

I do not see this behavior on a new nextjs project following exactly the steps in here and implementing the client side auth via this workaround so that you actually get the styling covered.

Seemingly, the token refresh behavior is taken care of. This is after around 1 day of letting the token expire etc.

Note that the Auth component is the one referenced in the above issue - pasting in my AuthButton so that other people can just try it out;

(obviously, you can delete those extraneous app/login components for this approach)

AuthButton.server.tsx

import React from "react";
import { createClient } from "@/utils/supabase/server";
import { cookies } from "next/headers";
import { AuthButtonClient } from "./AuthButton";

export const AuthButton = async () => {
  const cookieStore = cookies();
  const supabase = createClient(cookieStore);

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

  return <AuthButtonClient initialUser={user} />;
};

AuthButton.tsx

"use client";

import { useEffect, useState } from "react";
import { Button } from "../ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "../ui/dialog";
import { Auth } from "./Auth";
import { createClient } from "@/utils/supabase/client";
import { User } from "@supabase/supabase-js";
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import { LogOut } from "lucide-react";

const supabaseClient = createClient();

type AuthButtonProps = {
  initialUser?: null | User;
};

export const AuthButtonClient = ({ initialUser }: AuthButtonProps) => {
  const [isDialogOpenState, setIsDialogOpenState] = useState<boolean>(false);
  const [userState, setUserState] = useState<undefined | User>(
    initialUser ?? undefined
  );

  const { auth } = supabaseClient;

  useEffect(() => {
    async function getUser() {
      const {
        data: { user },
      } = await auth.getUser();

      if (user) {
        setIsDialogOpenState(false);
        setUserState(user);
      }
    }

    getUser();
  }, [auth]);

  useEffect(() => {
    const { data: authListener } = auth.onAuthStateChange((event, session) => {
      if (event === "SIGNED_IN") {
        setIsDialogOpenState(false);
        setUserState(session?.user);
      }

      if (event === "SIGNED_OUT") {
        setUserState(undefined);
      }
    });

    return () => {
      authListener?.subscription.unsubscribe();
    };
  }, [auth]);

  const handleLogOutClicked = () => {
    auth.signOut();
    setUserState(undefined);
  };

  const { email, user_metadata } = userState ?? {};
  const { avatar_url } = user_metadata ?? {};

  return (
    <>
      <Dialog open={isDialogOpenState} onOpenChange={setIsDialogOpenState}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>Sign in</DialogTitle>
            <DialogDescription>to continue to Skipit</DialogDescription>
          </DialogHeader>

          <div className="">
            <Auth />
          </div>
        </DialogContent>
      </Dialog>

      {userState && (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Avatar>
              <AvatarImage src={avatar_url} alt="user avatar" />
              <AvatarFallback className="select-none">
                {email ? email[0].toUpperCase() : ""}
              </AvatarFallback>
            </Avatar>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="w-56">
            <DropdownMenuLabel>My Account</DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={handleLogOutClicked}>
              <LogOut className="mr-2 h-4 w-4" />
              <span>Log out</span>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      )}
      {!userState && (
        <div>
          <Button
            onClick={() => {
              setIsDialogOpenState(true);
            }}
          >
            Sign In
          </Button>
        </div>
      )}
    </>
  );
};

middleware.ts

import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";

export async function middleware(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 response;
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * Feel free to modify this pattern to include more paths.
     */
    "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
  ],
};

This is with everything at their latest versions on a fresh project using shadcdn for the other components.

Again it seems all good, even after multiple expirations take place, it seems to refresh properly.

@ummahusla
Copy link
Sponsor

Ugh, and still no good solution to this problem? Because I tried everything I found in github issues, reddit and there is still no valid workaround it seems.

@mbeaudru
Copy link

From what I've found, it seems that the refresh token workflow works well until supabase/ssr decides to split the cookie in two chunks. Maybe the refresh token code misses to handle this situation.

In my case, the refresh token workflow works well with email login, but it doesn't work properly with google signin/up as it pulls all user info in cookies and it gets split.

I didn't found time to investigate this further and submit a PR yet, so take it with a grain of salt. In the meantime, going back to old auth-helpers package helps, but this would be really awesome for the refresh token workflow to work again reliably with supabase/ssr - because as of today users are forced-unlogged as soon as the JWT token expires (1h by default)

@CarlosBalladares
Copy link

CarlosBalladares commented Mar 7, 2024

This happens when i have an old token, calling getUser() doesn't overwrite the old token unless i sign in again. Any ideas on workarounds?

@aplyd
Copy link

aplyd commented Mar 18, 2024

commenting because I'm also experiencing this issue with social logins (azure specifically). the user being logged out every hour isn't a huge issue in my scenario but definitely inconvenient.

@singuerinc
Copy link

Hi folks, any update on this? I keep getting 404 on the site I'm building if I don't visit it for a few hours. This is terrible for business critical apps and users who won't bother in refreshing the page (which I assume are all). I'm seriously thinking about migrating away if this is not resolved (which is also frustrating giving all the hours I invested in making it work with Supabase).

@hf
Copy link
Contributor

hf commented Apr 5, 2024

From what I've found, it seems that the refresh token workflow works well until supabase/ssr decides to split the cookie in two chunks. Maybe the refresh token code misses to handle this situation.

In my case, the refresh token workflow works well with email login, but it doesn't work properly with google signin/up as it pulls all user info in cookies and it gets split.

I didn't found time to investigate this further and submit a PR yet, so take it with a grain of salt. In the meantime, going back to old auth-helpers package helps, but this would be really awesome for the refresh token workflow to work again reliably with supabase/ssr - because as of today users are forced-unlogged as soon as the JWT token expires (1h by default)

OK thanks for this insight. I'll check the code there.

@hf
Copy link
Contributor

hf commented Apr 6, 2024

These are some fixes I identified that could be causing weird issues: #760

@hf
Copy link
Contributor

hf commented Apr 6, 2024

Also one thing that may be confusing you is if you are getting this error on localhost, not on production. This is somewhat expected on localhost because the cookies remain in place forever, but your backend / database is not there. So it's normal to get Invalid Refresh Token errors if your database has changed.

How many of you are actually seeing this on a real, live project (or staging environment) -- not local development?

@mbeaudru
Copy link

mbeaudru commented Apr 6, 2024

Thanks for starting investigations, really appreciated!

I moved on to something else so I won't be able to give more valuable feedback moving forward, but I have to say that I had invalid refresh token happening on prod on my end sadly, not just localhost

@hf
Copy link
Contributor

hf commented Apr 7, 2024

OK I've done a deep dive into this with NextJS. It is very important for your middleware.ts file to look exactly like this to prevent this from happening.

If it's just a bit off, your server-rendered pages and components won't see the correct state and all hell will break loose.

https://supabase.com/docs/guides/auth/server-side/creating-a-client?environment=middleware

@astonfuture
Copy link

Also one thing that may be confusing you is if you are getting this error on localhost, not on production. This is somewhat expected on localhost because the cookies remain in place forever, but your backend / database is not there. So it's normal to get Invalid Refresh Token errors if your database has changed.

How many of you are actually seeing this on a real, live project (or staging environment) -- not local development?

I'm seeing this is production with Remix but interestingly I haven't been able to reproduce on localhost

@hawkcookie
Copy link

@hf Thanks you for the investigation! I am also seeing this issue in production with Remix deployed to cloudflare pages. A log is below. This event occurs only rarely, but a few users have encountered this issue.

Log Event Message

{"component":"api","error":"invalid_grant: Invalid Refresh Token: Refresh Token Not Found","level":"info","method":"POST","msg":"invalid_grant: Invalid Refresh Token: Refresh Token Not Found","path":"/token","referer":"XXXXXXX","remote_addr":"2a06:98c0:3600::103","time":"2024-04-05T14:38:33Z","timestamp":"2024-04-05T14:38:33Z"}

Log Meta Data
[
  {
    "message": null,
    "timestamp": "2024-04-05T14:38:33Z",
    "__MONOTONIC_TIMESTAMP": null,
    "CODE_FUNC": null,
    "instance_id": null,
    "status": null,
    "_CMDLINE": null,
    "method": "POST",
    "_SYSTEMD_CGROUP": null,
    "CODE_FILE": null,
    "EXECUTABLE": null,
    "_EXE": null,
    "UNIT": null,
    "level": "info",
    "_COMM": null,
    "duration": null,
    "issuer": null,
    "_LINE_BREAK": null,
    "_SOURCE_REALTIME_TIMESTAMP": null,
    "msg": "invalid_grant: Invalid Refresh Token: Refresh Token Not Found",
    "action": null,
    "login_method": null,
    "_UID": null,
    "host": "XXXXXXXX,
    "PRIORITY": null,
    "_CAP_EFFECTIVE": null,
    "_PID": null,
    "INVOCATION_ID": null,
    "_SYSTEMD_UNIT": null,
    "source_type": null,
    "SYSLOG_FACILITY": null,
    "request_id": null,
    "CODE_LINE": null,
    "path": "/token",
    "component": "api",
    "project": null,
    "user_id": null,
    "auth_event": [],
    "args": [],
    "referer": "XXXXXXX",
    "factor_id": null,
    "provider": null,
    "client_id": null,
    "remote_addr": "2a06:98c0:3600::103",
    "_SYSTEMD_SLICE": null,
    "_SYSTEMD_INVOCATION_ID": null,
    "header": null,
    "_MACHINE_ID": null,
    "_AUDIT_LOGINUID": null,
    "_TRANSPORT": null,
    "_SELINUX_CONTEXT": null,
    "MESSAGE_ID": null,
    "__REALTIME_TIMESTAMP": null,
    "metadata": [],
    "_STREAM_ID": null,
    "metering": null,
    "time": null,
    "_GID": null,
    "_BOOT_ID": null,
    "SYSLOG_IDENTIFIER": null,
    "_AUDIT_SESSION": null,
    "error": "invalid_grant: Invalid Refresh Token: Refresh Token Not Found"
  }
]

@singuerinc
Copy link

Also one thing that may be confusing you is if you are getting this error on localhost, not on production. This is somewhat expected on localhost because the cookies remain in place forever, but your backend / database is not there. So it's normal to get Invalid Refresh Token errors if your database has changed.

How many of you are actually seeing this on a real, live project (or staging environment) -- not local development?

I can reproduce it in production always. I just need to wait less than a day, I check the production site and it always fails on the first load.

@singuerinc
Copy link

OK I've done a deep dive into this with NextJS. It is very important for your middleware.ts file to look exactly like this to prevent this from happening.

If it's just a bit off, your server-rendered pages and components won't see the correct state and all hell will break loose.

supabase.com/docs/guides/auth/server-side/creating-a-client?environment=middleware

I understand that this is ideal, but in a real application the middleware could look different.

In my case I have next-intl configured:

next-intl modifies the middleware https://next-intl-docs.vercel.app/docs/getting-started/app-router#middleware

So for example, I need to modify the matcher, which it may create some problems?

@cervantes-x
Copy link

Any updates on this? Our users get signed out at random times because of this and it's a big issue for our app.

@silentworks silentworks removed their assignment May 1, 2024
@singuerinc
Copy link

singuerinc commented May 3, 2024

@cervantes-x I found out they changed the docs few months ago with a suspicious change:

https://github.com/supabase/supabase/commit/94a07fe7245ba0c3c4a796e270c54131b1b40d4e#diff-dd339bd5166457f97527bb5dd3507aa30e4c4d12a336b527e6baeb84d6a978c2R225

I had in my middleware:

await supabase.auth.getSession();

but in the docs now says:

await supabase.auth.getUser();

I haven't tested it yet, but any application created prior to that change (4 months ago) I guess should update to that.

I'll monitor my app for a while and post some update.

@harrisrobin
Copy link

harrisrobin commented May 4, 2024

@cervantes-x I found out they changed the docs few months ago with a suspicious change:

https://github.com/supabase/supabase/commit/94a07fe7245ba0c3c4a796e270c54131b1b40d4e#diff-dd339bd5166457f97527bb5dd3507aa30e4c4d12a336b527e6baeb84d6a978c2R225

I had in my middleware:

await supabase.auth.getSession();

but in the docs now says:

await supabase.auth.getUser();

I haven't tested it yet, but any application created prior to that change (4 months ago) I guess should update to that.

I'll monitor my app for a while and post some update.

This seems to have helped, however every user that's visited the site since this change has had to manually clear their cookies, otherwise they were permanently met with a 500, so be careful before making that change in a production system without handling the error.

Once sb- cookies are cleared, things are pretty smooth so far.

@hawkcookie
Copy link

@cervantes-x I found out they changed the docs few months ago with a suspicious change:

https://github.com/supabase/supabase/commit/94a07fe7245ba0c3c4a796e270c54131b1b40d4e#diff-dd339bd5166457f97527bb5dd3507aa30e4c4d12a336b527e6baeb84d6a978c2R225

I had in my middleware:

await supabase.auth.getSession();

but in the docs now says:

await supabase.auth.getUser();

I haven't tested it yet, but any application created prior to that change (4 months ago) I guess should update to that.

I'll monitor my app for a while and post some update.

It sounds like you're suspecting that the issue might not be resolved because the getUser method is calling the same getSession method(https://github.com/supabase/auth-js/blob/bd91e72824ceb075f6fca7ae25bf9f066e6508d2/src/GoTrueClient.ts#L1195-L1207). In fact, in my application, I'm experiencing Invalid Refresh Token: Refresh Token Not Found randomly when using getUser.

@singuerinc
Copy link

ok, it didn't solve the issue. I'm tired of this and no support from Supabase.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests