Remix 集成

Better Auth可以轻松地与Remix集成。本文将向你展示如何将Better Auth与Remix集成。

你可以按照安装指南中的步骤开始,或者按照本指南以Remix的方式进行操作。

如果你已经按照安装步骤操作,可以跳过第一步。

创建认证实例

创建一个名为 auth.server.ts 的文件,放在以下位置之一:

  • 项目根目录
  • lib/ 文件夹
  • utils/ 文件夹

你也可以将这些文件夹嵌套在 app/ 文件夹下。(例如 app/lib/auth.server.ts

在此文件中,导入 Better Auth 并创建你的实例。

确保使用变量名 auth 导出认证实例,或者将其作为 default 导出。

app/lib/auth.server.ts
import { betterAuth } from "better-auth"
 
export const auth = betterAuth({
    database: {
        provider: "postgres", //更改为你的数据库提供商
        url: process.env.DATABASE_URL, // 你的数据库路径或连接字符串
    }
})

创建 API 路由

我们需要将处理程序挂载到 API 路由。在 app/routes/ 目录中创建一个资源路由文件 api.auth.$.ts。并添加以下代码:

app/routes/api.auth.$.ts
import { auth } from '~/lib/auth.server' // 根据需要调整路径
import type { LoaderFunctionArgs, ActionFunctionArgs } from "@remix-run/node"
 
export async function loader({ request }: LoaderFunctionArgs) {
    return auth.handler(request)
}
 
export async function action({ request }: ActionFunctionArgs) {
    return auth.handler(request)
}

你可以在 better-auth 配置中更改路径,但建议保持为 routes/api.auth.$.ts

创建客户端

创建一个客户端实例。这里我们在 lib/ 目录下创建 auth-client.ts 文件。

app/lib/auth-client.ts
import { createAuthClient } from "better-auth/react" // 确保从 better-auth/react 导入
 
export const authClient = createAuthClient({
    //你可以在这里传递客户端配置
})

一旦你创建了客户端,你就可以使用它来注册、登录和执行其他操作。

使用示例

注册

app/routes/signup.tsx
import { Form } from "@remix-run/react"
import { useState } from "react"
import { authClient } from "~/lib/auth.client"
 
export default function SignUp() {
  const [email, setEmail] = useState("")
  const [name, setName] = useState("")
  const [password, setPassword] = useState("")
 
  const signUp = async () => {
    await authClient.signUp.email(
      {
        email,
        password,
        name,
      },
      {
        onRequest: (ctx) => {
          // 显示加载状态
        },
        onSuccess: (ctx) => {
          // 重定向到首页
        },
        onError: (ctx) => {
          alert(ctx.error)
        },
      },
    )
  }
 
  return (
    <div>
      <h2>
        注册
      </h2>
      <Form
        onSubmit={signUp}
      >
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="姓名"
        />
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="邮箱"
        />
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="密码"
        />
        <button
          type="submit"
        >
          注册
        </button>
      </Form>
    </div>
  )
}

登录

app/routes/signin.tsx
import { Form } from "@remix-run/react"
import { useState } from "react"
import { authClient } from "~/services/auth.client"
 
export default function SignIn() {
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
 
  const signIn = async () => {
    await authClient.signIn.email(
      {
        email,
        password,
      },
      {
        onRequest: (ctx) => {
          // 显示加载状态
        },
        onSuccess: (ctx) => {
          // 重定向到首页
        },
        onError: (ctx) => {
          alert(ctx.error)
        },
      },
    )
  }
 
  return (
    <div>
      <h2>
        登录
      </h2>
      <Form onSubmit={signIn}>
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <button
          type="submit"
        >
          登录
        </button>
      </Form>
    </div>
  )
}

On this page