Skip to main content

如何将 Prisma ORM 和 Prisma Postgres 与 Better Auth 和 Astro 结合使用

25 min

介绍

¥Introduction

Better Auth 是一款现代化的开源 Web 应用身份验证解决方案。它是一个使用 TypeScript 构建的生成器,提供简单且可扩展的身份验证体验,并支持多种数据库适配器,包括 Prisma。

¥Better Auth is a modern, open-source authentication solution for web apps. It's built with TypeScript and provides a simple and extensible auth experience with support for multiple database adapters, including Prisma.

在本指南中,你将把 Better Auth 集成到全新的 Astro 应用中,并将用户数据持久化到 Prisma Postgres 数据库中。你可以在 GitHub 上找到本指南的完整示例。

¥In this guide, you'll wire Better Auth into a brand-new Astro app and persist users in a Prisma Postgres database. You can find a complete example of this guide on GitHub.

先决条件

¥Prerequisites

  • Node.js 20+

  • 熟悉 Astro 和 Prisma

    ¥Basic familiarity with Astro and Prisma

1. 设置你的项目

¥ Set up your project

创建一个新的 Astro 项目:

¥Create a new Astro project:

npm create astro@latest betterauth-astro-prisma
信息
  • 你希望如何启动你的新项目?Use minimal (empty) template

    ¥How would you like to start your new project? Use minimal (empty) template

  • 安装依赖?(推荐)Yes

    ¥Install dependencies? (recommended) Yes

  • 是否初始化新​​的 git 存储库?(可选)Yes

    ¥Initialize a new git repository? (optional) Yes

导航到项目目录:

¥Navigate to the project directory:

cd betterauth-astro-prisma

这些选项将创建一个最小化的 Astro 项目,并使用 TypeScript 确保类型安全。

¥These selections will create a minimal Astro project with TypeScript for type safety.

2. 设置 Prisma

¥ Set up Prisma

接下来,你将 Prisma 添加到你的项目中以管理你的数据库。

¥Next, you'll add Prisma to your project to manage your database.

2.1.安装 Prisma 及其依赖

¥2.1. Install Prisma and dependencies

安装必要的 Prisma 软件包:

¥Install the necessary Prisma packages:

npm install prisma tsx @types/pg --save-dev
npm install @prisma/client @prisma/adapter-pg dotenv pg
信息

如果你使用其他数据库提供商(MySQL、SQL Server、SQLite),请安装相应的驱动程序适配器包,而不是 @prisma/adapter-pg。欲了解更多信息,请参阅 数据库驱动程序

¥If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of @prisma/adapter-pg. For more information, see Database drivers.

安装完成后,请在你的项目中初始化 Prisma:

¥Once installed, initialize Prisma in your project:

npx prisma init --db --output ../prisma/generated
信息

在设置 Prisma Postgres 数据库时,你需要回答几个问题。选择离你最近的区域,并为数据库选择一个容易记住的名称,例如 "我的 Better Auth Astro 项目"

¥You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Better Auth Astro Project"

这将造成:

¥This will create:

  • 一个包含 schema.prisma 文件的 prisma 目录

    ¥A prisma directory with a schema.prisma file

  • Prisma Postgres 数据库

    ¥A Prisma Postgres database

  • 项目根目录下的 .env 文件,其中包含 DATABASE_URL 文件

    ¥A .env file containing the DATABASE_URL at the project root

  • 用于配置 Prisma 的 prisma.config.ts 文件

    ¥A prisma.config.ts file for configuring Prisma

  • 用于存放生成的 Prisma Client 的 output 目录(作为 prisma/generated 文件)

    ¥An output directory for the generated Prisma Client as prisma/generated

2.2.配置 Prisma 以加载环境变量

¥2.2. Configure Prisma to load environment variables

要访问 .env 文件中的变量,请更新 prisma.config.ts 以导入 dotenv

¥To get access to the variables in the .env file, update your prisma.config.ts to import dotenv:

prisma.config.ts
import "dotenv/config";
import { defineConfig, env } from "prisma/config";

export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
engine: "classic",
datasource: {
url: env("DATABASE_URL"),
},
});

2.3.生成 Prisma 客户端

¥2.3. Generate the Prisma Client

运行以下命令生成 Prisma 客户端:

¥Run the following command to generate the Prisma Client:

