Handling Logout

The final thing to handle on the home page is logging out. We need a log-out button:

<button id="logout-btn">Logout</button>

In js/posts.js, we have already imported the logout function from auth.js.

const logoutBtn = document.querySelector("#logout-btn");
logoutBtn.addEventListener("click", logout);

In a real application, we want to confirm with the user before logging out.

Handling Login

Finally, we want to handle logging in. Our HTMl and JS code will be very similar to our register code.

<form>
  <input name="email" type="email" required />
  <input name="password" type="password" required />
  <button>Login</button>
</form>

In js/login.js:

import { supabase } from "./supabase.js";

const loginForm = document.querySelector("form");

loginForm.addEventListener("submit", async function (e) {
  e.preventDefault();

  const form = e.target;
  const email = form.email.value.trim();
  const password = form.password.value;

  try {
    const { data, error } = await supabase.auth.signInWithPassword({
      email,
      password,
    });

    if (data.user) {
      console.log("user", data.user);
      console.log("session", data.session);
      // location.href = "/";
    }
  } catch (error) {
    // handler error
  }
});

Key Concepts

  • signInWithPassword() authenticates existing users (vs signUp() for creating new ones).
  • After successful login, we receive both the user object and session object.
  • The Supabase library automatically handles the session storage and management for us.
  • Sessions persist across page reloads, so users stay logged in.

In the code above, we are logging the user and session objects, but normally, we would want to redirect them here.

If you try to log in with an unconfirmed email, Supabase will return the error: Email not confirmed.


Tags: