TanStack Start Integration
This integration guide is assuming you are using TanStack Start.
Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the installation.
Mount the handler
We need to mount the handler to a TanStack API endpoint/Server Route.
Create a new file: /src/routes/api/auth/$.ts
import { auth } from '@/lib/auth'
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/api/auth/$')({
server: {
handlers: {
GET: ({ request }) => {
return auth.handler(request)
},
POST: ({ request }) => {
return auth.handler(request)
},
},
},
})Usage tips
- We recommend using the client SDK or
authClientto handle authentication, rather than server actions withauth.api. - When you call functions that need to set cookies (like
signInEmailorsignUpEmail), you'll need to handle cookie setting for TanStack Start. Better Auth provides atanstackStartCookiesplugin to automatically handle this for you.
import { betterAuth } from "better-auth";
import { tanstackStartCookies } from "better-auth/tanstack-start";
export const auth = betterAuth({
//...your config
plugins: [tanstackStartCookies()] // make sure this is the last plugin in the array
})Now, when you call functions that set cookies, they will be automatically set using TanStack Start's cookie handling system.
import { auth } from "@/lib/auth"
const signIn = async () => {
await auth.api.signInEmail({
body: {
email: "user@email.com",
password: "password",
}
})
}Middleware
You can use TanStack Start's middleware to protect routes that require authentication. Create a middleware that checks for a valid session and redirects unauthenticated users to the login page.
import { redirect } from "@tanstack/react-router";
import { createMiddleware } from "@tanstack/react-start";
import { auth } from "./auth";
export const authMiddleware = createMiddleware().server(
async ({ next, request }) => {
const session = await auth.api.getSession({ headers: request.headers })
if (!session) {
throw redirect({ to: "/login" })
}
return await next()
}
);You can then use this middleware in your route definitions to protect specific routes:
import { createFileRoute } from '@tanstack/react-router'
import { authMiddleware } from '@/lib/middleware'
export const Route = createFileRoute('/dashboard')({
component: RouteComponent,
server: {
middleware: [authMiddleware],
},
})
function RouteComponent() {
return <div>Hello "/dashboard"!</div>
}