npx prisma generate

2.4.设置全局 Prisma 客户端

¥2.4. Set up a global Prisma client

src 目录中,创建 lib 文件夹并在其中创建一个 prisma.ts 文件。此文件将用于创建和导出你的 Prisma 客户端实例。

¥In the src directory, create a lib folder and a prisma.ts file inside it. This file will be used to create and export your Prisma Client instance.

mkdir -p src/lib
touch src/lib/prisma.ts

按如下方式设置 Prisma 客户端:

¥Set up the Prisma client like this:

src/lib/prisma.ts
import { PrismaClient } from "../../prisma/generated/client";
import { PrismaPg } from "@prisma/adapter-pg";

const adapter = new PrismaPg({
connectionString: import.meta.env.DATABASE_URL,
});

const prisma = new PrismaClient({
adapter,
});

export default prisma;
警告

我们建议使用连接池(例如 Prisma 加速)来高效管理数据库连接。

¥We recommend using a connection pooler (like Prisma Accelerate) to manage database connections efficiently.

如果你选择不使用 PrismaClient,请避免在长期存在的环境中全局实例化 PrismaClient。请改为按请求创建并释放客户端,以防止耗尽数据库连接。

¥If you choose not to use one, avoid instantiating PrismaClient globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections.

3. 设置 Better Auth

¥ Set up Better Auth

现在是时候集成 Better Auth 进行身份验证了。

¥Now it's time to integrate Better Auth for authentication.

3.1.安装并配置 Better Auth

¥3.1. Install and configure Better Auth

首先,安装 Better Auth 核心包:

¥First, install the Better Auth core package:

npm install better-auth

接下来,生成一个安全密钥,供 Better Auth 用于签署身份验证令牌。这将确保你的令牌不会被篡改。

¥Next, generate a secure secret that Better Auth will use to sign authentication tokens. This ensures your tokens cannot be tampered with.

npx @better-auth/cli@latest secret

复制生成的密钥,并将其与应用的 URL 一起添加到你的 .env 文件中:

¥Copy the generated secret and add it, along with your application's URL, to your .env file:

.env
# Better Auth
BETTER_AUTH_SECRET=your-generated-secret
BETTER_AUTH_URL=http://localhost:4321

# Prisma
DATABASE_URL="your-database-url"
信息

Astro 的默认开发服务器运行在 4321 端口。如果你的应用运行在不同的端口上,请相应地更新 BETTER_AUTH_URL 文件。

¥Astro's default development server runs on port 4321. If your application runs on a different port, update the BETTER_AUTH_URL accordingly.

现在,为 Better Auth 创建一个配置文件。在 src/lib 目录中,创建一个 auth.ts 文件:

¥Now, create a configuration file for Better Auth. In the src/lib directory, create an auth.ts file:

touch src/lib/auth.ts

在此文件中,你将配置 Better Auth 以使用 Prisma 适配器,从而允许其将用户和会话数据持久化到数据库中。你还将启用电子邮件和密码身份验证。

¥In this file, you'll configure Better Auth to use the Prisma adapter, which allows it to persist user and session data in your database. You will also enable email and password authentication.

src/lib/auth.ts
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import prisma from "./prisma";

export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "postgresql",
}),
emailAndPassword: {
enabled: true,
},
});

Better Auth 还支持其他登录方式,例如社交登录(Google、GitHub 等),你可以在其 documentation 文件中进行探索。

¥Better Auth also supports other sign-in methods like social logins (Google, GitHub, etc.), which you can explore in their documentation.

3.2.将 Better Auth 模型添加到你的模式

¥3.2. Add Better Auth models to your schema

Better Auth 提供了一个 CLI 命令,可以自动将必要的身份验证模型(UserSessionAccountVerification)添加到你的 schema.prisma 文件中。

¥Better Auth provides a CLI command to automatically add the necessary authentication models (User, Session, Account, and Verification) to your schema.prisma file.

运行以下命令:

¥Run the following command:

npx @better-auth/cli generate
注意

它会请求确认是否覆盖你现有的 Prisma 模式。选择 y

¥It will ask for confirmation to overwrite your existing Prisma schema. Select y.

这将添加以下模型:

¥This will add the following models:

