TanStack 启动集成

本集成指南假设你正在使用 TanStack Start。

【This integration guide is assuming you are using TanStack Start.】

在开始之前,请确保你已配置了 Better Auth 实例。如果还没有配置,请查看安装指南

【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】

我们需要将处理程序挂载到 TanStack API 端点/服务器路由。创建一个新文件:/src/routes/api/auth/$.ts

【We need to mount the handler to a TanStack API endpoint/Server Route. Create a new file: /src/routes/api/auth/$.ts

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: async ({ request }:{ request: Request }) => {
                return await auth.handler(request)
            },
            POST: async ({ request }:{ request: Request }) => {
                return await auth.handler(request)
            },
        },
    },
})

使用提示

【Usage tips】

  • 我们建议使用客户端 SDK 或 authClient 来处理身份验证,而不是使用 auth.api 的服务器操作。
  • 当你调用需要设置 Cookie 的函数(例如 signInEmailsignUpEmail)时,你需要处理 TanStack Start 的 Cookie 设置。Better Auth 提供了一个 tanstackStartCookies 插件,可以自动为你处理这些操作。

适用于 React(TanStack 从 React 开始):

【For React (TanStack Start with React):】

src/lib/auth.ts
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
})

针对 Solid.js(TanStack 从 Solid 开始):

【For Solid.js (TanStack Start with Solid):】

src/lib/auth.ts
import { betterAuth } from "better-auth";
import { tanstackStartCookies } from "better-auth/tanstack-start/solid";

export const auth = betterAuth({
    //...your config
    plugins: [tanstackStartCookies()] // make sure this is the last plugin in the array
})

现在,当你调用设置 cookies 的函数时,它们将会自动使用 TanStack Start 的 cookie 处理系统来设置。

【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】

你可以使用 TanStack Start 的中间件来保护需要身份验证的路由。创建一个中间件来检查有效的会话,并将未认证的用户重定向到登录页面。

【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.】

src/middleware/auth.ts
import { redirect } from "@tanstack/react-router";
import { createMiddleware } from "@tanstack/react-start";
import { getRequestHeaders } from "@tanstack/react-start/server";
import { auth } from "@/lib/auth";

export const authMiddleware = createMiddleware().server(
    async ({ next, request }) => {
        const headers = getRequestHeaders();
        const session = await auth.api.getSession({ headers })

        if (!session) {
            throw redirect({ to: "/login" })
        }

        return await next()
    }
);

然后你可以在路由定义中使用这个中间件来保护特定的路由:

【You can then use this middleware in your route definitions to protect specific routes:】

src/routes/dashboard.tsx
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>
}

On this page