/supabase-tutorials

How to allow login only for invited users in Supabase?

Configure Supabase for invite-only login by setting up a custom invites table, authentication triggers, and email notifications for secure access.

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 allow login only for invited users in Supabase?

 

Step 1: Set Up Your Supabase Project

 

Begin by creating a project in Supabase if you haven't already. Visit the Supabase dashboard and either create a new project or access an existing project. Note the project's URL and anon key as these will be necessary for setting up the frontend and backend.

 

Step 2: Configure Authentication Settings

 

In Supabase, head over to the Authentication section and adjust the settings to allow only invited users.

  1. Navigate to the Authentication tab in the Supabase dashboard.
  2. Under the Settings tab, locate the Email settings section.
  3. Ensure that "Enable email signup" is not checked to prevent users from signing up without an invitation.

 

Step 3: Create an invites Table

 

Set up a table to track invitations in your database.

 

create table invites (
  id uuid default uuid_generate_v4() primary key,
  email text unique not null,
  invited_at timestamp default now()
);

 

Step 4: Set Up a Server Function to Handle Invitations

 

Write a server-side function or API endpoint to allow admins to invite users by adding them to the invites table.

Suppose you're using Node.js and Express, an example of an API endpoint might look like this:

 

const express = require('express');
const { createClient } = require('@supabase/supabase-js');

const supabaseUrl = 'your_supabase_url';
const supabaseKey = 'your_anon_key';
const supabase = createClient(supabaseUrl, supabaseKey);
const app = express();

app.use(express.json());

app.post('/invite', async (req, res) => {
  const { email } = req.body;

  try {
    const { data, error } = await supabase
      .from('invites')
      .insert([{ email }]);

    if (error) throw error;

    res.status(200).send({ message: 'User invited successfully.', data });
  } catch (error) {
    res.status(400).send({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

 

Step 5: Add User Authentication Logic

 

Implement user authentication so that only users with an invitation can sign in. You can do this by setting up database triggers or writing additional logic to check if a user's email is present in the invites table upon signup.

Configure a trigger using SQL to automatically insert users into the auth.users table if they already have an invite:

 

create function invite_only_auth()
returns trigger as $$
begin
  if exists(select 1 from invites where email = new.email) then
    return new;
  else
    raise exception 'Signup not allowed';
  end if;
end;
$$ language plpgsql;

create trigger on_auth_signup
before insert on auth.users
for each row execute procedure invite_only_auth();

 

Step 6: Notify Invited Users

 

Once a user is invited, send them an email with a link to complete their registration. You could use services like SendGrid, Mailgun, or any other email service provider. Here is a conceptual example using SendGrid:

 

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey('your_sendgrid_api_key');

app.post('/invite', async (req, res) => {
  const { email } = req.body;

  try {
    const { data, error } = await supabase
      .from('invites')
      .insert([{ email }]);

    if (error) throw error;

    const msg = {
      to: email,
      from: '[email protected]',
      subject: 'You are Invited',
      text: `You have been invited to join our platform. Click here to register: [registration link]`,
    };

    await sgMail.send(msg);
    res.status(200).send({ message: 'User invited and notified via email.', data });
  } catch (error) {
    res.status(400).send({ error: error.message });
  }
});

 

Step 7: Test the Registration Flow

 

After setting up everything, perform a test to ensure only invited emails can complete the signup process. Send an invite to a test email, follow the link, and ensure only this email can be used to register.

With these steps, you've configured Supabase to allow login only for users who are invited. This setup not only restricts access but also makes your application more secure.

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