Astro 통합

Better Auth는 Astro를 위한 일급 지원을 제공합니다. 이 가이드는 Better Auth를 Astro와 통합하는 방법을 안내합니다.

시작하기 전에, Better Auth 인스턴스가 설정되어 있는지 확인하세요. 아직 설정하지 않았다면 설치를 확인하세요.

핸들러 마운트

Better Auth가 요청을 처리할 수 있도록 하려면, 핸들러를 캐치올 API 라우트에 마운트해야 합니다. /pages/api/auth 내부에 [...all].ts 파일을 생성하고 다음 코드를 추가하세요:

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

export const ALL: APIRoute = async (ctx) => {
	// 속도 제한을 사용하려면, 컨텍스트에서 요청 헤더에 'x-forwarded-for' 헤더를 설정해야 합니다
	// ctx.request.headers.set("x-forwarded-for", ctx.clientAddress);
	return auth.handler(ctx.request);
};

better-auth 설정에서 경로를 변경할 수 있지만 /api/auth/[...all]로 유지하는 것이 권장됩니다

클라이언트 생성

Astro는 여러 프론트엔드 프레임워크를 지원하므로, 사용 중인 프레임워크에 따라 클라이언트를 쉽게 가져올 수 있습니다.

프론트엔드 프레임워크를 사용하지 않는 경우에도 바닐라 클라이언트를 가져올 수 있습니다.

lib/auth-client.ts
import { createAuthClient } from "better-auth/client"
export const authClient =  createAuthClient()
lib/auth-client.ts
import { createAuthClient } from "better-auth/react"
export const authClient =  createAuthClient()
lib/auth-client.ts
import { createAuthClient } from "better-auth/vue"
export const authClient =  createAuthClient()
lib/auth-client.ts
import { createAuthClient } from "better-auth/svelte"
export const authClient =  createAuthClient()
lib/auth-client.ts
import { createAuthClient } from "better-auth/solid"
export const authClient =  createAuthClient()

인증 미들웨어

Astro Locals 타입

Astro locals에 대한 타입을 갖추려면, env.d.ts 파일 내부에 설정해야 합니다.

env.d.ts

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

declare namespace App {
    // 참고: 'import {} from ""' 구문은 .d.ts 파일에서 작동하지 않습니다.
    interface Locals {
        user: import("better-auth").User | null;
        session: import("better-auth").Session | null;
    }
}

미들웨어

라우트를 보호하려면, 미들웨어에서 getSession 메서드를 사용하여 사용자가 인증되었는지 확인하고 이전에 설정한 타입을 사용하여 Astro locals를 통해 사용자 및 세션 데이터를 설정할 수 있습니다. 프로젝트 루트에 middleware.ts 파일을 생성하고 아래 예제를 따르세요:

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

export const onRequest = defineMiddleware(async (context, next) => {
    const isAuthed = await auth.api
        .getSession({
            headers: context.request.headers,
        })

    if (isAuthed) {
        context.locals.user = isAuthed.user;
        context.locals.session = isAuthed.session;
    } else {
        context.locals.user = null;
        context.locals.session = null;
    }

    return next();
});

.astro 파일 내부의 서버에서 세션 가져오기

Astro.locals를 사용하여 사용자가 세션을 가지고 있는지 확인하고 서버 측에서 사용자 데이터를 가져올 수 있습니다. 다음은 .astro 파일 내부에서 세션을 가져오는 방법의 예입니다:

---
import { UserCard } from "@/components/user-card";

const session = () => {
    if (Astro.locals.session) {
        return Astro.locals.session;
    } else {
        // 사용자가 인증되지 않은 경우 로그인 페이지로 리디렉션
        return Astro.redirect("/login");
    }
}

---

<UserCard initialSession={session} />

On this page