How to store user id in supabase table for a logged in user

Lonare
4 min readSep 9, 2024

--

supabase user id

Storing user-specific data in your Supabase table is a key part of developing any application that involves user authentication.

Whether you’re building a blog, e-commerce site, or any app requiring user login, you’ll need to store user IDs associated with each logged-in user to link their data.

This article will guide you through the process of storing a logged-in user’s ID in a Supabase table step-by-step.

Step 1: Set Up Supabase Authentication

Before you can store user IDs, you’ll need to ensure your users are authenticated. Supabase provides easy-to-use authentication services out of the box.

  1. Create a Supabase account: If you haven’t already, sign up for Supabase and create a new project.
  2. Enable authentication: In the Supabase dashboard, go to the “Authentication” tab and set up your preferred sign-in method (e.g., email, social login, etc.).
  3. Install Supabase in your app: You can integrate Supabase into your frontend using the following commands based on your project setup
npm install @supabase/supabase-js
  1. Initialize Supabase in your app:
import { createClient } from '@supabase/supabase-js'  
const supabaseUrl = 'https://your-project-url.supabase.co'
const supabaseAnonKey = 'your-anon-key'
const supabase = createClient(supabaseUrl, supabaseAnonKey)

Step 2: Authenticate the User and Retrieve the User ID

Once your users can log in, you’ll need to capture their user ID. Supabase assigns a unique id to every authenticated user, which can be accessed via the authentication session.

Here’s how you can retrieve the current logged-in user’s ID:

const user = supabase.auth.user();
if (user) {
const userId = user.id; // This is the unique user ID
console.log('User ID:', userId);
}

Step 3: Create a Table to Store User-Specific Data

Now that you can access the logged-in user’s ID, it’s time to store this data in a Supabase table. Follow these steps:

  1. Create a new table in the Supabase dashboard:
  2. Go to the “Database” tab, then “Tables”.
  3. Create a table, e.g., user_data.
  4. Add columns like id (primary key), user_id (to store the logged-in user’s ID), and any other fields you need.
  5. Set up the schema. For example:
  6. ColumnTypeDescriptionidbigintPrimary key, auto-incrementuser_iduuidStores the user’s unique IDcontenttextAny user-specific data

Step 4: Insert User ID into the Table

Whenever a user performs an action in your app (e.g., submits a form), you’ll want to store their user_id in the user_data table. Here's how to insert a record into Supabase using the logged-in user’s ID:

const { data, error } = await supabase
.from('user_data')
.insert([
{ user_id: user.id, content: 'Some user-specific data' }
])
if (error) {
console.error('Error inserting user data:', error);
} else {
console.log('User data inserted:', data);
}

Step 5: Retrieve Data Based on User ID

If you want to fetch data for the currently logged-in user, use the following query:

const { data, error } = await supabase
.from('user_data')
.select('*')
.eq('user_id', user.id);
if (error) {
console.error('Error fetching user data:', error);
} else {
console.log('User data:', data);
}

This will retrieve any data related to that specific user, allowing you to personalise the app experience for them.

Bonus: Use Row-Level Security (RLS)

To ensure that only the user who owns the data can access or modify it, you can enable Row-Level Security (RLS) in Supabase. This is critical for safeguarding user data.

  1. Enable RLS: In the Supabase dashboard, go to your table and enable Row-Level Security.
  2. Write policies to restrict access. For example, to allow only the logged-in user to access their data, you can write a policy like:
CREATE POLICY "Allow logged-in user access to their data"
ON user_data
FOR SELECT, INSERT, UPDATE, DELETE
USING (auth.uid() = user_id);

This policy ensures that only the user with the correct user_id can access their rows in the table.

Or you can just use a default value for your user if field in the supabase and use as default value and it will store the logged in users id into the database table

auth.uid()

Conclusion

Storing a logged-in user’s ID in a Supabase table is straightforward. With the combination of authentication, data insertion, and row-level security, you can safely manage user-specific data in your app. Supabase simplifies this process, allowing you to focus more on building your app’s features rather than worrying about backend setup.

With these steps, you’ll be well on your way to securely handling user data and creating personalised user experiences in your Supabase-powered applications!

--

--

Lonare
Lonare

Written by Lonare

Imagination is the key to unlock the world. I am trying to unlock mine.