콘텐츠로 이동

Astro 세션 드라이버 API

Astro의 세션을 사용하면 온디맨드 렌더링 페이지의 요청 간에 데이터를 공유할 수 있습니다. 세션 데이터를 저장하려면 Astro 세션 드라이버가 필요합니다.

Astro는 astro/config에서 기본 제공 세션 드라이버를 내보냅니다.

import { sessionDrivers } from 'astro/config'

모든 unstorage 드라이버를 사용할 수 있습니다. 예를 들면 다음과 같습니다.

astro.config.mjs
import { defineConfig, sessionDrivers } from 'astro/config'
export default defineConfig({
session: {
driver: sessionDrivers.redis({
url: process.env.REDIS_URL
}),
}
})

세션 드라이버는 두 부분으로 구성됩니다.

  • 드라이버 설정: Astro가 런타임에 어떤 구현을 사용할지, 어떤 설정을 전달할지 알려줍니다.
  • 드라이버 구현: 런타임에 스토리지 로직을 처리합니다.

SessionDriverConfig는 필수 런타임 entrypoint와 선택적 config를 포함하는 객체입니다. 이를 구현하는 선호되는 방법은 이 객체를 반환하고 설정을 선택적 매개변수로 받는 함수를 내보내는 것입니다.

다음 예시는 메모리 드라이버 설정을 정의합니다.

driver/config.ts
import type { SessionDriverConfig } from 'astro'
export interface Config {
max?: number;
}
export function memoryDriver(config: Config = {}): SessionDriverConfig {
return {
entrypoint: new URL('./runtime.js', import.meta.url),
config,
}
}

그 다음 Astro 설정에 등록합니다.

astro.config.ts
import { defineConfig } from 'astro/config'
import { memoryDriver } from './driver/config'
export default defineConfig({
session: {
driver: memoryDriver({
max: 500
})
}
})

타입: string | URL

추가된 버전: astro@6.0.0

드라이버 구현을 위한 진입점을 정의합니다.

타입: Record<string, any> | undefined

추가된 버전: astro@6.0.0

런타임에 드라이버 구현으로 전달되는 직렬화 가능한 설정을 정의합니다.

SessionDriver런타임에 세션을 사용할 때 (예: context.session.set()) 데이터를 저장, 조회삭제하는 역할을 담당하는 객체입니다. 세션 드라이버 모듈에서 드라이버 설정을 매개변수로 받는 기본 함수를 내보내어 구현할 수 있습니다.

다음 예시는 메모리 드라이버를 구현합니다.

driver/runtime.ts
import type { SessionDriver } from 'astro'
import type { Config } from './config'
import { LRUCache } from 'lru-cache'
export default function(config: Config): SessionDriver {
const cache = new LRUCache({ max: config.max })
return {
setItem: async (key, value) => {
cache.set(key, value)
},
getItem: async (key) => {
return cache.get(key)
},
removeItem: async (key) => {
cache.delete(key)
},
}
}

타입: (key: string, value: any) => Promise<void>

추가된 버전: astro@6.0.0

키별로 세션 데이터를 설정하는 함수를 정의합니다.

타입: (key: string) => Promise<any>

추가된 버전: astro@6.0.0

키별로 세션 데이터를 조회하는 함수를 정의합니다.

타입: (key: string) => Promise<void>

추가된 버전: astro@6.0.0

키별로 세션 데이터를 제거하는 함수를 정의합니다.

기본 제공 드라이버는 Unstorage와 동일한 드라이버를 제공합니다. 더 많은 사용자 지정이 필요한 경우, 모든 Unstorage 드라이버를 기반으로 자체 드라이버를 빌드할 수 있습니다.

unstorage 패키지를 설치하고 드라이버 지정자를 진입점으로 전달하세요.

driver/config.ts
import type { SessionDriverConfig } from "astro";
export function configuredRedisDriver(): SessionDriverConfig {
return {
entrypoint: "unstorage/drivers/redis",
config: {
tls: true,
},
};
}

Unstorage 드라이버를 가져와 자체 구현으로 래핑할 수도 있습니다. 드라이버에 추가 로직을 적용하거나 런타임에 구성을 재정의하려는 경우에 유용합니다.

다음 예시는 기본 ttl이 7일로 설정된 Redis 드라이버를 구현합니다.

driver/runtime.ts
import type { SessionDriver } from "astro";
import redisDriver, { type RedisOptions } from "unstorage/drivers/redis";
export default function (config: RedisOptions): SessionDriver {
const driver = redisDriver({
...config,
ttl: config.ttl ?? 60 * 60 * 24 * 7, // 기본값: 7일
});
return {
async getItem(key) {
return await driver.getItem(key);
},
async setItem(key, value) {
await driver.setItem?.(key, value, {});
},
async removeItem(key) {
await driver.removeItem?.(key, {});
},
};
}
기여하기 커뮤니티 후원하기