/supabase-tutorials

How to add a phone number to Supabase user profile?

Learn how to add a phone number to your Supabase user profile. Follow this step-by-step guide to update your schema, call APIs, and adjust your UI effectively.

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 add a phone number to Supabase user profile?

 

Step 1: Set Up Supabase Project

 

To start adding a phone number to a Supabase user profile, first, ensure you have a Supabase project set up. You can create a new Supabase project from the Supabase website. It requires you to log in and then follow the process to create a new project where you will be provided with an API URL and an API Key.

 

Step 2: Initialize Your Project with Supabase

 

Ensure you have Node.js installed. Then, initialize your project with Supabase by installing the @supabase/supabase-js package.

npm install @supabase/supabase-js
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'https://your-project-id.supabase.co';
const supabaseKey = 'your-anon-key';
const supabase = createClient(supabaseUrl, supabaseKey);

 

Step 3: Add the Phone Number Field to the User Schema

 

By default, the Supabase authentication system includes basic fields in the user profile. To add more fields like a phone number, you need to extend the users' table in the Supabase database. This can be done through the SQL Editor in the Supabase dashboard.

ALTER TABLE auth.users
ADD COLUMN phone_number VARCHAR;

This SQL command adds a new column named phone_number to the users table.

 

Step 4: Update a User Profile with Phone Number

 

Now, you can update a user profile to include a phone number using Supabase's API. Here's how you can update a specific user's phone number:

const updateUserPhoneNumber = async (userId, phoneNumber) => {
  const { data, error } = await supabase
    .from('users')
    .update({ phone_number: phoneNumber })
    .eq('id', userId);

  if (error) {
    console.error('Error updating phone number:', error);
    return;
  }

  console.log('User phone number updated:', data);
};

// Example usage
updateUserPhoneNumber('user-123', '123-456-7890');

Make sure to replace 'user-123' with the actual user's ID you wish to update.

 

Step 5: Fetch User Data Including Phone Number

 

To retrieve user data including the newly added phone number, you can perform a simple SELECT query through Supabase.

const fetchUserProfile = async (userId) => {
  const { data, error } = await supabase
    .from('users')
    .select('id, email, phone_number')
    .eq('id', userId);

  if (error) {
    console.error('Error fetching user profile:', error);
    return;
  }

  console.log('User profile:', data);
};

// Example usage
fetchUserProfile('user-123');

This query will return the user's id, email, and phone number.

 

Step 6: Implementing UI Changes (Optional)

 

If you're building a client application, you'll want to include form fields to capture and display the phone number. This step involves modifying your frontend form to capture the phone number and updating an event handler to send the phone number alongside other profile data to your Supabase backend.

For example, if you're using React:

import React, { useState } from 'react';

const UserProfileForm = ({ userId }) => {
  const [phoneNumber, setPhoneNumber] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();

    const { data, error } = await supabase
      .from('users')
      .update({ phone_number: phoneNumber })
      .eq('id', userId);

    if (error) {
      console.error('Error updating profile:', error);
    } else {
      console.log('Profile updated successfully:', data);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Phone Number:
        <input
          type="text"
          value={phoneNumber}
          onChange={(e) => setPhoneNumber(e.target.value)}
        />
      </label>
      <button type="submit">Update Profile</button>
    </form>
  );
};

export default UserProfileForm;

Make sure you import supabase from your initialized Supabase client file.

 

Conclusion

 

Following these steps will allow you to add and manage a phone number in your Supabase user profile system. It involves modifying your database schema, using Supabase API calls to update and retrieve user data, and optionally adjusting your frontend for capturing new user information. Ensure your application logic is sufficiently robust to handle any potential errors, especially when dealing with user data and database operations.

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