Nitro 集成
Better Auth 可以与你的 Nitro 应用 集成(一个用于构建 Web 服务器的开源框架)。
【Better Auth can be integrated with your Nitro Application (an open source framework to build web servers).】
本指南旨在帮助你通过几个简单步骤将 Better Auth 集成到你的 Nitro 应用中。
【This guide aims to help you integrate Better Auth with your Nitro application in a few simple steps.】
创建一个新的 Nitro 应用
【Create a new Nitro Application】
首先使用以下命令搭建一个新的 Nitro 应用:
【Start by scaffolding a new Nitro application using the following command:】
npx giget@latest nitro nitro-app --install这将创建 nitro-app 目录并安装所有依赖。你现在可以在代码编辑器中打开 nitro-app 目录。
【This will create the nitro-app directory and install all the dependencies. You can now open the nitro-app directory in your code editor.】
Prisma 适配器设置
【Prisma Adapter Setup】
本指南假设你对 Prisma 有基本了解。如果你是 Prisma 新手,可以查看 Prisma 文档。
本指南中使用的 sqlite 数据库不适合在生产环境中使用。你应该将其替换为像 PostgreSQL 这样的生产级数据库。
在本指南中,我们将使用 Prisma 适配器。你可以通过运行以下命令来安装 Prisma 客户端:
【For this guide, we will be using the Prisma adapter. You can install prisma client by running the following command:】
npm install @prisma/clientprisma 可以作为开发依赖使用以下命令安装:
npm install -D prisma通过运行以下命令,在 prisma 目录中生成一个 schema.prisma 文件:
【Generate a schema.prisma file in the prisma directory by running the following command:】
npx prisma init你现在可以将 schema.prisma 文件的内容替换为以下内容:
【You can now replace the contents of the schema.prisma file with the following:】
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
// Will be deleted. Just need it to generate the prisma client
model Test {
id Int @id @default(autoincrement())
name String
}确保你更新 .env 文件中的 DATABASE_URL,以指向你的数据库位置。
【Ensure that you update the DATABASE_URL in your .env file to point to the location of your database.】
DATABASE_URL="file:./dev.db"运行以下命令以生成 Prisma 客户端并同步数据库:
【Run the following command to generate the Prisma client & sync the database:】
npx prisma db push安装与配置更好的认证
【Install & Configure Better Auth】
按照安装指南中的步骤 1 和步骤 2,在你的 Nitro 应用中安装 Better Auth 并设置环境变量。
【Follow steps 1 & 2 from the installation guide to install Better Auth in your Nitro application & set up the environment variables.】
完成后,在 server/utils/auth.ts 文件中创建你的 Better Auth 实例。
【Once that is done, create your Better Auth instance within the server/utils/auth.ts file.】
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, { provider: "sqlite" }),
emailAndPassword: { enabled: true },
});更新 Prisma 架构
【Update Prisma Schema】
使用 Better Auth CLI 通过运行以下命令更新你的 Prisma 模式以包含所需的模型:
【Use the Better Auth CLI to update your Prisma schema with the required models by running the following command:】
npx @better-auth/cli generate --config server/utils/auth.ts--config 标志用于指定你创建 Better Auth 实例的文件路径。
前往 prisma/schema.prisma 文件,并保存文件以触发保存时格式化。
【Head over to the prisma/schema.prisma file & save the file to trigger the format on save.】
保存文件后,你可以运行 npx prisma db push 命令来更新数据库模式。
【After saving the file, you can run the npx prisma db push command to update the database schema.】
挂载处理器
【Mount The Handler】
你现在可以在你的 Nitro 应用中挂载 Better Auth 处理器。你可以通过将以下代码添加到你的 server/routes/api/auth/[...all].ts 文件来实现这一点:
【You can now mount the Better Auth handler in your Nitro application. You can do this by adding the following code to your server/routes/api/auth/[...all].ts file:】
export default defineEventHandler((event) => {
return auth.handler(toWebRequest(event));
});This is a catch-all route that will handle all requests to /api/auth/*.
跨域资源共享
【CORS】
你可以通过创建插件为你的 Nitro 应用配置 CORS。
【You can configure CORS for your Nitro app by creating a plugin.】
首先安装 cors 包:
【Start by installing the cors package:】
npm install cors你现在可以创建一个新文件 server/plugins/cors.ts 并添加以下代码:
【You can now create a new file server/plugins/cors.ts and add the following code:】
import cors from "cors";
export default defineNitroPlugin((plugin) => {
plugin.h3App.use(
fromNodeMiddleware(
cors({
origin: "*",
}),
),
);
});This will enable CORS for all routes. You can customize the origin property to allow requests from specific domains. Ensure that the config is in sync with your frontend application.
认证守卫/中间件
【Auth Guard/Middleware】
你可以在你的 Nitro 应用中添加身份验证守卫来保护需要认证的路由。你可以通过创建一个新文件 server/utils/require-auth.ts 并添加以下代码来实现:
【You can add an auth guard to your Nitro application to protect routes that require authentication. You can do this by creating a new file server/utils/require-auth.ts and adding the following code:】
import { EventHandler, H3Event } from "h3";
import { fromNodeHeaders } from "better-auth/node";
/**
* Middleware used to require authentication for a route.
*
* Can be extended to check for specific roles or permissions.
*/
export const requireAuth: EventHandler = async (event: H3Event) => {
const headers = event.headers;
const session = await auth.api.getSession({
headers: headers,
});
if (!session)
throw createError({
statusCode: 401,
statusMessage: "Unauthorized",
});
// You can save the session to the event context for later use
event.context.auth = session;
};现在你可以在路由中使用此事件处理程序/中间件来保护它们:
【You can now use this event handler/middleware in your routes to protect them:】
// Object syntax of the route handler
export default defineEventHandler({
// The user has to be logged in to access this route
onRequest: [requireAuth],
handler: async (event) => {
setResponseStatus(event, 201, "Secret data");
return { message: "Secret data" };
},
});示例
【Example】
你可以在 这里 找到一个集成了 Better Auth 和 Prisma 的 Nitro 应用示例。
【You can find an example of a Nitro application integrated with Better Auth & Prisma here.】