Nextbase Docs
Authentication

Login with Magic Link

Nextbase supports login with Magic Link, which is a secure way to authenticate users without requiring them to remember a password.

Server Action

Here's the server action used to login with Magic Link:

'use server';
import { createSupabaseUserServerActionClient } from '@/supabase-clients/user/createSupabaseUserServerActionClient';
import { toSiteURL } from '@/utils/helpers';
 
export const signInWithMagicLink = async (email: string, next?: string) => {
  const supabase = createSupabaseUserServerActionClient();
  const redirectUrl = new URL(toSiteURL('/auth/callback'));
  if (next) {
    redirectUrl.searchParams.set('next', next);
  }
  const { error } = await supabase.auth.signInWithOtp({
    email,
    options: {
      emailRedirectTo: redirectUrl.toString(),
    },
  });
 
  if (error) {
    console.log(error);
    throw error;
  }
};

Usage

Here's an example of how to use the Magic Link authentication in your login component:

const magicLinkMutation = useToastMutation(
  async (email: string) => {
    return await signInWithMagicLink(email, next);
  },
  {
    loadingMessage: 'Sending magic link...',
    errorMessage: 'Failed to send magic link',
    successMessage: 'Magic link sent!',
    onSuccess: () => {
      setSuccessMessage('A magic link has been sent to your email!');
    },
    onError: (error) => {
      console.log(error);
    },
    onMutate: () => {
      setSuccessMessage(null);
    },
  },
);
 
// In your component JSX
<Email
  onSubmit={magicLinkMutation.mutate}
  isLoading={magicLinkMutation.isLoading}
  view="sign-in"
/>;

This implementation allows users to receive a login link via email, providing a passwordless authentication experience.

On this page