model User {
id String @id
name String
email String
emailVerified Boolean
image String?
createdAt DateTime
updatedAt DateTime
sessions Session[]
accounts Account[]

@@unique([email])
@@map("user")
}

model Session {
id String @id
expiresAt DateTime
token String
createdAt DateTime
updatedAt DateTime
ipAddress String?
userAgent String?
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@unique([token])
@@map("session")
}

model Account {
id String @id
accountId String
providerId String
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
accessToken String?
refreshToken String?
idToken String?
accessTokenExpiresAt DateTime?
refreshTokenExpiresAt DateTime?
scope String?
password String?
createdAt DateTime
updatedAt DateTime

@@map("account")
}

model Verification {
id String @id
identifier String
value String
expiresAt DateTime
createdAt DateTime?
updatedAt DateTime?

@@map("verification")
}

3.3.迁移数据库

¥3.3. Migrate the database

使用架构中的新模型,你需要更新数据库。运行迁移以创建相应的表:

¥With the new models in your schema, you need to update your database. Run a migration to create the corresponding tables:

npx prisma migrate dev --name add-auth-models
npx prisma generate

4. 设置 API 路由

¥ Set up the API routes

Better Auth 需要一个 API 端点来处理登录、注册和注销等身份验证请求。你将在 Astro 中创建一个通用 API 路由,用于处理发送到 /api/auth/[...all] 的所有请求。

¥Better Auth needs an API endpoint to handle authentication requests like sign-in, sign-up, and sign-out. You'll create a catch-all API route in Astro to handle all requests sent to /api/auth/[...all].

src/pages 目录中,创建一个 api/auth 文件夹结构,并在其中创建一个 [...all].ts 文件:

¥In the src/pages directory, create an api/auth folder structure and a [...all].ts file inside it:

mkdir -p src/pages/api/auth
touch 'src/pages/api/auth/[...all].ts'

将以下代码添加到新创建的 [...all].ts 文件中。此代码使用 Better Auth 处理程序来处理身份验证请求。

¥Add the following code to the newly created [...all].ts file. This code uses the Better Auth handler to process authentication requests.

src/pages/api/auth/[...all].ts
import { auth } from "../../../lib/auth";
import type { APIRoute } from "astro";

export const prerender = false; // Not needed in 'server' mode

export const ALL: APIRoute = async (ctx) => {
return auth.handler(ctx.request);
};

接下来,你需要一个客户端实用程序,以便从 Astro 页面与这些端点进行交互。在 src/lib 目录中,创建一个 auth-client.ts 文件:

¥Next, you'll need a client-side utility to interact with these endpoints from your Astro pages. In the src/lib directory, create an auth-client.ts file:

touch src/lib/auth-client.ts

添加以下代码,用于创建你将在 UI 中使用的客户端函数:

¥Add the following code, which creates the client functions you'll use in your UI:

src/lib/auth-client.ts
import { createAuthClient } from "better-auth/client";

export const authClient = createAuthClient();

export const { signIn, signUp, signOut, useSession } = authClient;

5. 配置 TypeScript 定义

¥ Configure TypeScript definitions

src 目录中,创建一个 env.d.ts 文件,用于提供环境变量和 Astro 局部变量的 TypeScript 定义:

¥In the src directory, create an env.d.ts file to provide TypeScript definitions for environment variables and Astro locals:

touch src/env.d.ts

添加以下类型定义:

¥Add the following type definitions:

src/env.d.ts
/// <reference path="../.astro/types.d.ts" />

declare namespace App {
interface Locals {
user: import("better-auth").User | null;
session: import("better-auth").Session | null;
}
}

interface ImportMetaEnv {
readonly DATABASE_URL: string;
}

interface ImportMeta {
readonly env: ImportMetaEnv;
}

6. 设置身份验证中间件

¥ Set up authentication middleware

src 目录中,创建一个 middleware.ts 文件,用于检查每个请求的身份验证状态。这将使用户和会话数据可供所有页面使用。

¥In the src directory, create a middleware.ts file to check authentication status on every request. This will make the user and session data available to all your pages.

touch src/middleware.ts

添加以下代码:

¥Add the following code:

src/middleware.ts
import { auth } from "./lib/auth";
import { defineMiddleware } from "astro:middleware";

