Better Auth Fastify 통합 가이드
이 가이드는 필수 핸들러와 CORS 설정을 모두 구성하기 위한 단계별 지침을 제공합니다.
진행하기 전에 Better Auth 인스턴스가 구성되어 있어야 합니다. 아직 설정하지 않았다면 설치 가이드를 참조하세요.
사전 준비사항
통합 전에 다음 요구사항을 확인하세요:
- Node.js 환경: v16 이상 설치됨
- ES 모듈 지원: 다음 중 하나에서 ES 모듈 활성화:
package.json:{ "type": "module" }- TypeScript
tsconfig.json:{ "module": "ESNext" }
- Fastify 종속성:
npm install fastify @fastify/cors
TypeScript의 경우: 최적의 호환성을 위해
tsconfig.json에 "esModuleInterop": true가 포함되어 있는지 확인하세요. 인증 핸들러 설정
캐치올 라우트를 생성하여 Better Auth가 인증 요청을 처리하도록 구성하세요:
import Fastify from "fastify";
import { auth } from "./auth"; // 구성된 Better Auth 인스턴스
const fastify = Fastify({ logger: true });
// 인증 엔드포인트 등록
fastify.route({
method: ["GET", "POST"],
url: "/api/auth/*",
async handler(request, reply) {
try {
// 요청 URL 구성
const url = new URL(request.url, `http://${request.headers.host}`);
// Fastify 헤더를 표준 Headers 객체로 변환
const headers = new Headers();
Object.entries(request.headers).forEach(([key, value]) => {
if (value) headers.append(key, value.toString());
});
// Fetch API 호환 요청 생성
const req = new Request(url.toString(), {
method: request.method,
headers,
body: request.body ? JSON.stringify(request.body) : undefined,
});
// 인증 요청 처리
const response = await auth.handler(req);
// 클라이언트로 응답 전달
reply.status(response.status);
response.headers.forEach((value, key) => reply.header(key, value));
reply.send(response.body ? await response.text() : null);
} catch (error) {
fastify.log.error("Authentication Error:", error);
reply.status(500).send({
error: "Internal authentication error",
code: "AUTH_FAILURE"
});
}
}
});
// 서버 초기화
fastify.listen({ port: 4000 }, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
console.log("Server running on port 4000");
});신뢰할 수 있는 출처
다른 출처에서 요청이 이루어지면, 기본적으로 요청이 차단됩니다. auth 인스턴스에 신뢰할 수 있는 출처를 추가할 수 있습니다.
export const auth = betterAuth({
trustedOrigins: ["http://localhost:3000", "https://example.com"],
});CORS 구성
적절한 CORS 구성으로 API 엔드포인트를 보호하세요:
import fastifyCors from "@fastify/cors";
// CORS 정책 구성
fastify.register(fastifyCors, {
origin: process.env.CLIENT_ORIGIN || "http://localhost:3000",
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: [
"Content-Type",
"Authorization",
"X-Requested-With"
],
credentials: true,
maxAge: 86400
});
// CORS 등록 후 인증 핸들러 마운트
// (여기에 이전 핸들러 구성 사용) 프로덕션 환경에서는 항상 CORS 출처를 제한하세요. 동적 구성을 위해 환경 변수를 사용하세요.