/supabase-tutorials

How to refresh a session token in Supabase?

Refresh your Supabase session tokens effortlessly. This guide covers client setup, token expiry handling, manual refresh, and storing updated sessions for smooth user authentication.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to refresh a session token in Supabase?

 

Step 1: Understand the Context

 

Before delving into code, it's essential to understand what a session token is. It’s a security credential used by Supabase to verify a user’s session. Once logged in with email/password, Supabase generates a session token. This token might expire, requiring a refresh to re-authenticate the session without the user having to log in again.

 

Step 2: Setup your Supabase Environment

 

Ensure you have the Supabase setup in your development environment. If you haven't already, install the @supabase/supabase-js package using npm or yarn.


npm install @supabase/supabase-js

or


yarn add @supabase/supabase-js

You'll also need to create a Supabase project from their dashboard and get the API URL and anon key.

 

Step 3: Initialize Your Supabase Client

 

Start by initializing your Supabase client in your application. Import the necessary functions and create a Supabase client using your API details.


import { createClient } from '@supabase/supabase-js'

const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseAnonKey = 'YOUR_SUPABASE_ANON\_KEY'

const supabase = createClient(supabaseUrl, supabaseAnonKey)

Replace the placeholders YOUR_SUPABASE_URL and YOUR_SUPABASE_ANON_KEY with your actual Supabase project URL and anonymous key.

 

Step 4: Listening for Token Expiry

 

Supabase client automatically refreshes session tokens. However, to handle custom logic upon token refresh, you can listen for any authentication state changes:


supabase.auth.onAuthStateChange((event, session) => {
  if (event === 'TOKEN\_REFRESHED') {
    console.log('Token has been refreshed:', session)
  }
})

This function logs the new session whenever the token is refreshed.

 

Step 5: Refresh Token Manually (if needed)

 

While Supabase handles token refresh automatically, you might encounter scenarios where you need to perform this manually. To perform a manual refresh, check if a session exists and invoke the refresh method:


const refreshSessionToken = async () => {
  const { session, error } = await supabase.auth.refreshSession()

  if (error) {
    console.error('Error refreshing session:', error)
  } else {
    console.log('Session refreshed:', session)
  }
}

refreshSessionToken()

Note that this method might not be available in all SDK versions. Always refer to the most recent documentation for updates.

 

Step 6: Store the Updated Session

 

Ensure to store the refreshed session either in your app's state or local storage if you rely on this data for subsequent API requests or user session management.


localStorage.setItem('supabase.auth.token', JSON.stringify(session))

 

Conclusion

 

This tutorial provided a comprehensive guide to understand and implement session token refresh in Supabase. It involves initializing the Supabase client, listening for session token events, manually refreshing tokens if necessary, and storing refreshed sessions for application use. Always refer to the Supabase documentation for any updates or changes in the SDK.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022