Supabase "JWT expired" (PGRST303 or PGRST301): why it starts after an hour and how to fix it

By AI App Medic · Updated · Supabase · Auth · Sessions · Next.js

Users sign in and everything works. An hour or so later, or the morning after they left the tab open, lists come back empty, saves fail, and the console fills with 401 errors. The response body from the Data API says:

{"code":"PGRST303","details":null,"hint":null,"message":"JWT expired"}

On older projects the same message comes with PGRST301. Calls to Storage, Realtime or your Edge Functions fail around the same time with their own wording, and a server-rendered Next.js page may show no data at all. Reloading the page sometimes fixes it, which makes it look random. It is not random.

What the error means

A Supabase session has two parts. The access token is a JWT that every request carries in the Authorization header. It is short-lived on purpose, one hour by default. The refresh token is used to get a new access token when the old one runs out. In a browser, supabase-js does this for you: autoRefreshToken is on by default, and the client swaps the token shortly before it expires.

So when the database says JWT expired, the client library did not send that request with its current token, or nothing was running to refresh it. Almost every case comes down to one of these:

Step 1: decode the token that failed

Do not guess. In DevTools, open the Network tab, click the failed request, and copy the value after Bearer in the Authorization request header. Paste it into this in the console:

const token = 'eyJ...'
const payload = JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')))
console.log({
  issuedAt: new Date(payload.iat * 1000).toISOString(),
  expiresAt: new Date(payload.exp * 1000).toISOString(),
  now: new Date().toISOString(),
})

If expiresAt is in the past, some code sent an old token, and Steps 2 to 5 find where. If issuedAt is in the future or the times are off by minutes on a fresh login, go to Step 6. Never paste a live token into a website to decode it; the snippet above runs locally.

Step 2: stop storing the access token

This is the most common cause in apps built with Lovable, Bolt or Cursor. The generated code reads the token once after login and keeps it in React state, a context, localStorage or a client created with a fixed header:

// Breaks after an hour: the token is captured once
const { data } = await supabase.auth.getSession()
const token = data.session?.access_token

const api = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
  global: { headers: { Authorization: `Bearer ${token}` } },
})

// later, maybe hours later
await fetch('/api/report', { headers: { Authorization: `Bearer ${token}` } })

supabase-js refreshes its own session, but it cannot update a copy you made. The fix is to never keep the token. For normal queries, use the shared client and let it attach the current token. For your own API or a raw fetch to a function, ask for the session right before the call:

// Supabase queries: the client adds the current token itself
const { data, error } = await supabase.from('projects').select('*')

// Your own API: read the session at call time, never cache it
async function authFetch(input: string, init: RequestInit = {}) {
  const { data: { session } } = await supabase.auth.getSession()
  const headers = new Headers(init.headers)
  if (session) headers.set('Authorization', `Bearer ${session.access_token}`)
  return fetch(input, { ...init, headers })
}

In the browser, getSession() refreshes the session first if the stored token has expired, so this always sends a valid token. For Edge Functions, use supabase.functions.invoke, which also sends the current session.

Search the project for access_token, global: { headers and Authorization to find every place a token was copied. Also search for code that saves the session object to localStorage by hand; supabase-js already stores it.

Step 3: use one Supabase client in the browser

AI tools often call createClient in several files. If the console shows Multiple GoTrueClient instances detected in the same browser context, you have this problem. Each client runs its own refresh timer against the same stored session, so one client refreshes, the other keeps an old access token, and the refresh tokens can collide. Keep one module:

// src/lib/supabase.ts
import { createClient } from '@supabase/supabase-js'

export const supabase = createClient(
  import.meta.env.VITE_SUPABASE_URL,
  import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY
)

Import supabase from this file everywhere and delete the other createClient calls in front-end code. In Next.js, createBrowserClient from @supabase/ssr already returns a single shared instance.

Step 4: refresh the session on the server (Next.js)

With @supabase/ssr the session lives in cookies. Server Components cannot write cookies, so if nothing else refreshes them, every server query fails with JWT expired once the access token is an hour old. Supabase's answer is a proxy file that runs before each request, refreshes the token and writes the new cookies to both the request and the response. On Next.js 16 the file is proxy.ts. On Next.js 15 and earlier it must be middleware.ts with a function named middleware; a proxy.ts file is never called there, which is an easy mistake to make when an AI tool follows newer docs on an older project.

// lib/supabase/proxy.ts
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'

export async function updateSession(request: NextRequest) {
  let supabaseResponse = NextResponse.next({ request })

  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    {
      cookies: {
        getAll() {
          return request.cookies.getAll()
        },
        setAll(cookiesToSet, headers) {
          cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
          supabaseResponse = NextResponse.next({ request })
          cookiesToSet.forEach(({ name, value, options }) =>
            supabaseResponse.cookies.set(name, value, options)
          )
          Object.entries(headers).forEach(([key, value]) =>
            supabaseResponse.headers.set(key, value)
          )
        },
      },
    }
  )

  // Refreshes the session when needed. Keep nothing between createServerClient and this call.
  await supabase.auth.getClaims()

  return supabaseResponse
}

