We don’t want the home page to be accessible unless a user is logged in.

In js/auth.js we will create two functions:

  • checkAuth - will check if there is a logged-in user. If there isn’t, it will redirect to login.html.
  • logout - will log the user out and redirect to login.html.
import { supabase } from "./supabase.js";

export async function checkAuth() {
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    window.location.href = "login.html";
  }

  console.log("user", user);
}

export async function logout() {
  const { error } = await supabase.auth.signOut();

  if (error) {
    console.error("Error logging out:", error);
  }

  window.location.href = "login.html";
}

Key Concepts

  • supabase.auth.getUser() checks if there’s a current session and returns the user object (containing id, email, etc.).
  • supabase.auth.signOut() clears the user session.

Tags: