Supabase

How to set up custom claims in Supabase JWTs?

Discover how to efficiently set up custom claims in Supabase JWTs. Dive into this thorough guide for step-by-step instructions and top tips.

Developer profile skeleton
a developer thinking

Overview

Setting up custom claims in Supabase JWTs means tweaking settings within Supabase Auth and changing your JWT payload. Custom claims can stash extra user-specific info in the tokens, which amps up security and personalization for your app. Start by creating a middleware or server-side function to tack on claims based on roles, permissions, or other criteria. Adjusting the JWT structure without compromising the token's integrity and authenticity is key. Also, grasping the basics of JWT, the Supabase API, and security best practices is crucial for making it work right.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to set up custom claims in Supabase JWTs?

Step 1: Install Supabase Client Libraries

Alright, first things first, let's get those Supabase client libraries installed. You can use your favorite package manager for this. If you're an npm fan, just run:

npm install @supabase/supabase-js

Or if you prefer yarn, go with:

yarn add @supabase/supabase-js

Step 2: Initialize Supabase Client

Next up, we need to initialize the Supabase client in your project. Import the library and create a Supabase client instance. Don't forget to replace YOUR_SUPABASE_URL and YOUR_SUPABASE_KEY with your actual Supabase project URL and public API key.

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

const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseKey = 'YOUR_SUPABASE_KEY'

const supabase = createClient(supabaseUrl, supabaseKey)

Step 3: Define Custom Claims

Now, let's add some custom claims during the sign-up or sign-in process. This usually means working with user metadata when creating a user.

const { user, error } = await supabase.auth.signUp({
  email: '[email protected]',
  password: 'securepassword',
}, {
  data: {
    is_premium: true, // Custom Claim Example
    subscription_type: 'pro' // Another Custom Claim Example
  }
})

Step 4: Update Supabase JWT Secret

In Supabase, the JWT token is signed using a secret. You can update this secret to include custom claims by tweaking Supabase's environment settings.

  1. Head over to Settings in the Supabase dashboard.
  2. Click on API under settings.
  3. Update the JWT_SECRET to include a JSON payload with your custom claims.

For example:

{
  "iss": "your-domain.com",
  "sub": "1234567890",
  "aud": [
    "your-api-audience"
  ],
  "metadata": {
    "is_premium": true,
    "subscription_type": "pro"
  }
}

Make sure to place this updated secret in your environment variable setup for JWT_SECRET.

Step 5: Apply Custom Claims in Policies

Now, let's use those custom claims in your database policies for access control. For instance, in Supabase SQL:

-- Allow access only to premium users
create policy "Allow premium users"
on your_table
for select using (
  auth.jwt() ->> 'is_premium' = 'true'
);

This policy checks the is_premium claim in the JWT and grants access based on that condition.

Step 6: Verify Custom Claims in JWT

To make sure your custom claims are set correctly, decode the JWT using a JWT decoding tool or library. For example, with jwt-decode in JavaScript:

import jwtDecode from 'jwt-decode';

const jwt = supabase.auth.session()?.access_token
const decoded = jwtDecode(jwt);

console.log(decoded);

Step 7: Test and Validate

Finally, it's time to test and validate everything. Sign in or sign up users and check the JWT to ensure the custom claims are there.

  • Sign up a new user.
  • Verify that the custom claims show up in the JWT.
  • Test your policies to make sure they enforce the custom claims correctly.

Explore more Supabase tutorials

Complete Guide to Supabase: Tutorials, Tips, and Best Practices

Explore our Supabase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.