// proxy.ts (Next.js 16) or middleware.ts with "export async function middleware" (Next.js 15 and earlier)
import { type NextRequest } from 'next/server'
import { updateSession } from '@/lib/supabase/proxy'

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

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'],
}

Three details cause most of the remaining failures:

Other frameworks need the same thing: something that runs on every request, refreshes the session and writes the new cookies to the response.

Step 5: handle sleeping tabs and mobile apps

Browsers slow down or pause timers in background tabs, and supabase-js pauses its refresh while the tab is hidden, then checks the session when the tab becomes visible again. A request fired by your own code at that exact moment, such as a polling interval that wakes up first, can still go out with the old token. In a React Native or Expo app, refresh stops completely while the app is in the background unless you wire it to the app state, as Supabase's docs show:

import { AppState } from 'react-native'

AppState.addEventListener('change', (state) => {
  if (state === 'active') supabase.auth.startAutoRefresh()
  else supabase.auth.stopAutoRefresh()
})

For dashboards that stay open all day, add a single retry for this one error. Retry once only; if the refresh itself fails, the session is gone and the user has to sign in again:

async function withFreshToken<T extends { error: { code?: string; message?: string } | null }>(
  run: () => PromiseLike<T>
): Promise<T> {
  const res = await run()
  if (res.error && /jwt expired/i.test(res.error.message ?? '')) {
    const { error } = await supabase.auth.refreshSession()
    if (error) {
      await supabase.auth.signOut()
      window.location.assign('/login')
      return res
    }
    return run()
  }
  return res
}

const { data, error } = await withFreshToken(() => supabase.from('projects').select('*'))

This is a safety net, not the fix. If you need it often, Step 2 or Step 3 is still the real problem.

Step 6: check the clock

If the token in Step 1 was issued seconds ago but is still rejected, or the error says JWT issued at future, the problem is time, not refresh logic. Check the clock of the device or server that made the request. A laptop with automatic time turned off or a container without time sync can be minutes off. Servers that make Supabase calls with user tokens should run NTP. If every clock is correct and fresh tokens are still rejected, make sure your Supabase project is on the latest platform version from the dashboard and contact Supabase support with your project reference and the decoded iat and exp values, never the full token.

Edge Functions and your own backend

An Edge Function with JWT verification on rejects an expired token at the gateway with a 401 before your code runs. If you see that, fix the caller with the steps above; the function is fine. The 401 has other causes too, covered in Edge Function 401 Invalid JWT.

A background job or cron that saved a user's access token to act for them later will always hit this error. Jobs that are not acting inside a live user request should use a server-only secret key and check permissions in their own code, never a stored user token.

What not to do

Prevention

FAQ

Should I just make the JWT expiry longer?

No. A longer expiry only delays the error and makes a stolen token useful for longer. Supabase recommends the default of one hour for most apps. The error means some code is holding a token that supabase-js cannot refresh, and that code still breaks with a 24 hour expiry, just less often.

Is JWT expired the same as Invalid Refresh Token: Refresh Token Not Found?

No. JWT expired means an access token was sent after its exp time, and the session is usually still fine. Invalid Refresh Token means the refresh step itself failed, so the session is gone and the user has to sign in again. A stale token stored in your code can lead to the first; refreshing in two places at once often leads to the second.

Does supabase.auth.getSession() refresh an expired token?

In the browser, yes. If the stored access token has expired, getSession() uses the refresh token first and returns the new session. On the server it only reads the cookie and does not verify it, so in server code use getClaims() to check the user and rely on the proxy or middleware to refresh.

Why does it only happen in production?

During development you sign in often, restart the dev server and reload the page, so you rarely keep one session for a full hour. Real users leave a tab open over lunch or overnight, and that is when a stored token or a missing server refresh shows up.

What is the difference between PGRST301 and PGRST303?

Both come back as HTTP 401 from the Data API. Current PostgREST versions report a failed claims check, which includes an expired token, as PGRST303, and use PGRST301 for a token that cannot be decoded or is invalid. Older versions reported JWT expired under PGRST301. Read the message, not just the code.

Related guides