Site icon JD Bots

How to Build a Sign-Up Form with Better Auth in Next.js

A dark indigo card titled Better Auth Sign-Up Form, labelled Better Auth How-To, with the line Create accounts in Next.js with authClient.signUp.email, beside a drawing of a Create your account form with name, email and password fields and a Sign up button.

How to build a sign-up form with Better Auth in Next.js.

A sign-up form collects a name, an email address and a password, and Better Auth turns them into an account. This guide builds a Better Auth sign-up form in Next.js with authClient.signUp.email, creates an account with it, and shows what happens when the email address is already taken.

The short answer: in a client component, call authClient.signUp.email({ name, email, password }). Better Auth creates the user, stores a hash of the password and, by default, signs the new user in.

Syntax

Syntax

const { data, error } = await authClient.signUp.email({
  name: "<display name>",
  email: "<email address>",
  password: "<password>",
  image: "<picture address>",
  callbackURL: "<page address>",
});

The reference: Sign Up in the Better Auth documentation.

Prerequisites

Step 1: Create the Sign-Up Page

The example is a small bookshop app with a header that shows who’s signed in. In the app folder, create a folder named sign-up, and in it a file named page.tsx:

app/sign-up/page.tsx

"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { type FormEvent, useState } from "react";
import { authClient } from "@/lib/auth-client";

export default function SignUpPage() {
  const router = useRouter();
  const [errorMessage, setErrorMessage] = useState("");
  const [isPending, setIsPending] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    setErrorMessage("");
    setIsPending(true);

    const { error } = await authClient.signUp.email({
      name: String(form.get("name")),
      email: String(form.get("email")),
      password: String(form.get("password")),
    });

    setIsPending(false);
    if (error) {
      setErrorMessage(error.message ?? "Sign-up failed. Please try again.");
      return;
    }
    router.push("/");
  }

  return (
    <main className="mx-auto w-full max-w-sm flex-1 px-6 py-12">
      <h1 className="text-2xl font-semibold">Create your account</h1>
      <form onSubmit={handleSubmit} className="mt-6 flex flex-col gap-4">
        <label className="flex flex-col gap-1 text-sm">
          Name
          <input
            name="name"
            required
            autoComplete="name"
            className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
          />
        </label>
        <label className="flex flex-col gap-1 text-sm">
          Email
          <input
            name="email"
            type="email"
            required
            autoComplete="email"
            className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
          />
        </label>
        <label className="flex flex-col gap-1 text-sm">
          Password
          <input
            name="password"
            type="password"
            required
            minLength={8}
            autoComplete="new-password"
            className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
          />
        </label>
        {errorMessage && (
          <p role="alert" className="text-sm text-red-600">
            {errorMessage}
          </p>
        )}
        <button
          type="submit"
          disabled={isPending}
          className="rounded bg-zinc-900 px-4 py-2 text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900"
        >
          {isPending ? "Creating account…" : "Sign up"}
        </button>
      </form>
      <p className="mt-6 text-sm">
        Already have an account?{" "}
        <Link href="/sign-in" className="underline">
          Sign in
        </Link>
      </p>
    </main>
  );
}

Step 2: Create an Account

Open /sign-up in your browser and fill in the form. Here it’s Lena Park, a customer of the bookshop:

The sign-up form, filled in.

Click Sign up. Better Auth creates the account and signs Lena in, so the header shows her name:

Signed in straight after signing up.

Step 3: Try an Email Address That’s Taken

Sign out, open /sign-up again and sign up with the same email address:

An email address can only have one account.

Better Auth refuses with status 422 and the message User already exists. Use another email., which the form shows.

Common Mistakes

MistakeWhat happensDo this instead
Calling signUp.email on the serverIt’s the browser client, meant for client componentsKeep it in a component that starts with "use client"
Ignoring errorA failed sign-up looks like nothing happenedShow error.message next to the form

FAQ

Why is the new user signed in straight away?

autoSignIn is true by default. Set autoSignIn: false in emailAndPassword to make new users sign in themselves.

Can I collect more than a name?

Yes, with additional fields on the user (Extending core schema). Part 6 of the Better Auth Tutorial covers it.

Conclusion

authClient.signUp.email turns a name, an email address and a password into an account, and signs the person in. Show error.message when it fails, such as for an email address that already has an account.

Additional Resources

Related

Better Auth, Next.js and other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by Better Auth, Inc. or Vercel.

Exit mobile version