Nextbase Docs
Authentication

Login with Password

Nextbase supports traditional email and password authentication, providing a familiar login experience for users.

Here's the server action used for password-based signup. Login is similar, but uses a different schema and action.

We use next-safe-action to ensure type safety and error handling for our server actions. Next safe action errors are also passed along to react hook form with field level errors to correctly display errors in the UI.

'use server';
import { createSupabaseUserServerActionClient } from '@/supabase-clients/user/createSupabaseUserServerActionClient';
// ...other imports
/**
 * Signs up a new user with email and password.
 * @param {Object} params - The parameters for sign up.
 * @param {string} params.email - The user's email address.
 * @param {string} params.password - The user's password (minimum 8 characters).
 * @returns {Promise<Object>} The data returned from the sign-up process.
 * @throws {Error} If there's an error during sign up.
 */
export const signUpWithPasswordAction = actionClient
  .schema(signUpWithPasswordSchema)
  .action(async ({ parsedInput: { email, password, next } }) => {
    const supabase = createSupabaseUserServerActionClient();
    const emailRedirectTo = new URL(toSiteURL('/auth/callback'));
    if (next) {
      emailRedirectTo.searchParams.set('next', next);
    }
    const { data, error } = await supabase.auth.signUp({
      email,
      password,
      options: {
        emailRedirectTo: emailRedirectTo.toString(),
      },
    });
 
    if (error) {
      const errorDetails = handleSupabaseAuthPasswordSignUpErrors(error);
      if (errorDetails.field) {
        returnValidationErrors(signUpWithPasswordSchema, {
          [email]: {
            _errors: [errorDetails.message],
          },
        });
      } else {
        returnValidationErrors(signUpWithPasswordSchema, {
          _errors: [errorDetails.message],
        });
      }
    }
 
    return data;
  });

Usage

Here's an example of how to use password-based authentication in your login component:

const signUpWithPasswordMutation = useAction(signUpWithPasswordAction, {
  onExecute: () => {},
  onSuccess: () => {},
  onError: ({ error }) => {}
);
 
// In your component JSX
<EmailAndPassword
  isLoading={signUpWithPasswordMutation.execute}
  onSubmit={(data) => {
    passwordMutation.mutate(data);
  }}
  view="sign-in"
/>;

This implementation allows users to log in using their email and password credentials.

On this page