Astro 어댑터 API
Astro는 서버 측 렌더링(SSR)으로 알려진 요청 시 렌더링을 위해 모든 클라우드 제공업체에 쉽게 배포할 수 있도록 설계되었습니다. 이 기능은 통합으로 제공되는 어댑터 를 통해 사용할 수 있습니다. 기존 어댑터를 사용하는 방법을 알아보려면 요청 시 렌더링 가이드를 참조하세요.
어댑터란 무엇입니까?
섹션 제목: 어댑터란 무엇입니까?어댑터는 요청 시 서버 렌더링을 위한 엔트리포인트 제공하는 특별한 종류의 통합입니다. 어댑터는 두 가지 작업을 수행합니다.
- 요청 처리를 위한 호스트별 API를 구현합니다.
- 호스트 규칙에 따라 빌드를 구성합니다.
어댑터 빌드
섹션 제목: 어댑터 빌드어댑터는 통합이며 통합이 수행할 수 있는 모든 작업을 수행할 수 있습니다.
어댑터는 반드시 다음과 같이 astro:config:done
후크에서 setAdapter
API를 호출해야 합니다.
export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', supportedAstroFeatures: { staticOutput: 'stable' } }); }, }, };}
setAdapter
에 전달된 객체는 다음과 같이 정의됩니다.
interface AstroAdapter { name: string; serverEntrypoint?: string; exports?: string[]; adapterFeatures: AstroAdapterFeatures; supportedAstroFeatures: AstroAdapterFeatureMap;}
export interface AstroAdapterFeatures { /** * Astro 미들웨어와 통신할 에지 기능을 생성합니다. */ edgeMiddleware: boolean; /** * 어댑터가 의도하는 빌드 출력 유형을 결정합니다. 기본값은 `server`입니다. */ buildOutput?: 'static' | 'server';}
export type AdapterSupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated' | 'limited';
export type AdapterSupportWithMessage = { support: Exclude<AdapterSupportsKind, 'stable'>; message: string;};
export type AdapterSupport = AdapterSupportsKind | AdapterSupportWithMessage;
export type AstroAdapterFeatureMap = { /** * 어댑터는 정적 페이지를 제공할 수 있습니다. */ staticOutput?: AdapterSupport; /** * 어댑터는 정적이거나 서버를 통해 렌더링되는 페이지를 제공할 수 있습니다. */ hybridOutput?: AdapterSupport; /** * 어댑터는 요청 시 렌더링되는 페이지를 제공할 수 있습니다. */ serverOutput?: AdapterSupport; /** * 어댑터는 i18n 도메인을 지원할 수 있습니다. */ i18nDomains?: AdapterSupport; /** * 어댑터는 `astro:env/server`에서 내보낸 `getSecret`을 지원할 수 있습니다. */ envGetSecret?: AdapterSupport; /** * 어댑터는 Sharp 이미지 서비스를 지원합니다. */ sharpImageService?: AdapterSupport;};
속성은 다음과 같습니다.
- name: 로깅에 사용되는 어댑터의 고유 이름입니다.
- serverEntrypoint: 요청 시 서버 렌더링의 엔트리포인트입니다.
- exports:
createExports
와 함께 사용되는 경우 명명된 내보내기 배열입니다 (아래 설명 참조). - adapterFeatures: 어댑터에서 지원해야 하는 특정 기능을 활성화하는 객체입니다. 이러한 기능은 빌드된 출력을 변경하며 어댑터는 다양한 출력을 처리하기 위해 적절한 로직을 구현해야 합니다.
- supportedAstroFeatures: Astro 내장 기능 맵입니다. 이를 통해 Astro는 어댑터가 지원할 수 없거나 지원하지 않는 기능을 판단하여 적절한 오류 메시지를 제공할 수 있습니다.
서버 엔트리포인트
섹션 제목: 서버 엔트리포인트Astro의 어댑터 API는 모든 유형의 호스트와 작동하려고 시도하며 호스트 API를 준수하는 유연한 방법을 제공합니다.
Exports
섹션 제목: Exports일부 서버리스 호스트는 handler
와 같은 함수를 내보낼 것을 기대합니다.
export function handler(event, context) { // ...}
어댑터 API를 사용하면 serverEntrypoint
에 createExports
를 구현하여 이를 달성할 수 있습니다.
import { App } from 'astro/app';
export function createExports(manifest) { const app = new App(manifest);
const handler = (event, context) => { // ... };
return { handler };}
그런 다음 setAdapter
를 호출하는 통합에서 exports
에 이 이름을 제공합니다.
export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', exports: ['handler'], }); }, }, };}
Start
섹션 제목: Start일부 호스트는 포트를 수신하여 서버를 직접 시작하기를 기대합니다. 이러한 유형의 호스트의 경우 어댑터 API를 사용하면 번들 스크립트가 실행될 때 호출되는 start
함수를 내보낼 수 있습니다.
import { App } from 'astro/app';
export function start(manifest) { const app = new App(manifest);
addEventListener('fetch', event => { // ... });}
astro/app
섹션 제목: astro/app이 모듈은 astro build
를 통해 사전 빌드된 페이지를 렌더링하는 데 사용됩니다. Astro는 표준 Request 및 Response 객체를 사용합니다. 요청/응답에 대해 다른 API를 사용하는 호스트는 어댑터에서 이러한 유형으로 변환해야 합니다.
import { App } from 'astro/app';import http from 'http';
export function start(manifest) { const app = new App(manifest);
addEventListener('fetch', event => { event.respondWith( app.render(event.request) ); });}
다음과 같은 메서드가 제공됩니다.
app.render()
섹션 제목: app.render()타입: (request: Request, options?: RenderOptions) => Promise<Response>
이 메서드는 요청과 일치하는 Astro 페이지를 호출하고 렌더링한 후 Response 객체에 Promise를 반환합니다. 이는 페이지를 렌더링하지 않는 API 경로에도 적용됩니다.
const response = await app.render(request);
RenderOptions
섹션 제목: RenderOptions타입: {addCookieHeader?: boolean; clientAddress?: string; locals?: object; routeData?: RouteData;}
app.render()
메서드는 필수 request
인수와 addCookieHeader
, clientAddress
, locals
, routeData
에 대한 선택적 RenderOptions
객체를 허용합니다.
addCookieHeader
섹션 제목: addCookieHeader타입: boolean
기본값: false
Astro.cookie.set()
이 작성한 모든 쿠키를 응답 헤더에 자동으로 추가할지 여부입니다.
true
로 설정하면 응답의 Set-Cookie
헤더에 쉼표로 구분된 키-값 쌍으로 추가됩니다. 표준 response.headers.getSetCookie()
API를 사용하여 개별적으로 읽을 수 있습니다. false
(기본값)로 설정하면 App.getSetCookieFromResponse(response)
에서만 쿠키를 사용할 수 있습니다.
const response = await app.render(request, { addCookieHeader: true });
clientAddress
섹션 제목: clientAddress타입: string
기본값: request[Symbol.for("astro.clientAddress")]
페이지에서는 Astro.clientAddress
로, API 경로 및 미들웨어에서는 ctx.clientAddress
로 사용할 수 있는 클라이언트 IP 주소입니다.
아래 예시에서는 x-forwarded-for
헤더를 읽고 이를 clientAddress
로 전달합니다. 이 값은 사용자가 Astro.clientAddress
로 사용할 수 있게 됩니다.
const clientAddress = request.headers.get("x-forwarded-for");const response = await app.render(request, { clientAddress });
locals
섹션 제목: locals타입: object
요청 수명 주기 동안 정보를 저장하고 액세스하는 데 사용되는 context.locals
객체입니다.
아래 예시에서는 x-private-header
라는 헤더를 읽고 이를 객체로 구문 분석한 후 locals
에 전달하려고 시도합니다. 그런 다음 미들웨어 함수에 전달될 수 있습니다.
const privateHeader = request.headers.get("x-private-header");let locals = {};try { if (privateHeader) { locals = JSON.parse(privateHeader); }} finally { const response = await app.render(request, { locals });}
routeData
섹션 제목: routeData타입: RouteData
기본값: app.match(request)
렌더링할 경로를 이미 알고 있는 경우 integrationRouteData
에 대한 값을 제공하세요. 그렇게 하면 렌더링할 경로를 결정하기 위해 app.match
에 대한 내부 호출을 우회하게 됩니다.
const routeData = app.match(request);if (routeData) { return app.render(request, { routeData });} else { /* 어댑터별 404 응답 */ return new Response(..., { status: 404 });}
app.match()
섹션 제목: app.match()타입: (request: Request) => RouteData | undefined
이 메서드는 요청이 Astro 앱의 라우팅 규칙과 일치하는지 확인하는 데 사용됩니다.
if(app.match(request)) { const response = await app.render(request);}
Astro가 404.astro
파일을 제공하면 404를 처리하기 때문에 일반적으로 .match
를 사용하지 않고 app.render(request)
를 호출할 수 있습니다. 404를 다른 방식으로 처리하려면 app.match(request)
를 사용하세요.
astro add
를 통한 설치 허용
섹션 제목: astro add를 통한 설치 허용astro add
명령을 사용하면 사용자가 프로젝트에 통합 및 어댑터를 쉽게 추가할 수 있습니다. 이 도구를 사용하여 여러분의 어댑터를 설치하려면 package.json
파일의 keywords
필드에 astro-adapter
를 추가하세요:
{ "name": "example", "keywords": ["astro-adapter"],}
어댑터를 npm에 게시한 후, astro add example
을 실행하면 package.json
파일에 지정된 피어 종속성과 함께 패키지가 설치됩니다. 또한 사용자에게 프로젝트 구성을 수동으로 업데이트하도록 지시할 것입니다.
Astro 기능
섹션 제목: Astro 기능
Added in:
astro@3.0.0
Astro 기능은 어댑터가 Astro에 기능을 지원할 수 있는지 여부와 어댑터의 지원 수준을 알려주는 방법입니다.
이러한 속성을 사용할 때 Astro는 다음을 수행합니다.
- 특정 검증을 실행합니다.
- 로그에 대한 상황에 맞는 정보를 내보냅니다.
이러한 작업은 지원되거나 지원되지 않는 기능, 지원 수준 및 사용자가 사용하는 구성을 기반으로 실행됩니다.
다음 구성은 이 어댑터가 Sharp 기반의 내장 이미지 서비스에 대한 실험적 지원을 가지고 있음을 Astro에 알려줍니다.
export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', supportedAstroFeatures: { sharpImageService: 'experimental' } }); }, }, };}
Sharp 이미지 서비스가 사용되는 경우, Astro는 어댑터의 지원 상태에 따라 터미널에 경고와 오류를 기록할 것입니다.
[@matthewp/my-adapter] The feature is experimental and subject to issues or changes.
[@matthewp/my-adapter] The currently selected adapter `@matthewp/my-adapter` is not compatible with the service "Sharp". Your project will NOT be able to build.
사용자에게 더 많은 맥락을 제공하기 위해 추가적인 메시지를 제공할 수 있습니다:
export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', supportedAstroFeatures: { sharpImageService: { support: 'limited', message: 'This adapter has limited support for Sharp, certain features may not work as expected.' } } }); }, }, };}
어댑터 기능
섹션 제목: 어댑터 기능내보낸 파일의 출력을 변경하는 기능 세트입니다. 어댑터가 이러한 기능을 선택하면 특정 후크에서 추가 정보를 얻게 됩니다.
edgeMiddleware
섹션 제목: edgeMiddleware타입: boolean
요청 시 렌더링되는 미들웨어 코드가 빌드 타임에 번들링될지 여부를 정의합니다.
활성화되면, 이는 빌드 타임에 모든 페이지에서 미들웨어 코드가 번들링되고 가져와지는 것을 방지합니다:
export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', adapterFeatures: { edgeMiddleware: true } }); }, }, };}
그런 다음, 파일 시스템의 실제 파일에 대한 URL
인 middlewareEntryPoint
를 제공하는 astro:build:ssr
훅을 사용합니다.
export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', adapterFeatures: { edgeMiddleware: true } }); },
'astro:build:ssr': ({ middlewareEntryPoint }) => { // 이 속성이 존재하는지 확인하는 것을 잊지 마세요. 어댑터가 이 기능을 사용하도록 설정하지 않은 경우 `undefined`가 될 것입니다. if (middlewareEntryPoint) { createEdgeMiddleware(middlewareEntryPoint) } } }, };}
function createEdgeMiddleware(middlewareEntryPoint) { // 번들러를 사용하여 새로운 물리적 파일을 생성하세요.}
envGetSecret
섹션 제목: envGetSecret타입: AdapterSupportsKind
이는 어댑터가 env.schema
에서 사용자가 구성한 비밀을 검색할 수 있도록 하는 기능입니다.
어댑터에 유효한 AdapterSupportsKind
값을 전달하여 기능을 활성화하세요:
export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', adapterFeatures: { envGetSecret: 'stable' } }); }, }, };}
astro/env/setup
모듈을 통해 getSecret()
구현을 제공할 수 있습니다. 서버 엔트리포인트에서 가능한 한 빨리 setGetEnv()
를 호출하세요:
import { App } from 'astro/app';import { setGetEnv } from "astro/env/setup"
setGetEnv((key) => process.env[key])
export function createExports(manifest) { const app = new App(manifest); const handler = (event, context) => { // ... };
return { handler };}
비밀을 지원하는 경우, 환경 변수가 요청에 연결되어 있을 때 getSecret()
전에 setGetEnv()
를 호출해야 합니다:
import type { SSRManifest } from 'astro';import { App } from 'astro/app';import { setGetEnv } from 'astro/env/setup';import { createGetEnv } from '../utils/env.js';
type Env = { [key: string]: unknown;};
export function createExports(manifest: SSRManifest) { const app = new App(manifest);
const fetch = async (request: Request, env: Env) => { setGetEnv(createGetEnv(env));
const response = await app.render(request);
return response; };
return { default: { fetch } };}
buildOutput
섹션 제목: buildOutput타입: 'static' | 'server'
astro@5.0.0
이 속성을 사용하면 빌드의 특정 출력 형태를 강제할 수 있습니다. 이는 특정 출력 유형에서만 작동하는 어댑터에 유용할 수 있습니다. 예를 들어, 어댑터가 정적 웹사이트를 기대하지만 호스트별 파일을 생성하기 위해 어댑터를 사용하는 경우가 있습니다. 지정하지 않으면 기본값은 server
입니다.
export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', adapterFeatures: { buildOutput: 'static' } }); }, }, };}