Elysia 集成
本集成指南假设您使用 Bun 服务器与 Elysia 一起使用。
在开始之前,请确保您已配置 Better Auth 实例。如果您尚未这样做,请查看 安装。
挂载处理程序
我们需要将处理程序挂载到 Elysia 端点。
import { Elysia } from "elysia";
import { auth } from "./auth";
const app = new Elysia().mount(auth.handler).listen(3000);
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
);CORS
要配置 CORS,您可以使用 @elysiajs/cors 的 cors 插件。
import { Elysia } from "elysia";
import { cors } from "@elysiajs/cors";
import { auth } from "./auth";
const app = new Elysia()
.use(
cors({
origin: "http://localhost:3001",
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
credentials: true,
allowedHeaders: ["Content-Type", "Authorization"],
})
)
.mount(auth.handler)
.listen(3000);
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
);Macro
您可以使用 macro 与 resolve 在传递到视图之前提供会话和用户信息的支持。
import { Elysia } from "elysia";
import { auth } from "./auth";
// user middleware (compute user and session and pass to routes)
const betterAuth = new Elysia({ name: "better-auth" })
.mount(auth.handler)
.macro({
auth: {
async resolve({ status, request: { headers } }) {
const session = await auth.api.getSession({
headers,
});
if (!session) return status(401);
return {
user: session.user,
session: session.session,
};
},
},
});
const app = new Elysia()
.use(betterAuth)
.get("/user", ({ user }) => user, {
auth: true,
})
.listen(3000);
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
);这将允许您在所有路由中访问 user 和 session 对象。