authenticationnext.jsaccess-tokensupabasesupabase-js

How do I persist the the user with supabase using nextjs?


import { createClient } from "@supabase/supabase-js";

export const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPADB_URL || "",
  process.env.NEXT_PUBLIC_SUPADB_API_KEY || "",
  {
    auth: {
      detectSessionInUrl: false,
    },
  }
);

I need the email verification link to be used to verify the user and detectSessionInUrl should be true but then I need to set it to false so that the session persists because this is an SPA

I expected that this would be done out of the box without any issue.


Solution

  • For NextJS and Supabase, I usually would use NextAuth for authentication (if you aren't already).

    During auth, check if the user is new or existing. For new users, send an email verification request and require them to verify email.

    When the user successfully verifies their email and returns to your site (upon refresh i.e), through NextAuth, you fetch the user's verification status from the database.

    You can then store this verification status in i.e. Zustand or directly reference it from NextAuth hooks (e.g., emailVerified) and perform the necessary checks from there.

    NextAuth in this case persists the user through i.e. JWTs for you.

    I can provide pseudo code here if needed