# Authentication (/docs/starter/modules/auth)

Choose with `--auth supabase` (default), `--auth better-auth`, `--auth firebase`, `--auth appwrite`, or `--auth none`. Firebase and Appwrite need Starter v0.21.0 or newer.

With Next.js and TanStack Start, every provider gives you server-verified sessions in secure cookies, a protected dashboard, rate-limited sign-in, and an account settings page with display name, password change, and account deletion. Password reset by email comes with Supabase Auth and Appwrite, and with Better Auth and Firebase when the project has an [email module](./email.mdx). Pages and forms never touch the provider SDK: they go through the `AuthProvider` interface in `packages/auth`.

A React + Vite frontend with an API works differently: see [A frontend and its API](#a-frontend-and-its-api).

Until the provider is configured, the dashboard stays viewable as a demo and the login page explains what is missing. Once it is configured, the dashboard redirects signed-out visitors to the login page.

<Tabs items={['Supabase Auth', 'Better Auth', 'Firebase', 'Appwrite']} groupId="auth" persist>
  <Tab value="Supabase Auth">
    Create or select a Supabase project and copy its URL and publishable key from the project's API settings into the Supabase variables:

    | Next.js | TanStack Start |
    | --- | --- |
    | `NEXT_PUBLIC_SUPABASE_URL` | `SUPABASE_URL` |
    | `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY` | `SUPABASE_PUBLISHABLE_KEY` |

    Authentication runs on the server, which validates every user with Supabase, and the publishable key is all sign-in needs. To let users delete their account from the settings page, also set `SUPABASE_SECRET_KEY` to a secret key from the same settings. It stays on the server, so never give it a `NEXT_PUBLIC_` prefix.

    ### Redirect URLs [#redirect-urls]

    In Supabase Auth URL configuration, add this redirect URL for local email confirmation and password reset links:

    ```text
    http://localhost:3000/auth/callback**
    ```

    For deployed environments, add your deployed origin followed by `/auth/callback**`. The `**` lets links carry the page to open next, such as `/reset-password`.

    ### Supabase emails [#supabase-emails]

    Supabase sends the confirmation and password reset emails itself. Configure its SMTP settings in the Supabase project to send them from your own domain.
  </Tab>
  <Tab value="Better Auth">
    Better Auth keeps users, passwords, and sessions in your PostgreSQL database, in its own `auth_*` tables with a separate migration history (`packages/auth-better-auth/drizzle`). Set `DATABASE_URL` and apply the migrations (see [Database](../database.mdx)), then set a secret of at least 32 random characters:

    ```sh
    openssl rand -base64 32
    ```

    Put the result in `BETTER_AUTH_SECRET`:

    ```dotenv title="apps/web/.env.local"
    BETTER_AUTH_SECRET=<the output of openssl rand -base64 32>
    ```

    Signing in again on another device creates another session row, and signing out deletes it.

    ### Better Auth emails [#better-auth-emails]

    With an [email module](./email.mdx), Better Auth sends its emails through it:

    - **Password reset:** "Forgot password?" on the login page emails a link to `/reset-password`, valid for one hour and usable once.
    - **Email verification:** every new account gets a confirmation link. Sign-up signs the user in right away unless `BETTER_AUTH_REQUIRE_EMAIL_VERIFICATION=true`, which refuses sign-in until the link is opened.

    With [background jobs](./jobs.mdx) too, these emails are sent by the `send-email` job, so sign-up never waits for the email provider, and a failed send is retried with backoff.

    Without an email module, sign-up signs the user in immediately; add email verification in `packages/auth-better-auth` if your application needs it.
  </Tab>
  <Tab value="Firebase">
    [Firebase Authentication](https://firebase.google.com/docs/auth) keeps the accounts. The app's own pages sign users in, and the server holds the session in an HTTP-only Firebase session cookie, checked for revocation on each request.

    In development, start the Auth Emulator (`firebase.json`, port 9099). The example environment points at it, so no Firebase project or account is needed:

    ```sh
    pnpm auth:dev
    ```

    In production:

    1. In the [Firebase console](https://console.firebase.google.com), create a project and turn on **Email/Password** under Authentication, Sign-in method.
    2. Set `FIREBASE_PROJECT_ID` and `FIREBASE_API_KEY`, the Web API key from Project settings, General.
    3. Under Project settings, Service accounts, generate a private key, and set `FIREBASE_CLIENT_EMAIL` and `FIREBASE_PRIVATE_KEY` from it.
    4. Remove `FIREBASE_AUTH_EMULATOR_HOST`; `pnpm check:env` refuses it in production.

    ### Firebase emails [#firebase-emails]

    Reset and confirmation links are generated by Firebase and sent through the app's [email module](./email.mdx), so they open the app's own `/reset-password` and `/auth/callback` with no setup in the Firebase console. Without an email module there is no password reset.
  </Tab>
  <Tab value="Appwrite">
    [Appwrite](https://appwrite.io) keeps the accounts, on Appwrite Cloud or your own server. The app's own pages sign users in, and the server holds the session's secret in an HTTP-only cookie.

    1. Create a project in [Appwrite Cloud](https://cloud.appwrite.io) (free tier) or on your server.
    2. Under Overview, Platforms, add a **Web** platform for the app's hostname: `localhost` in development, your domain in production. Appwrite only sends links to registered hostnames.
    3. Under Overview, Integrations, API keys, create a key with the `sessions.write` and `users.write` scopes.
    4. Set `APPWRITE_ENDPOINT` (such as `https://cloud.appwrite.io/v1`, or your region's), `APPWRITE_PROJECT_ID`, and `APPWRITE_API_KEY`. The key stays on the server.

    ### Appwrite emails [#appwrite-emails]

    Appwrite sends the confirmation and recovery emails itself, with links back to the app's `/auth/callback` and `/reset-password`. On your own server, set its SMTP settings (`_APP_SMTP_HOST` and the rest) to send them.
  </Tab>
</Tabs>

Changing or resetting a password signs out every other session, with every provider.

## A frontend and its API [#a-frontend-and-its-api]

On a [React + Vite frontend with Hono or FastAPI](../../cli/frontend-and-api.mdx) (Starter v0.24.0 or newer), the browser signs in with the provider, and the API checks the user on every request it serves. The frontend has the landing page, the dashboard, the sign-in and sign-up page (`/login`), `/forgot-password`, `/reset-password`, and the account settings page (`/settings`, Starter v0.25.0 or newer). The dashboard reads the user from the API's `/api/session`, and once the provider is configured it redirects signed-out visitors to `/login`.

The frontend's settings are public `VITE_*` variables in `apps/web/.env.local`, and the API's are in `apps/api/.env.local`. Vite compiles the `VITE_*` values into the build, so in production set them where the frontend is built: as Docker build arguments, or on Railway as the frontend service's variables.

<Tabs items={['Supabase Auth', 'Better Auth', 'Firebase', 'Appwrite']} groupId="auth" persist>
  <Tab value="Supabase Auth">
    | Frontend | API |
    | --- | --- |
    | `VITE_SUPABASE_URL` | `SUPABASE_URL` |
    | `VITE_SUPABASE_PUBLISHABLE_KEY` | `SUPABASE_PUBLISHABLE_KEY` |

    The browser keeps the Supabase session and sends its access token to the API as a bearer token. The API asks Supabase Auth for the token's user on each request. Sign-in needs no secret key. To let users delete their account from the settings page, set `SUPABASE_SECRET_KEY` in `apps/api/.env.local`; only the API uses it.

    Sign-up confirmation links open `/login` and password reset links open `/reset-password`, so add both to Supabase Auth's redirect URLs, locally and for your deployed origin:

    ```text
    http://localhost:3000/login**
    http://localhost:3000/reset-password**
    ```
  </Tab>
  <Tab value="Better Auth">
    Better Auth runs in the frontend's own Node server (`auth.server.mjs`), which answers `/api/auth/*`, and keeps the session in an HTTP-only cookie on the frontend's origin. `pnpm dev` starts it on port 3002 once `DATABASE_URL` and `BETTER_AUTH_SECRET` are set, and the dev server forwards `/api/auth` to it; in production, `node server.mjs` serves it.

    | Frontend | API |
    | --- | --- |
    | `DATABASE_URL` | `BETTER_AUTH_URL` |
    | `BETTER_AUTH_SECRET`, at least 32 random characters | |
    | `BETTER_AUTH_URL`, the frontend's public origin | |

    The browser calls the API through the frontend's `/api`, so the cookie goes with each request: leave `VITE_API_URL` blank. The API checks the session by passing the cookie to `BETTER_AUTH_URL/api/auth/get-session`. Apply the `auth_*` migrations with `pnpm db:migrate`.

    With an [email module](./email.mdx#a-frontend-and-its-api), Better Auth sends its emails with the same provider as the API, so the email variables go in both env files. Without one, it sends them through Resend when `RESEND_API_KEY` and `EMAIL_FROM` are in the frontend's environment. Either way, Better Auth sends password reset links to `/reset-password`, valid for one hour, and a confirmation link on sign-up; `BETTER_AUTH_REQUIRE_EMAIL_VERIFICATION=true` then refuses sign-in until it is opened. With no email set up, sign-up signs the user in immediately and there is no password reset.
  </Tab>
  <Tab value="Firebase">
    | Frontend | API |
    | --- | --- |
    | `VITE_FIREBASE_API_KEY` | Hono: `FIREBASE_PROJECT_ID`, `FIREBASE_CLIENT_EMAIL`, `FIREBASE_PRIVATE_KEY` |
    | `VITE_FIREBASE_PROJECT_ID` | FastAPI: `FIREBASE_API_KEY` |
    | `VITE_FIREBASE_AUTH_DOMAIN` | |

    The browser signs in with Firebase's SDK and sends its ID token to the API as a bearer token. Hono verifies it with the Firebase Admin SDK, checking for revocation, with the service account from Project settings, Service accounts. FastAPI looks it up with Identity Toolkit's `accounts:lookup`, using the Web API key. To let users delete their account with the Hono API, also set `FIREBASE_API_KEY` on the API, which checks the password with it. FastAPI checks the password and deletes the user with the same Web API key, so it needs no service account.

    Firebase sends the confirmation and password reset emails itself; its own page completes a reset, then returns to `/login`. Sign-up sends a confirmation email and signs the user out, and both the frontend and the API refuse an address that isn't verified yet. Add your domain under Authentication, Settings, Authorized domains, so Firebase accepts links back to it.

    In development, `pnpm auth:dev` starts the Auth Emulator on port 9099. Point both apps at it: `VITE_FIREBASE_AUTH_EMULATOR_URL=http://127.0.0.1:9099` for the frontend and `FIREBASE_AUTH_EMULATOR_HOST=127.0.0.1:9099` for the API, with the project id `demo-clubedge` and any API key. Remove both in production.
  </Tab>
  <Tab value="Appwrite">
    | Frontend | API |
    | --- | --- |
    | `VITE_APPWRITE_ENDPOINT` | `APPWRITE_ENDPOINT` |
    | `VITE_APPWRITE_PROJECT_ID` | `APPWRITE_PROJECT_ID` |

    The browser signs in with Appwrite's Web SDK and, for each API request, creates a short-lived JWT and sends it as a bearer token. The API checks it by reading `/account` from Appwrite with the `X-Appwrite-JWT` header. Sign-in needs no API key. To let users delete their account, set `APPWRITE_API_KEY` on the API, a key with the `sessions.write` and `users.write` scopes.

    Add a **Web** platform for the frontend's hostname, as above. Appwrite sends the confirmation and recovery emails itself, with links back to `/login` and `/reset-password`. Sign-up sends a confirmation email and signs the user out, and both the frontend and the API refuse an address that isn't verified yet.
  </Tab>
</Tabs>

### In the mobile app [#in-the-mobile-app]

A [mobile app](../mobile-app.mdx) (Starter v0.27.0 or newer) keeps its session on the device and sends it with each call, since the website's cookies never reach it. With Better Auth, it signs in with bearer tokens, which the API checks as it checks the cookie; with Appwrite, add a **Web** platform for the hostname `localhost` too. Emailed links open the website. See [Sign-in](../mobile-app.mdx#sign-in) for each provider.

### In the native app [#in-the-native-app]

The [native app](../native-app.mdx) (Starter v0.28.0 or newer) signs in with Supabase Auth or Better Auth, or has no sign-in: the CLI refuses Firebase and Appwrite with `--mobile expo`. It keeps its session on the device. Better Auth's Expo plugin keeps the session cookie in the device's secure storage, and the server trusts the app's address scheme; Supabase keeps its session in the app's storage, and the app sends the access token to the API. Emailed links open the website, or the app in a project without a website. See [Sign-in](../native-app.mdx#sign-in).

## Without a website [#without-a-website]

In a project [without a website](../../cli/without-a-website.mdx) (Starter v0.28.0 or newer), clients sign in and send the session or token with each request, and the API checks the user, with every provider. The settings go in `apps/api/.env.local`:

- **Better Auth** runs in the Hono API, at `/api/auth`, once `BETTER_AUTH_SECRET`, at least 32 random characters, is set; `pnpm check:env` refuses a shorter one. `BETTER_AUTH_URL` is the API's public URL. FastAPI can't run it, so the CLI refuses `--auth better-auth` with `--api fastapi` there.
- **Supabase Auth:** `SUPABASE_URL` and `SUPABASE_PUBLISHABLE_KEY`, and `SUPABASE_SECRET_KEY` for account deletion. For emailed links to open the native app, add its address scheme to the Redirect URLs, such as `my-product://**`.
- **Firebase and Appwrite:** clients send Firebase's ID token, or a JWT from Appwrite, as a bearer token, and the API accepts only confirmed addresses. The native app doesn't sign in with either.

The API keeps the account endpoints, the display name and account deletion, as with a frontend; passwords change with the provider. See [Sign-in](../../cli/without-a-website.mdx#sign-in).

### The settings page [#the-settings-page]

With either API, the settings page has the display name, the password change, and account deletion, as on Next.js and TanStack Start (with FastAPI, Starter v0.26.0 or newer). The password change goes to the provider, in the browser or in Better Auth's server, which signs out the user's other sessions. The display name and account deletion go through the API, which keeps the app's data: deletion checks the password (10 tries a minute per user), removes the user's app data, then deletes the user from the provider. With an active [subscription](./payments.mdx#a-frontend-and-its-api), it refuses until the user cancels it.

## Another provider [#another-provider]

Pages and forms depend on the `AuthProvider` interface in `packages/auth`, so another provider is a new package that implements it and a variant of `src/server/auth.ts`. Prove it with the conformance suite every provider runs, which covers sign-up and sign-in, one answer for a wrong password and an unknown address, sign-out, password reset through the emailed link, password changes, and account deletion:

```ts title="packages/auth-my-provider/src/conformance.test.ts"
import { describeAuthProvider } from "@clubedge/auth/conformance";
import { createMyAuth } from "./index";

describeAuthProvider("my-provider", () => ({
  browser: () => createMyAuth({ cookies: cookieJar() }),
  // The token from the latest reset email to this address, as a person clicking it would get.
  openResetLink: async (email) => readResetToken(email),
}));
```

Provider user ids are stored as text in `users.auth_user_id` (Starter v0.21.0 or newer), so they need not be UUIDs.

On a frontend and its API, a provider is two variants instead: a browser client implementing `AuthClient` (`apps/web/src/lib/auth-client.ts`), and the API's check: `getCurrentUser`, `canDeleteAccount`, and `deleteAccount` in `apps/api/src/server/auth.ts` with Hono, or `get_current_user`, `can_delete_account`, and `delete_account` in `apps/api/src/clubedge_api/auth.py` with FastAPI.

## Protect routes and pages [#protect-routes-and-pages]

Make authenticated server routes call `getCurrentUser()` or `requireUser()` from `@/server/auth` (the latter throws a 401 `AppError`), and protect pages with `getPageUser`, which redirects signed-out visitors to `/login`. Do not treat cookie contents alone as proof of identity.

On a frontend and its API, and without a website, the API protects the data. Its routes get the user from the dependencies the composition root passes them, as `/api/session` does: `dependencies.getCurrentUser(request)` with Hono, `dependencies.get_current_user(request)` with FastAPI. It returns `null` (`None`) for a signed-out request, so answer 401 then. The provider's check is in `apps/api/src/server/auth.ts` or `apps/api/src/clubedge_api/auth.py`. The frontend's redirect to `/login` is a convenience, not a check.

## Framework differences [#framework-differences]

| Concern               | Next.js                    | TanStack Start                                                  |
| --------------------- | -------------------------- | --------------------------------------------------------------- |
| Sign-in and sign-up   | Server actions             | Form posts to `/auth/sign-in` and `/auth/sign-up` server routes |
| Session refresh       | `src/proxy.ts`, with Supabase Auth and Better Auth | Request middleware in `src/start.ts`, with every provider |
| Cross-site protection | Built into server actions  | `createCsrfMiddleware` in `src/start.ts`                        |