export const onRequest = defineMiddleware(async (context, next) => {
context.locals.user = null;
context.locals.session = null;
const isAuthed = await auth.api.getSession({
headers: context.request.headers,
});
if (isAuthed) {
context.locals.user = isAuthed.user;
context.locals.session = isAuthed.session;
}
return next();
});

7. 设置你的页面

¥ Set up your pages

现在,让我们构建用于身份验证的用户界面。在 src/pages 目录中,创建以下文件夹结构:

¥Now, let's build the user interface for authentication. In the src/pages directory, create the following folder structure:

  • sign-up/index.astro

  • sign-in/index.astro

  • dashboard/index.astro

mkdir -p src/pages/{sign-up,sign-in,dashboard}
touch src/pages/{sign-up,sign-in,dashboard}/index.astro

7.1.注册页面

¥7.1. Sign up page

此页面允许新用户创建账户。首先在 src/pages/sign-up/index.astro 中使用基本的 HTML 结构。

¥This page allows new users to create an account. Start with the basic HTML structure in src/pages/sign-up/index.astro.

src/pages/sign-up/index.astro
---
export const prerender = false;
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Sign Up</title>
</head>
<body>
<main>
<h1>Sign Up</h1>
</main>
</body>
</html>

添加一个包含名称、邮箱和密码输入字段的表单。此表单将收集用户的注册信息。

¥Add a form with input fields for name, email, and password. This form will collect the user's registration information.

src/pages/sign-up/index.astro
---
export const prerender = false;
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Sign Up</title>
</head>
<body>
<main>
<h1>Sign Up</h1>
<form id="signup-form">
<input type="text" name="name" placeholder="Name" required />
<input type="email" name="email" placeholder="Email" required />
<input
required
type="password"
name="password"
placeholder="Password"
/>
<button type="submit">Sign up</button>
</form>
<p>Already have an account? <a href="/sign-in">Sign in here</a>.</p>
</main>
</body>
</html>

现在添加一个脚本来处理表单提交。导入 authClient 并向表单添加一个事件监听器,该监听器阻止默认提交行为,提取表单数据,并调用 Better Auth 注册方法。

¥Now add a script to handle form submission. Import the authClient and add an event listener to the form that prevents the default submission behavior, extracts the form data, and calls the Better Auth sign-up method.

src/pages/sign-up/index.astro
---
export const prerender = false;
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Sign Up</title>
</head>
<body>
<main>
<h1>Sign Up</h1>
<form id="signup-form">
<input type="text" name="name" placeholder="Name" required />
<input type="email" name="email" placeholder="Email" required />
<input
required
type="password"
name="password"
placeholder="Password"
/>
<button type="submit">Sign up</button>
</form>
<p>Already have an account? <a href="/sign-in">Sign in here</a>.</p>
</main>
<script>
import { authClient } from "../../lib/auth-client";
document
.getElementById("signup-form")
?.addEventListener("submit", async (event) => {
event.preventDefault();
const formData = new FormData(event.target as HTMLFormElement);
const name = formData.get("name") as string;
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const tmp = await authClient.signUp.email({
name,
email,
password,
});
console.log(tmp);
if (Boolean(tmp.error) === false) window.location.href = "/dashboard";
});
</script>
</body>
</html>

最后,添加服务器端检查,将已认证用户重定向到其他页面。如果用户已登录,则应将其重定向到仪表板。

¥Finally, add a server-side check to redirect authenticated users away from this page. If a user is already signed in, they should be redirected to the dashboard instead.

src/pages/sign-up/index.astro
---
export const prerender = false;

if (Astro.locals.user?.id) return Astro.redirect("/dashboard");
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Sign Up</title>
</head>
<body>
<main>
<h1>Sign Up</h1>
<form id="signup-form">
<input type="text" name="name" placeholder="Name" required />
<input type="email" name="email" placeholder="Email" required />
<input
required
type="password"
name="password"
placeholder="Password"
/>
<button type="submit">Sign up</button>
</form>
<p>Already have an account? <a href="/sign-in">Sign in here</a>.</p>
</main>
<script>
import { authClient } from "../../lib/auth-client";
document
.getElementById("signup-form")
?.addEventListener("submit", async (event) => {
event.preventDefault();
const formData = new FormData(event.target as HTMLFormElement);
const name = formData.get("name") as string;
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const tmp = await authClient.signUp.email({
name,
email,
password,
});
console.log(tmp);
if (Boolean(tmp.error) === false) window.location.href = "/dashboard";
});
</script>
</body>
</html>

