Email and Password Authentication in Supabase
Supabase Auth provides secure authentication infrastructure out of the box, including session token encryption and password hashing. Let us implement basic email/password authentication.
1. Registering Users (Sign Up)
To register new users, call supabase.auth.signUp(). This registers the credentials in the internal auth.users system schema:
import { supabase } from "../lib/supabase";
async function handleRegister(emailStr: string, passwordStr: string) {
const { data, error } = await supabase.auth.signUp({
email: emailStr,
password: passwordStr,
});
if (error) {
console.error("Sign up failed:", error.message);
return;
}
// By default, Supabase sends a confirmation link to the email address
console.log("Check your email for confirmation link!");
}2. Authenticating Users (Sign In)
Once confirmed, users can log in using supabase.auth.signInWithPassword(). This opens a connection session and stores the authorization token in the browser client cookies or local storage automatically:
async function handleLogin(emailStr: string, passwordStr: string) {
const { data, error } = await supabase.auth.signInWithPassword({
email: emailStr,
password: passwordStr,
});
if (error) {
console.error("Login failed:", error.message);
return;
}
// Session token details saved automatically
console.log("User successfully logged in. User details:", data.user);
}3. Retrieving Active User State
To verify if a visitor is currently logged in, use the .getUser() query:
async function checkCurrentUser() {
const { data: { user }, error } = await supabase.auth.getUser();
if (error || !user) {
console.log("No active user session found");
return null;
}
console.log("Welcome back:", user.email);
return user;
}4. Signing Out (Logout)
To clear the active token session and sign out, call supabase.auth.signOut():
async function handleLogout() {
const { error } = await supabase.auth.signOut();
if (error) {
console.error("Logout failed:", error.message);
}
}Published on Last updated: