For a long time, my go-to stack for building authentication in React was Next.js with NextAuth and Prisma (I even wrote a tutorial about it). But the React ecosystem has changed a lot since then. TanStack Start has reached its stable 1.0 release, giving us a full-stack React framework with type-safe routing, server functions, and middleware, all built on top of Vite.
On the authentication side, Better Auth has become one of the most popular open-source options for TypeScript projects. It's framework-agnostic, it stores your users in your own database, and it comes with a dedicated integration for TanStack Start. For the database layer, we will use Drizzle ORM, a lightweight TypeScript ORM where our schema is plain TypeScript code and our queries look very close to SQL. Together, they give us a fully type-safe authentication system from the database all the way to our React components.
In this tutorial, we will learn how to build a simple email and password authentication system by using TanStack Start, Better Auth, Drizzle ORM, and PostgreSQL. We will also learn how to protect our routes and server functions so that only signed-in users can access them.
Project Setup
Let's start by creating our TanStack Start project with the TanStack CLI:
npx @tanstack/cli@latest createThe CLI will ask us for a project name, our package manager, and some optional add-ons like Tailwind CSS. For this tutorial, we won't select any add-ons since we will configure everything manually (the CLI also offers Better Auth and Drizzle add-ons, but building it ourselves will help us understand how every piece fits together).
Once the project is created, we can run npm run dev and open http://localhost:3000 to check that everything is working. The generated project also configures the @/* path alias inside our tsconfig.json file, which points to our src folder:
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}We will use this alias throughout the tutorial to import our files (e.g. @/lib/auth).
Install and Configure Drizzle
Drizzle is an open-source TypeScript ORM (Object Relational Mapper). Instead of a separate schema language, we define our tables with TypeScript functions, and Drizzle infers all of our types from them.
For this tutorial, we will use Drizzle 1.0, which is currently in its release candidate (RC) phase. Drizzle 1.0 comes with a new way of defining relations between tables (Relations v2) and a new migrations folder structure, and it's the version that Drizzle's documentation now uses in its getting started guides. Since it isn't the default latest version on npm yet, we will install it with the @rc tag. We will also use the node-postgres driver, which is the one used in Drizzle's PostgreSQL guide:
npm install drizzle-orm@rc pg
npm install -D drizzle-kit@rc @types/pg dotenvLet's go through each package:
drizzle-ormis the ORM we will use to query our database.pg(also known asnode-postgres) is the PostgreSQL driver that Drizzle uses to connect to our database.drizzle-kitis the Drizzle CLI that we will use to generate and apply our database migrations. Its version should always match the version ofdrizzle-orm.@types/pgcontains the TypeScript definitions for thepgpackage.dotenvloads our environment variables into the Drizzle config file.
Next, let's add our PostgreSQL connection string to a new .env file in the root of our project. If you don't have a database yet, you can follow Drizzle's guide to run PostgreSQL with Docker, or use any hosted provider like Neon or Supabase:
DATABASE_URL="postgresql://username:password@localhost:5432/mydb"Now, let's create our database connection inside a new file called src/db/index.ts:
import { drizzle } from 'drizzle-orm/node-postgres';
export const db = drizzle(process.env.DATABASE_URL!);The drizzle function receives our connection string, creates a node-postgres connection pool for us, and returns our db instance, which we export so we can reuse it across our whole application. TanStack Start automatically loads our .env file, so process.env.DATABASE_URL is available on the server.
Finally, we need a config file for Drizzle Kit. Let's create a new file called drizzle.config.ts in the root of our project:
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
out: './drizzle',
schema: './src/db/schema.ts',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});Let's go through each field:
outis the folder where Drizzle Kit will save our migrations.schemais the path to the file that contains our table definitions. We haven't created it yet; the Better Auth CLI will generate it for us in the next section.dialectis the type of database we are using.dbCredentialscontains the connection URL that Drizzle Kit uses to apply our migrations.
Setup Authentication with Better Auth
Now that our database connection is ready, let's install Better Auth and its Drizzle adapter:
npm install better-auth @better-auth/drizzle-adapterBetter Auth needs two environment variables to work. The first one is BETTER_AUTH_SECRET, which is used for encryption and hashing. It must be at least 32 characters long, and we can generate one with the command openssl rand -base64 32. The second one is BETTER_AUTH_URL, which is the base URL of our application. Let's add both to our .env file:
DATABASE_URL="postgresql://username:password@localhost:5432/mydb"
BETTER_AUTH_SECRET="your-generated-secret"
BETTER_AUTH_URL="http://localhost:3000"Next, let's create our Better Auth instance inside a new file called src/lib/auth.ts:
import { betterAuth } from 'better-auth';
import { drizzleAdapter } from '@better-auth/drizzle-adapter/relations-v2';
import { tanstackStartCookies } from 'better-auth/tanstack-start';
import { db } from '@/db';
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: 'pg',
}),
emailAndPassword: {
enabled: true,
},
plugins: [tanstackStartCookies()],
});Let's go through each field of our configuration:
databaseconnects Better Auth to our database. We usedrizzleAdapter, which receives our Drizzle instance and theproviderof our database (pgfor PostgreSQL). Notice that we import it from@better-auth/drizzle-adapter/relations-v2, which is the version of the adapter built for the Relations v2 API of Drizzle 1.0.emailAndPasswordenables the email and password authentication method. Better Auth also supports social providers like GitHub and Google through thesocialProvidersfield, and many more methods through plugins.pluginsis a list of Better Auth plugins. Here, we addtanstackStartCookies, which makes sure that cookies are set correctly through TanStack Start when we call Better Auth functions that set cookies on the server. This plugin should always be the last one in the array.
Better Auth needs a few tables to store its data: user, session, account (which stores credentials like our hashed passwords), and verification. Instead of writing these tables by hand, we can use the Better Auth CLI to generate our Drizzle schema:
npx auth@latest generate --output src/db/schema.tsThe CLI finds our src/lib/auth.ts file, reads our configuration, and creates the src/db/schema.ts file with our four tables. Since we are using the Relations v2 adapter, the CLI also generates the relations between them with Drizzle's new defineRelationsPart helper. At the bottom of our schema file, we will find the following code:
export const authRelations = defineRelationsPart(
{ user, session, account, verification },
(r) => ({
user: {
sessions: r.many.session({
from: r.user.id,
to: r.session.userId,
}),
accounts: r.many.account({
from: r.user.id,
to: r.account.userId,
}),
},
session: {
user: r.one.user({
from: r.session.userId,
to: r.user.id,
}),
},
account: {
user: r.one.user({
from: r.account.userId,
to: r.user.id,
}),
},
}),
);Here, r.many defines a one-to-many relation (a user has many sessions and accounts), while r.one defines the opposite side (each session and account belongs to one user). The from and to fields define which columns connect both tables.
Now that we have our schema, let's pass these relations to our Drizzle instance so we can use them in our queries. We will update our src/db/index.ts file with the following code:
import { drizzle } from 'drizzle-orm/node-postgres';
import { authRelations } from './schema';
export const db = drizzle(process.env.DATABASE_URL!, {
relations: authRelations,
});We also need to pass our schema to the Drizzle adapter so Better Auth knows exactly which table to use for each of its models. Let's update our src/lib/auth.ts file:
import { betterAuth } from 'better-auth';
import { drizzleAdapter } from '@better-auth/drizzle-adapter/relations-v2';
import { tanstackStartCookies } from 'better-auth/tanstack-start';
import { db } from '@/db';
import * as schema from '@/db/schema';
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: 'pg',
schema,
}),
emailAndPassword: {
enabled: true,
},
plugins: [tanstackStartCookies()],
});The schema field maps each Better Auth model to our Drizzle tables. Since the CLI generated tables with the same names that Better Auth expects (user, session, account, and verification), we can pass the whole schema as it is.
Finally, let's create our migration with Drizzle Kit and apply it to our database:
npx drizzle-kit generate
npx drizzle-kit migrateThe first command compares our schema with our previous migrations and creates a new folder inside drizzle (e.g. drizzle/20261114203622_melted_blackheart) with a migration.sql file and a snapshot.json file. In Drizzle 1.0, every migration gets its own folder, which avoids Git conflicts when multiple people create migrations at the same time. The second command runs our SQL against the database and creates our four tables.
Mount the Auth Handler
Better Auth exposes all of its endpoints (sign up, sign in, sign out, get session, and more) under the /api/auth/* path. To handle these requests, we will create a server route in TanStack Start, which is a route file that defines raw HTTP handlers instead of a React component.
Let's create a new file called src/routes/api/auth/$.ts. The $ in the file name makes it a catch-all route, so it will match every path under /api/auth:
import { createFileRoute } from '@tanstack/react-router';
import { auth } from '@/lib/auth';
export const Route = createFileRoute('/api/auth/$')({
server: {
handlers: {
GET: async ({ request }) => {
return await auth.handler(request);
},
POST: async ({ request }) => {
return await auth.handler(request);
},
},
},
});Inside the server.handlers object, we define a handler for each HTTP method. Both of them receive the incoming request and pass it to auth.handler, which returns a standard Response object.
Add Client Functionality
To call Better Auth from our React components, we need to create an auth client. Let's create a new file called src/lib/auth-client.ts:
import { createAuthClient } from 'better-auth/react';
export const authClient = createAuthClient();Since our auth server runs on the same domain as our application, we don't need to pass a baseURL to createAuthClient. The client gives us methods like signUp.email, signIn.email, signOut, and the useSession hook.
Now, let's build our login page with a simple form that allows users to create an account or sign in. We will create a new file called src/routes/login.tsx:
import { useState } from 'react';
import { createFileRoute, useNavigate } from '@tanstack/react-router';
import { authClient } from '@/lib/auth-client';
export const Route = createFileRoute('/login')({
component: Login,
});
function Login() {
const navigate = useNavigate();
const [isSignUp, setIsSignUp] = useState(false);
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
setError(null);
const { error } = isSignUp
? await authClient.signUp.email({ name, email, password })
: await authClient.signIn.email({ email, password });
if (error) {
setError(error.message ?? 'Something went wrong');
return;
}
navigate({ to: '/dashboard' });
};
return (
<form onSubmit={handleSubmit}>
<h1>{isSignUp ? 'Create an account' : 'Sign in'}</h1>
{isSignUp && (
<input placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} />
)}
<input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
<input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
{error && <p>{error}</p>}
<button type="submit">{isSignUp ? 'Sign up' : 'Sign in'}</button>
<button type="button" onClick={() => setIsSignUp(!isSignUp)}>
{isSignUp ? 'Already have an account? Sign in' : "Don't have an account? Sign up"}
</button>
</form>
);
}When the form is submitted, we call authClient.signUp.email or authClient.signIn.email depending on the mode of our form. Both methods return a data and an error object. If something goes wrong (e.g. a wrong password), we display the error message. Otherwise, we redirect the user to the dashboard. By default, Better Auth signs users in automatically right after they sign up, and passwords must have at least 8 characters.
Protect Routes and Server Functions
Now that our users can sign in, let's protect the pages and data that only signed-in users should access. First, we will create a server function that reads the current session, plus a middleware that we can attach to any server function that needs an authenticated user. Let's create a new file called src/lib/auth.functions.ts:
import { createMiddleware, createServerFn } from '@tanstack/react-start';
import { getRequestHeaders } from '@tanstack/react-start/server';
import { auth } from '@/lib/auth';
export const getSession = createServerFn({ method: 'GET' }).handler(async () => {
const headers = getRequestHeaders();
return await auth.api.getSession({ headers });
});
export const authMiddleware = createMiddleware({ type: 'function' }).server(
async ({ next }) => {
const headers = getRequestHeaders();
const session = await auth.api.getSession({ headers });
if (!session) {
throw new Error('Unauthorized');
}
return next({ context: { session } });
},
);Let's go through each function:
getSessionis a server function created withcreateServerFn. It reads the headers of the incoming request withgetRequestHeaders(which include our session cookie) and passes them toauth.api.getSession. It returns the session and user, ornullif the user isn't signed in.authMiddlewareis a server function middleware. It also reads the session, but if there isn't one, it throws an error and stops the request. If the user is signed in, it callsnextwith the session inside thecontextobject, so every server function that uses this middleware has access to the current user.
To protect our pages, we will create a pathless layout route. Any route inside the _protected folder will go through this layout first. Let's create a new file called src/routes/_protected.tsx:
import { createFileRoute, Outlet, redirect } from '@tanstack/react-router';
import { getSession } from '@/lib/auth.functions';
export const Route = createFileRoute('/_protected')({
beforeLoad: async () => {
const session = await getSession();
if (!session) {
throw redirect({ to: '/login' });
}
return { user: session.user };
},
component: () => <Outlet />,
});The beforeLoad function runs before any child route loads, including client-side navigations with the <Link> component. If there isn't a session, we redirect the user to our login page. Otherwise, we return the user, which becomes part of the route context for all of the child routes.
Let's create a server function that returns the number of active sessions of the current user in a new file called src/lib/user.functions.ts:
import { createServerFn } from '@tanstack/react-start';
import { eq } from 'drizzle-orm';
import { authMiddleware } from '@/lib/auth.functions';
import { db } from '@/db';
import { session } from '@/db/schema';
export const getSessionCount = createServerFn({ method: 'GET' })
.middleware([authMiddleware])
.handler(async ({ context }) => {
return await db.$count(session, eq(session.userId, context.session.user.id));
});Here, we use Drizzle's $count helper with the eq operator to count the rows of our session table that belong to the current user. Thanks to our middleware, context.session is fully typed, and the handler will never run for a user who isn't signed in.
Finally, let's create our dashboard page inside a new file called src/routes/_protected/dashboard.tsx:
import { createFileRoute, useNavigate } from '@tanstack/react-router';
import { authClient } from '@/lib/auth-client';
import { getSessionCount } from '@/lib/user.functions';
export const Route = createFileRoute('/_protected/dashboard')({
loader: () => getSessionCount(),
component: Dashboard,
});
function Dashboard() {
const navigate = useNavigate();
const { user } = Route.useRouteContext();
const sessionCount = Route.useLoaderData();
const handleSignOut = async () => {
await authClient.signOut();
navigate({ to: '/login' });
};
return (
<div>
<h1>Welcome, {user.name}!</h1>
<p>You have {sessionCount} active session(s).</p>
<button onClick={handleSignOut}>Sign out</button>
</div>
);
}Even though the file lives inside the _protected folder, its URL is just /dashboard because pathless layouts (the ones starting with _) don't add a segment to the URL. We read the user from the route context with Route.useRouteContext, load the session count with our protected server function, and sign the user out with authClient.signOut.
If we now run npm run dev and go to http://localhost:3000/dashboard, we will be redirected to the login page. Once we create an account, we will land on our dashboard with our name and session count.
Conclusion
We have now completed our authentication system with TanStack Start, Better Auth, and Drizzle. Our users are stored in our own PostgreSQL database, our pages are protected with a pathless layout route, and our server functions are protected with a typed middleware. From here, you can add social providers like GitHub or Google, email verification, or Better Auth plugins like two-factor authentication and organizations, all without changing the structure we built in this tutorial.