7.2.登录页面

¥7.2. Sign in page

此页面允许现有用户进行身份验证。首先在 src/pages/sign-in/index.astro 中使用基本的 HTML 结构。

¥This page allows existing users to authenticate. Start with the basic HTML structure in src/pages/sign-in/index.astro.

src/pages/sign-in/index.astro
---
export const prerender = false;
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Sign In</title>
</head>
<body>
<main>
<h1>Sign In</h1>
</main>
</body>
</html>

添加一个包含邮箱和密码输入字段的表单。此表单将收集用户的凭据。

¥Add a form with input fields for email and password. This form will collect the user's credentials.

src/pages/sign-in/index.astro
---
export const prerender = false;
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Sign In</title>
</head>
<body>
<main>
<h1>Sign In</h1>
<form id="signin-form">
<input type="email" name="email" placeholder="Email" required />
<input
required
type="password"
name="password"
placeholder="Password"
/>
<button type="submit">Sign In</button>
</form>
<p>Don't have an account? <a href="/sign-up">Sign up here</a>.</p>
</main>
</body>
</html>

现在添加一个脚本来处理表单提交。导入 authClient 并添加一个事件监听器,该监听器阻止默认提交,提取表单数据,并调用 Better Auth 登录方法。

¥Now add a script to handle form submission. Import the authClient and add an event listener that prevents default submission, extracts the form data, and calls the Better Auth sign-in method.

src/pages/sign-in/index.astro
---
export const prerender = false;
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Sign In</title>
</head>
<body>
<main>
<h1>Sign In</h1>
<form id="signin-form">
<input type="email" name="email" placeholder="Email" required />
<input
required
type="password"
name="password"
placeholder="Password"
/>
<button type="submit">Sign In</button>
</form>
<p>Don't have an account? <a href="/sign-up">Sign up here</a>.</p>
</main>
<script>
import { authClient } from "../../lib/auth-client";
document
.getElementById("signin-form")
?.addEventListener("submit", async (event) => {
event.preventDefault();
const formData = new FormData(event.target as HTMLFormElement);
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const tmp = await authClient.signIn.email({
email,
password,
});
if (Boolean(tmp.error) === false) window.location.href = "/dashboard";
});
</script>
</body>
</html>

最后,添加服务器端检查,将已认证用户重定向到其他页面。如果用户已登录,则应将其重定向到仪表板。

¥Finally, add a server-side check to redirect authenticated users away from this page. If a user is already signed in, they should be redirected to the dashboard instead.

src/pages/sign-in/index.astro
---
export const prerender = false;

if (Astro.locals.user?.id) return Astro.redirect("/dashboard");
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Sign In</title>
</head>
<body>
<main>
<h1>Sign In</h1>
<form id="signin-form">
<input type="email" name="email" placeholder="Email" required />
<input
required
type="password"
name="password"
placeholder="Password"
/>
<button type="submit">Sign In</button>
</form>
<p>Don't have an account? <a href="/sign-up">Sign up here</a>.</p>
</main>
<script>
import { authClient } from "../../lib/auth-client";
document
.getElementById("signin-form")
?.addEventListener("submit", async (event) => {
event.preventDefault();
const formData = new FormData(event.target as HTMLFormElement);
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const tmp = await authClient.signIn.email({
email,
password,
});
if (Boolean(tmp.error) === false) window.location.href = "/dashboard";
});
</script>
</body>
</html>

7.3.仪表板页面

¥7.3. Dashboard page

这是经过身份验证的用户的受保护页面。首先在 src/pages/dashboard/index.astro 中使用基本的 HTML 结构。

¥This is the protected page for authenticated users. Start with the basic HTML structure in src/pages/dashboard/index.astro.

src/pages/dashboard/index.astro
---
export const prerender = false;
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Dashboard</title>
</head>
<body>
<main>
<h1>Dashboard</h1>
</main>
</body>
</html>

添加服务器端检查以保护此路由。如果用户未通过身份验证,请将其重定向到登录页面。

¥Add a server-side check to protect this route. If the user is not authenticated, redirect them to the sign-in page.

src/pages/dashboard/index.astro
---
export const prerender = false;

