/supabase-tutorials

How to handle JWT expiration in Supabase?

Learn effective ways to handle JWT expiration in Supabase, configure token settings, auto-refresh sessions, and secure your authentication flow seamlessly.

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 handle JWT expiration in Supabase?

 

Step 1: Understand JWT in Supabase

 

JSON Web Tokens (JWT) are used for performing authentication and securing APIs. Supabase uses JWT for managing session state. Each JWT has an expiration time, which determines how long the token is valid.

 

Step 2: Configure JWT Expiration in Supabase

 

To handle JWT expiration, first you need to configure the expiration settings in Supabase:

  • Navigate to your Supabase project dashboard.
  • Go to the "Settings" tab and select "Auth Settings".
  • Find the section named "JWT Expiry".
  • Set the desired expiry time in seconds based on your application's needs. For example, set it to 3600 seconds for a 1-hour expiry.

 

Step 3: Detect JWT Expiration in Your Application

 

In your application, detect when a JWT has expired. Handle this by:

Using the Supabase client to check the current user's session state:


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

const supabase = createClient('your-supabase-url', 'your-supabase-key')

// Check the current user session
const session = supabase.auth.session()

if (!session) {
    console.log("No active session found. JWT may have expired.")
} else {
    const expiresAt = session.expires\_at
    const currentTime = Date.now() / 1000

    if (expiresAt < currentTime) {
        console.log("Session has expired.")
    } else {
        console.log("Session is still active.")
    }
}

 

Step 4: Refreshing the JWT

 

Implement JWT refresh functionality to maintain user sessions without requiring them to log in again:

  • When the JWT expiration is approaching, refresh the token automatically:

async function refreshToken() {
    const { user, error } = await supabase.auth.signIn({
        refreshToken: supabase.auth.session().refresh\_token,
    })

    if (error) {
        console.log("Error refreshing token:", error.message)
    } else {
        console.log("Token successfully refreshed. New session:", user)
    }
}
  • Invoke this function before the JWT expires or when certain actions require re-authentication.

 

Step 5: Handle Automatic JWT Refresh

 

To improve UX, automatically monitor token validity and refresh tokens in the background using a library like setInterval():


setInterval(() => {
    const currentTime = Date.now() / 1000
    const session = supabase.auth.session()

    if (session && session.expires\_at - currentTime < 600) { // Refresh if expiring within 10 mins
        refreshToken()
    }
}, 300000) // Check every 5 minutes

 

Step 6: Secure Your Refresh Strategy

 

Ensure that only safe environments can refresh JWTs by implementing:

  • HTTPS for all API interactions.
  • OAuth 2.0 or other secure flow using Supabase auth functions to further protect the refresh token mechanism.

This maintains secure JWT handling without constantly requiring user credentials.

 

Step 7: Logs and Monitoring

 

Add logs to monitor the expiration and refresh flow. Use Supabase or third-party logging tools to track any unexpected behavior:

  • Track successful token refresh events.
  • Monitor any refresh errors to alert you and help diagnose potential issues.

 

By following these comprehensive steps, you can effectively handle JWT expiration in Supabase and maintain secure and seamless user authentication in your application.

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