ssr: AuthApiError: Invalid Refresh Token: Refresh Token Not Found when refreshing token in middleware

Bug report

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

Describe the bug

I’m inadvertently logged out of my web application every day, with this error in the back-end logs: AuthApiError: Invalid Refresh Token: Refresh Token Not Found.

I recently set up Supabase auth on my new Next.js application. I followed the Setting up Server-Side Auth for Next.js guide, with some small tweaks. My code looks like this:

middleware.ts
import { type NextRequest } from "next/server"

import { updateSession } from "./app/supabase/middleware"

export async function middleware(request: NextRequest) {
  return await updateSession(request)
}

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)
     * - @vercel/speed-insights script
     */
    "/((?!_next/static|_next/image|favicon.ico|_vercel/speed-insights|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
  ],
}
app/supabase/middleware.ts
import { CookieMethodsServer, createServerClient } from "@supabase/ssr"
import { NextResponse, type NextRequest } from "next/server"

export async function updateSession(request: NextRequest) {
  const response = NextResponse.next({ request })
  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: nextMiddlewareCookies(request, response),
    }
  )
  await supabase.auth.getSession()
  return response
}

function nextMiddlewareCookies(
  req: NextRequest,
  res: NextResponse
): CookieMethodsServer {
  return {
    getAll() {
      return req.cookies.getAll()
    },
    setAll(cookiesToSet) {
      cookiesToSet.forEach((cookie) => {
        req.cookies.set(cookie.name, cookie.value)
        res.cookies.set(cookie.name, cookie.value, cookie.options)
      })
    },
  }
}

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Use the snippets above to set up token refresh with middleware
  2. Log in
  3. Wait 24 hours
  4. Load any page that will hit the middleware, which for me is any page of my application.
  5. Get the AuthApiError: Invalid Refresh Token: Refresh Token Not Found error in your middleware logs

Expected behavior

The token should refresh if there is one and it’s expired, without an error. If there’s not a session, it should not try to refresh it, and there should be no error.

Screenshots

From my Vercel logs: Screenshot 2024-09-22 at 12 24 16 PM

System information

  • OS: macOS and Ubuntu
  • Browser (if applies): Chrome, Safari and Firefox
  • Version of supabase-js: 2.45.4
  • Version of @supabase/ssr: 0.5.1
  • Version of Next.js: 14.2.13 and 15.0.0-canary.159
  • Version of Node.js: 20.12.1

Additional context

This appears to be the same or a similar bug as https://github.com/supabase/auth-helpers/issues/436, as well as https://github.com/supabase/auth-js/issues/620

I’ve tried forcing the issue to happen more quickly by shortening the JWT expiry to 60 seconds, but it refreshes just fine. There’s something with the 24 hour window that seems to be causing the error.

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 30 (2 by maintainers)

Most upvoted comments

Also getting this

having this issue in react-router-7 app.

When I clear the cookies and re-login, it works but I don’t know why…

Switch to better auth guys and relief yourself from weird bugs honestly I had to go through the migration but glad I did it have not encountered any weird auth sessions issues

On Thu, 1 May 2025 at 3:17 AM Tadeu Maia @.***> wrote:

tadeumaia left a comment (supabase/ssr#68) https://github.com/supabase/ssr/issues/68#issuecomment-2843779573

Having the same problems, specially happening inside a WebView on native IOS for a nextjs app with supabase

— Reply to this email directly, view it on GitHub https://github.com/supabase/ssr/issues/68#issuecomment-2843779573, or unsubscribe https://github.com/notifications/unsubscribe-auth/BNZE2ENMBP3Q4PQT7TZQAJ324FRZZAVCNFSM6AAAAABOUWP5UGVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDQNBTG43TSNJXGM . You are receiving this because you commented.Message ID: @.***>

having this issue in react-router-7 app.

any luck with this ? @MikePresman

yes i solved it. see my approach here https://github.com/MikePresman/supabase-rr-middleware

Hey @MikePresman, Could you explain the change you made? What made it work? Thanks

Specifically in react-router-7 you need to keep passing the headers around. The reason for this is the refresh token needs the headers to reauthenticate. Hence I wrote middleware that does this for me. Study this https://github.com/MikePresman/supabase-rr-middleware/blob/main/index.ts#L10-L50 it returns headers in all scenarios, where you call data(), if theres a response object being returned, or if its just an object being returned.