Enable Supabase magic link login with our step-by-step guide. Learn to set up your project, configure authentication, code the login flow, and test passwordless sign-in.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set Up Your Supabase Project
First, ensure you have a Supabase project set up. If you haven’t done so yet, go to Supabase's website and create an account. Once logged in, you can start a new project by providing a name and choosing a database password.
Step 2: Configure Authentication Settings
Step 3: Set Up Environment for Your Application
You need to make sure that your application environment can communicate with your Supabase instance. Here’s a generic example using Node.js but adapt it to your stack if different:
npm install @supabase/supabase-js
After installation, initialize Supabase in your application:
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = 'https://xyzcompany.supabase.co'
const supabaseKey = 'public-anon-key'
const supabase = createClient(supabaseUrl, supabaseKey)
Step 4: Code the Magic Link Login Functionality
Set up a function to trigger the magic link to the user's email:
async function sendMagicLink(email) {
const { user, error } = await supabase.auth.signInWithOtp({ email })
if (error) {
console.error('Error sending Magic Link:', error)
} else {
console.log('Magic link sent to:', user.email)
}
}
Call this function and pass the user's email input:
const email = '[email protected]'
sendMagicLink(email)
Step 5: Handle the Auth Redirect
Ensure your app can handle the magic link redirection. Typically, Supabase will append a token and a type to the URL when redirecting. You need to capture and use these to update the user's authentication state.
Here's how you might do this in a client-side app:
import { useEffect } from 'react'
import { supabase } from './supabaseClient'
useEffect(() => {
const { data } = supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED\_IN') {
// User now signed in, handle post-login logic here
console.log('User signed in:', session.user)
}
})
return () => {
data.unsubscribe()
}
}, [])
Step 6: Testing Magic Link
Test this functionality by trying to log in with a valid email. Ensure Supabase email configuration is set properly to receive the email. Supabase's free tier uses a shared SMTP server for sending emails, so make sure these emails don’t land in the spam folder.
Test the flow end-to-end to verify that users can initiate a login, receive an email, click the link, and be redirected to a logged-in state in your application.
Following these steps, you will be able to enable the magic link login for your application using Supabase, easily integrating secure and efficient passwordless authentication for users.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.