Passwordless OTP with Supabase

Passwordless login with one-time passwords (OTP) sent via email is a secure and user-friendly authentication method.

Supabase (as usual) makes this process simple with built-in support for email OTPs.

Here’s How:

Setting Up Email OTP

Supabase has email authentication, including OTP, enabled by default. To use OTPs, you need to modify the email template.

  1. Go to Email Templates in your Supabase Dashboard (for hosted projects).
  2. Modify the template to include the OTP token using the variable {{ .Token }}.

Example template:

<h2>Here is your OTP</h2>
<p>Enter this code: {{ .Token }}</p>

Send the OTP

To start the OTP process, you need to send a code to the user’s email. Here’s how to do it:

  1. Collect the user’s email.
  2. Call the signInWithOtp method from your client library.

Example in JavaScript:

const { data, error } = await supabase.auth.signInWithOtp({
  email: 'user@example.com',
  options: {
    shouldCreateUser: true,  // Set to false if you don't want automatic signup, but for the demo I'll let users signup too!
  },
});

if (!error) {
  console.log("OTP sent. Check your email.");
} else {
  console.error("Error sending OTP:", error);
}

Verifying the OTP

Once the user receives the OTP via email, they need to enter it on your site. Here’s how to verify the OTP:

  1. Provide an input field for the user to enter the OTP.
  2. Use the verifyOtp method to validate the code.

Example in JavaScript:

const email = 'user@example.com';  // The user's email
const otp = '123456';  // The OTP entered by the user

const { data, error } = await supabase.auth.verifyOtp({
  email,
  token: otp,
  type: 'email',
});

if (data && data.session) {
  console.log("User logged in successfully:", data.session);
} else {
  console.error("Error verifying OTP:", error);
}

And that's it! Just adjust this code to your use case.

SupabaseJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.