伊利西亚集成
本集成指南假设你正在使用带有 bun 服务器的 Elysia。
🌐 This integration guide is assuming you are using Elysia with bun server.
在开始之前,请确保你已配置了 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
我们需要将处理器挂载到 Elysia 端点。
🌐 We need to mount the handler to Elysia endpoint.
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 插件。
🌐 To configure cors, you can use the cors plugin from @elysiajs/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 在传递给视图之前提供会话和用户信息。
🌐 You can use macro with resolve to provide session and user information before pass to view.
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 对象。
🌐 This will allow you to access the user and session object in all of your routes.