if (!Astro.locals.user?.id) return Astro.redirect("/sign-in");
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Dashboard</title>
</head>
<body>
<main>
<h1>Dashboard</h1>
</main>
</body>
</html>

现在显示已认证用户的信息。Astro.locals.user 对象包含中间件设置的用户数据。

¥Now display the authenticated user's information. The Astro.locals.user object contains the user data that was set by the middleware.

src/pages/dashboard/index.astro
---
export const prerender = false;

if (!Astro.locals.user?.id) return Astro.redirect("/sign-in");
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Dashboard</title>
</head>
<body>
<main>
<h1>Dashboard</h1>
<pre>{JSON.stringify(Astro.locals.user, null, 2)}</pre>
</main>
</body>
</html>

最后,添加注销按钮。导入 authClient 并添加一个按钮,该按钮调用注销方法,允许用户注销并重定向到登录页面。

¥Finally, add a sign-out button. Import the authClient and add a button that calls the sign-out method, allowing the user to log out and be redirected to the sign-in page.

src/pages/dashboard/index.astro
---
export const prerender = false;

if (!Astro.locals.user?.id) return Astro.redirect("/sign-in");
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Dashboard</title>
</head>
<body>
<main>
<h1>Dashboard</h1>
<pre>{JSON.stringify(Astro.locals.user, null, 2)}</pre>
<button id="signOutButton">Sign Out</button>
</main>
<script>
import { authClient } from "../../lib/auth-client";
document
.getElementById("signOutButton")
?.addEventListener("click", async () => {
await authClient.signOut();
window.location.href = "/sign-in";
});
</script>
</body>
</html>

7.4.主页

¥7.4. Home page

最后,更新首页以提供简洁的导航。将 src/pages/index.astro 的内容替换为以下内容:

¥Finally, update the home page to provide simple navigation. Replace the contents of src/pages/index.astro with the following:

src/pages/index.astro
---
export const prerender = false;
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Better Auth + Astro + Prisma</title>
</head>
<body>
<main>
<h1>Better Auth + Astro + Prisma</h1>
{
Astro.locals.user ? (
<div>
<p>Welcome back, {Astro.locals.user.name}!</p>
<a href="/dashboard">Go to Dashboard</a>
</div>
) : (
<div>
<a href="/sign-up">Sign Up</a>
<a href="/sign-in">Sign In</a>
</div>
)
}
</main>
</body>
</html>

8. 测试一下

¥ Test it out

你的应用现已完全配置。

¥Your application is now fully configured.

  1. 启动开发服务器进行测试:

    ¥Start the development server to test it:

npm run dev
  1. 在浏览器中导航到 http://localhost:4321。你应该看到包含 "注册" 和 "登录" 链接的主页。

    ¥Navigate to http://localhost:4321 in your browser. You should see the home page with "Sign Up" and "Sign In" links.

  2. 点击“注册”,创建一个新账户,你将被重定向到仪表板。然后你可以退出并重新登录。

    ¥Click on Sign Up, create a new account, and you should be redirected to the dashboard. You can then sign out and sign back in.

  3. 要直接在数据库中查看用户数据,你可以使用 Prisma Studio。

    ¥To view the user data directly in your database, you can use Prisma Studio.

npx prisma studio
  1. 这将在你的浏览器中打开一个新标签页,你可以在其中查看 UserSessionAccount 表及其内容。

    ¥This will open a new tab in your browser where you can see the User, Session, and Account tables and their contents.

success

恭喜!你现在拥有一个使用 Better Auth、Prisma 和 Astro 构建的、功能齐全的身份验证系统。

¥Congratulations! You now have a fully functional authentication system built with Better Auth, Prisma, and Astro.

下一步

¥Next steps

  • 添加对社交登录或魔术链接的支持

    ¥Add support for social login or magic links

  • 实现密码重置和电子邮件验证

    ¥Implement password reset and email verification

  • 添加用户个人资料和账户管理页面

    ¥Add user profile and account management pages

  • 部署到 Vercel 或 Netlify 并保护你的环境变量

    ¥Deploy to Vercel or Netlify and secure your environment variables

  • 使用自定义应用模型扩展你的 Prisma 模式

    ¥Extend your Prisma schema with custom application models

延伸阅读

¥Further reading


Stay connected with Prisma

Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:

We genuinely value your involvement and look forward to having you as part of our community!