Supabase

How to implement custom authentication in Supabase?

Discover how to set up custom authentication in Supabase with our easy-to-follow guide. Boost security and take control using tailored authentication methods. Simple steps and clear instructions await.

Developer profile skeleton
a developer thinking

Overview

Custom authentication in Supabase lets developers surpass the usual auth methods—like email, password, and OAuth—to cater to specific security and user management demands. It means integrating third-party authentication systems, using single sign-on (SSO), or designing unique workflows. Doing this often needs knowledge of Supabase's Auth API and JWT tokens, and might involve other services such as Auth0 or Firebase. This flexibility grants developers the ability to craft more personalized and secure user experiences, all while benefiting from Supabase's robust backend.

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 implement custom authentication in Supabase?

Step 1: Set Up Supabase Project

  1. Head over to the Supabase website and either sign in or create a new account if you don't have one yet.
  2. Start a new project by filling in the details like project name, organization, and database password.
  3. After your project is up and running, go to the Project Settings to grab your API keys. You'll need these for custom authentication.

Step 2: Create Database Table for Users

  1. In the Supabase dashboard, find the Database section.
  2. Create a new SQL table called custom_users (or whatever name you like) with columns like id, email, password_hash, created_at, etc. Here's a sample schema:
    ```sql
    CREATE TABLE custom_users (
    id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
    email text UNIQUE NOT NULL,
    password_hash text NOT NULL,
    created_at timestamp with time zone DEFAULT timezone('utc'::text, now()) NOT NULL
    );
    ```
  3. Hit Save to lock in the changes.

Step 3: Set Up Custom Authentication Backend

  1. Set up a new backend service or use one you already have. This could be a Node.js/Express server, a Next.js API route, or any other backend framework you like.
  2. Use bcrypt or another hashing library to securely handle password encryption.
  3. Install the @supabase/supabase-js package to connect with Supabase from your backend:
    ```bash
    npm install @supabase/supabase-js
    ```
  4. Initialize the Supabase client in your backend:
    ```javascript
    const { createClient } = require('@supabase/supabase-js');
    const supabase = createClient('your-supabase-url', 'your-anon-key');
    ```

Step 4: Register Endpoint

  1. Create a registration endpoint (e.g., /register) in your backend.

  2. In the endpoint logic, hash the user’s password and insert the new user into the custom_users table:
    ```javascript
    const bcrypt = require('bcrypt');

    app.post('/register', async (req, res) => {
    const { email, password } = req.body;
    const passwordHash = await bcrypt.hash(password, 10);

    const { data, error } = await supabase
    .from('custom_users')
    .insert([{ email, password_hash: passwordHash }]);
    if (error) return res.status(400).json({ error: error.message });
    res.status(201).json({ message: 'User registered successfully' });
    });
    ```

Step 5: Login Endpoint

  1. Create a login endpoint (e.g., /login) in your backend.

  2. In the endpoint logic, compare the given password to the stored password hash:
    ```javascript
    app.post('/login', async (req, res) => {
    const { email, password } = req.body;

    const { data, error } = await supabase
    .from('custom_users')
    .select('*')
    .eq('email', email)
    .single();
    if (error || !data) return res.status(400).json({ error: 'Invalid email or password' });

    const isPasswordValid = await bcrypt.compare(password, data.password_hash);
    if (!isPasswordValid) return res.status(400).json({ error: 'Invalid email or password' });

    res.status(200).json({ message: 'Login successful' });
    });
    ```

Step 6: Integrate Middleware for Protected Routes

  1. To protect certain routes, add a middleware that verifies the user's session or token. You can use jsonwebtoken or any other session management library.

  2. Example middleware to authenticate routes:
    ```javascript
    const jwt = require('jsonwebtoken');

    const authenticateToken = (req, res, next) => {
    const token = req.headers['authorization'];
    if (!token) return res.sendStatus(403);

    jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
    });
    };

    app.get('/protected', authenticateToken, (req, res) => {
    res.status(200).json({ message: 'This is a protected route' });
    });
    ```

Step 7: Testing & Deployment

  1. Test the registration and login endpoints using Postman or another API client.
  2. Check that the user records are being added to the custom_users table.
  3. Make sure the login mechanism correctly validates credentials and that protected routes are secure.
  4. Deploy your backend service to a hosting provider like Vercel, Netlify, Heroku, or any other service you prefer.

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.