# Password Reset and Email Verification in Next.js

Add a forgot password flow, a reset password page and required email verification to a Next.js app, using CloudHike Auth to send the emails and check the tokens.

*Intermediate · 25 min · Updated Nov 18, 2026*

## What you'll build

- A forgot password form that never reveals which emails have accounts
- A reset password page that reads the token from the link and sets a new password
- Sign-in blocked until the user verifies their email, with a resend button
- Branded reset and verification emails, sent from your own domain

## Before you start

- A Next.js 16 app using the App Router
- Email and password sign-up working, for example from [Next.js Authentication with Email and Google](https://cloudhike.dev/guides/nextjs-authentication-email-google)
- A CloudHike.dev project with Auth deployed

## How the two flows work

Both flows rest on the same idea: prove the person controls an inbox by sending a link with a secret token. The hard parts are creating tokens that can't be guessed, expiring them, and sending the email. CloudHike Auth does those for you. You build the forms and pages.

| Step | Who does it |
| --- | --- |
| User asks to reset their password | Your form calls `POST {AUTH_URL}/request-password-reset` |
| Token is created and the reset email is sent | CloudHike Auth |
| User clicks the link and lands on `/reset-password?token=...` | Your page |
| New password is saved | Your form calls `POST {AUTH_URL}/reset-password` |
| New user signs up and gets a verification link | CloudHike Auth, when **Require a verified email** is on |
| Sign-in is refused until the link is opened | CloudHike Auth answers `403`; your form offers a resend |

You don't need to deploy the Email service for these emails. Auth sends them itself, so you configure no SMTP. If you also verify a domain under Email, Auth can send from it.

## Step 1: Turn on verification and add your sites

1. In your CloudHike project, open **Auth** and go to the **Providers** tab.
2. Turn on **Require a verified email** before sign-in.
3. Under the sites users may return to, add `http://localhost:3000` and your production address, one per line. Reset and verification links only send people back to these sites.
4. Copy the Auth values into `.env.local` and add your app's own address.

*.env.local*

```bash
AUTH_URL=https://...
AUTH_PUBLISHABLE_KEY=...
# Your app's address, used to build links in the emails
APP_URL=http://localhost:3000
```

> **Note:** These flows only need the publishable key. `AUTH_SECRET_KEY` is for admin endpoints and should never be used here. See the [Auth endpoints](https://cloudhike.dev/docs/auth#endpoints) for the full list.

## Step 2: Write a server-only Auth helper

The publishable key is safe in browser code, but calling Auth from the server keeps the session cookie, redirects and error messages in one place. Every call sends `x-api-key` and reads `{ message }` on errors.

```bash
npm install server-only
```

*lib/auth.ts*

```ts
import "server-only";

export type User = { id: string; email: string; name?: string };

export class AuthError extends Error {
  constructor(message: string, public status: number) {
    super(message);
  }
}

async function post<T>(path: string, body: unknown): Promise<T> {
  const res = await fetch(`${process.env.AUTH_URL}${path}`, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-api-key": process.env.AUTH_PUBLISHABLE_KEY!,
    },
    body: JSON.stringify(body),
    cache: "no-store",
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new AuthError(data.message ?? res.statusText, res.status);
  return data as T;
}

const appUrl = (path: string) => new URL(path, process.env.APP_URL).toString();

export const signUp = (name: string, email: string, password: string) =>
  post<{ token: string; user: User }>("/sign-up/email", { name, email, password });

export const signIn = (email: string, password: string) =>
  post<{ token: string; user: User }>("/sign-in/email", { email, password });

export const requestPasswordReset = (email: string) =>
  post("/request-password-reset", { email, redirectTo: appUrl("/reset-password") });

export const resetPassword = (token: string, newPassword: string) =>
  post("/reset-password", { newPassword, token });

export const sendVerificationEmail = (email: string) =>
  post("/send-verification-email", { email, callbackURL: appUrl("/sign-in?verified=1") });
```

The session token goes in an HTTP-only cookie that only your server can read. `cookies()` is async in Next.js 16, so `await` it.

*lib/session.ts*

```ts
import "server-only";
import { cookies } from "next/headers";

export async function setSession(token: string) {
  (await cookies()).set("session", token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
  });
}
```

## Step 3: Build the forgot password form

The form asks for an email and always shows the same answer, whether or not an account exists. Otherwise anyone could use it to find out who has signed up.

*app/actions/auth.ts*

```ts
"use server";

import { redirect } from "next/navigation";
import { AuthError, requestPasswordReset, resetPassword, sendVerificationEmail, signIn, signUp } from "@/lib/auth";
import { setSession } from "@/lib/session";
import { cookies } from "next/headers";

export type FormState = { ok: boolean; message: string; email?: string; unverified?: boolean } | null;

const isEmail = (s: string) => /^\S+@\S+\.\S+$/.test(s);

export async function forgotPassword(_prev: FormState, form: FormData): Promise<FormState> {
  const email = String(form.get("email") ?? "").trim().toLowerCase();
  if (!isEmail(email)) return { ok: false, message: "Please enter a valid email." };

  try {
    await requestPasswordReset(email);
  } catch (err) {
    // Only server trouble is worth showing. Anything else gets the same answer.
    if (err instanceof AuthError && err.status >= 500) {
      return { ok: false, message: "We couldn't send the email right now. Please try again in a minute." };
    }
    console.error("request-password-reset", err);
  }
  return { ok: true, message: "If an account exists for that email, we've sent a link to reset your password." };
}

export async function chooseNewPassword(_prev: FormState, form: FormData): Promise<FormState> {
  const token = String(form.get("token") ?? "");
  const password = String(form.get("password") ?? "");
  const confirm = String(form.get("confirm") ?? "");

  if (password.length < 8) return { ok: false, message: "Use at least 8 characters." };
  if (password !== confirm) return { ok: false, message: "The two passwords don't match." };

  try {
    await resetPassword(token, password);
  } catch (err) {
    if (err instanceof AuthError && err.status < 500) {
      return { ok: false, message: "This link is invalid or has expired. Please request a new one." };
    }
    console.error("reset-password", err);
    return { ok: false, message: "Something went wrong. Please try again." };
  }
  // redirect() throws, so call it outside try/catch.
  redirect("/sign-in?reset=1");
}

export async function signUpAction(_prev: FormState, form: FormData): Promise<FormState> {
  const name = String(form.get("name") ?? "").trim();
  const email = String(form.get("email") ?? "").trim().toLowerCase();
  const password = String(form.get("password") ?? "");

  if (!name || !isEmail(email) || password.length < 8) {
    return { ok: false, message: "Enter your name, a valid email and a password of at least 8 characters." };
  }

  try {
    await signUp(name, email, password);
  } catch (err) {
    return { ok: false, message: err instanceof AuthError && err.status < 500 ? err.message : "Sign-up failed. Please try again." };
  }

  // With "Require a verified email" on, the user is not signed in yet.
  // Remember the address for the check-your-email page, without putting it in the URL.
  (await cookies()).set("pending_email", email, { httpOnly: true, sameSite: "lax", path: "/", maxAge: 60 * 60 });
  redirect("/check-email");
}

export async function signInAction(_prev: FormState, form: FormData): Promise<FormState> {
  const email = String(form.get("email") ?? "").trim().toLowerCase();
  const password = String(form.get("password") ?? "");

  try {
    const { token } = await signIn(email, password);
    await setSession(token);
  } catch (err) {
    if (err instanceof AuthError && err.status === 403) {
      return { ok: false, unverified: true, email, message: "Please verify your email first. Check your inbox for the link." };
    }
    if (err instanceof AuthError && err.status < 500) {
      return { ok: false, message: "Wrong email or password." };
    }
    console.error("sign-in", err);
    return { ok: false, message: "Sign-in is unavailable right now. Please try again." };
  }
  redirect("/dashboard");
}

export async function resendVerification(_prev: FormState, form: FormData): Promise<FormState> {
  const email = String(form.get("email") ?? "").trim().toLowerCase();
  if (!isEmail(email)) return { ok: false, message: "Please enter a valid email." };

  try {
    await sendVerificationEmail(email);
  } catch (err) {
    console.error("send-verification-email", err);
  }
  return { ok: true, email, message: "If that account still needs verifying, a new link is on its way." };
}
```

*app/forgot-password/page.tsx*

```tsx
"use client";

import { useActionState } from "react";
import { forgotPassword } from "@/app/actions/auth";

export default function ForgotPasswordPage() {
  const [state, action, pending] = useActionState(forgotPassword, null);

  if (state?.ok) {
    return <p role="status" className="mx-auto max-w-sm p-8">{state.message}</p>;
  }

  return (
    <form action={action} className="mx-auto grid max-w-sm gap-3 p-8">
      <h1>Forgot your password?</h1>
      <p>Enter your email and we'll send you a link to choose a new one.</p>
      <input name="email" type="email" autoComplete="email" placeholder="you@example.com" required />
      <button disabled={pending}>{pending ? "Sending…" : "Send reset link"}</button>
      {state && <p role="alert" style={{ color: "crimson" }}>{state.message}</p>}
    </form>
  );
}
```

> **Warning:** A public form that sends email is a target for bots. Add a per-IP limit with Redis, as in [Rate Limit Next.js with Redis](https://cloudhike.dev/guides/rate-limit-nextjs-redis), to the forgot password, sign-up and resend actions.

## Step 4: Build the reset password page

The email links to the `redirectTo` you passed, with a `token` in the query. In Next.js 16, `searchParams` is a Promise, so the page awaits it and hands the token to the form.

*app/reset-password/page.tsx*

```tsx
import type { Metadata } from "next";
import Link from "next/link";
import { ResetForm } from "./reset-form";

// Don't leak the token in the Referer header if the page links elsewhere.
export const metadata: Metadata = { title: "Choose a new password", referrer: "no-referrer" };

export default async function ResetPasswordPage({ searchParams }: { searchParams: Promise<{ token?: string | string[] }> }) {
  const { token } = await searchParams;
  const value = Array.isArray(token) ? token[0] : token;

  if (!value) {
    return (
      <p className="mx-auto max-w-sm p-8">
        This link is incomplete. <Link href="/forgot-password">Request a new reset link</Link>.
      </p>
    );
  }
  return <ResetForm token={value} />;
}
```

*app/reset-password/reset-form.tsx*

```tsx
"use client";

import Link from "next/link";
import { useActionState } from "react";
import { chooseNewPassword } from "@/app/actions/auth";

export function ResetForm({ token }: { token: string }) {
  const [state, action, pending] = useActionState(chooseNewPassword, null);

  return (
    <form action={action} className="mx-auto grid max-w-sm gap-3 p-8">
      <h1>Choose a new password</h1>
      <input type="hidden" name="token" value={token} />
      <input name="password" type="password" autoComplete="new-password" placeholder="New password" minLength={8} required />
      <input name="confirm" type="password" autoComplete="new-password" placeholder="Repeat it" minLength={8} required />
      <button disabled={pending}>{pending ? "Saving…" : "Save new password"}</button>
      {state && !state.ok && (
        <p role="alert" style={{ color: "crimson" }}>
          {state.message} <Link href="/forgot-password">Get a new link</Link>
        </p>
      )}
    </form>
  );
}
```

On success the action redirects to `/sign-in?reset=1`, where the user signs in with the new password. If the token is no longer valid, for example because the link was already used or sat in an inbox too long, the user sees the error with a way to get a fresh link.

## Step 5: Require a verified email

With **Require a verified email** on, sign-up sends a verification link automatically. The user is not signed in until they open it, so the sign-up action sends them to a check-your-email page instead of the dashboard.

*app/check-email/page.tsx*

```tsx
import { cookies } from "next/headers";
import { ResendButton } from "./resend-button";

export default async function CheckEmailPage() {
  const email = (await cookies()).get("pending_email")?.value;

  return (
    <main className="mx-auto grid max-w-sm gap-3 p-8">
      <h1>Check your email</h1>
      <p>
        We sent a link to {email ?? "your inbox"}. Open it to verify your address, then sign in.
      </p>
      {email && <ResendButton email={email} />}
    </main>
  );
}
```

*app/check-email/resend-button.tsx*

```tsx
"use client";

import { useActionState } from "react";
import { resendVerification } from "@/app/actions/auth";

export function ResendButton({ email }: { email: string }) {
  const [state, action, pending] = useActionState(resendVerification, null);

  return (
    <form action={action}>
      <input type="hidden" name="email" value={email} />
      <button disabled={pending || state?.ok}>{pending ? "Sending…" : "Resend the link"}</button>
      {state && <p role="status">{state.message}</p>}
    </form>
  );
}
```

People also come back days later and try to sign in before verifying. Auth answers `403` then, and the sign-in action returns `unverified: true`. The form shows the resend button right there:

*app/sign-in/sign-in-form.tsx*

```tsx
"use client";

import Link from "next/link";
import { useActionState } from "react";
import { signInAction } from "@/app/actions/auth";
import { ResendButton } from "@/app/check-email/resend-button";

export function SignInForm({ notice }: { notice?: string }) {
  const [state, action, pending] = useActionState(signInAction, null);

  return (
    <div className="mx-auto grid max-w-sm gap-3 p-8">
      {notice && <p role="status">{notice}</p>}
      <form action={action} className="grid gap-3">
        <input name="email" type="email" autoComplete="email" placeholder="you@example.com" required />
        <input name="password" type="password" autoComplete="current-password" placeholder="Password" required />
        <button disabled={pending}>{pending ? "Signing in…" : "Sign in"}</button>
        <Link href="/forgot-password">Forgot your password?</Link>
      </form>
      {state && !state.ok && <p role="alert" style={{ color: "crimson" }}>{state.message}</p>}
      {state?.unverified && state.email && <ResendButton email={state.email} />}
    </div>
  );
}
```

*app/sign-in/page.tsx*

```tsx
import { SignInForm } from "./sign-in-form";

export default async function SignInPage({ searchParams }: { searchParams: Promise<{ reset?: string; verified?: string }> }) {
  const { reset, verified } = await searchParams;
  const notice = reset
    ? "Your password was changed. Sign in with the new one."
    : verified
      ? "Your email is verified. You can sign in now."
      : undefined;
  return <SignInForm notice={notice} />;
}
```

The resend call uses `callbackURL`, so that link returns the user to `/sign-in?verified=1`. The first link, sent at sign-up, returns them to your site as well.

## Step 6: Customize the reset and verification emails

Open **Auth** and go to the **Emails** tab. You don't write HTML for these emails. You change what Auth sends:

- **Sender name**, so the inbox shows your product's name.
- **From address** on a domain you verified under [Email → Domains](https://cloudhike.dev/docs/email#domains). Until then, emails come from CloudHike.dev's sender.
- **Reply-to address**, so a confused user who hits Reply reaches your support inbox.
- **Wording** of the verification and password reset emails, with a live preview and a test send.

Keep the wording plain. Say what the link does, that it expires, and that the user can ignore the email if they didn't ask for it. Send yourself a test and click the link from a phone to be sure it opens your site.

## Production checklist

- Add your production address to the sites users may return to, and set `APP_URL` to it on your host.
- Rate limit the forgot password, sign-up and resend actions per IP with [Redis](https://cloudhike.dev/guides/rate-limit-nextjs-redis).
- Keep the same answer for known and unknown emails on the forgot password form.
- Don't log full URLs on `/reset-password`. They contain the token.
- Send from your own verified domain and set a reply-to address on the Auth Emails tab.
- Protect signed-in pages by checking the session cookie, as in [Protect Routes in Next.js with proxy.ts](https://cloudhike.dev/guides/protect-routes-nextjs-proxy).
- Auth is billed per monthly active user. See the [pricing page](https://cloudhike.dev/pricing) for current numbers.

## FAQ

### How do I add a forgot password feature in Next.js?

Build a form that posts the email to a Server Action. The action asks your auth provider to send a reset link and always shows the same message. The link opens a page in your app that reads the token from the query string and lets the user choose a new password.

### Should the forgot password form say when an email isn't registered?

No. If the answer differs, anyone can check whether a person has an account. Show the same message, such as "If an account exists, we sent a link", in both cases.

### How long is a password reset link valid?

Your auth provider sets the exact lifetime, so treat reset links as short-lived and single-use. When the reset call fails for an old or used link, show a clear error and a link back to the forgot password page so the user can get a new one.

### What happens if a user signs in before verifying their email?

With Require a verified email turned on, CloudHike Auth refuses the sign-in with a 403 status. Catch that status in your sign-in action and offer to resend the verification link.

### Do I need SMTP to send password reset emails in Next.js?

Not with CloudHike Auth. Auth sends the verification and reset emails itself. You only choose the sender name, reply-to address and wording on the Auth Emails tab, and optionally a verified domain to send from.
