Fetch 라우팅 API 참조
추가된 버전:
astro@7.0.0
astro/fetch 모듈은 표준 Fetch API를 기반으로 구축된 고급 라우팅 핸들러를 제공합니다.
astro/fetch에서 가져오기
섹션 제목: “astro/fetch에서 가져오기”import { FetchState, astro, actions, cache, i18n, middleware, notFound, pages, redirects, sessions, trailingSlash,} from "astro/fetch";FetchState
섹션 제목: “FetchState”요청별 상태 객체입니다. fetch 메서드의 시작 부분에서 생성하세요:
import { FetchState } from "astro/fetch";
export default { async fetch(request: Request): Promise<Response> { const state = new FetchState(request); // 고급 라우팅 로직... },};FetchState는 일치하는 라우트, 쿠키, 세션 프로바이더 및 기타 요청별 데이터를 추적합니다. 모든 핸들러 함수는 첫 번째 인자로 이 객체를 전달해야 합니다.
FetchState를 사용하여 핸들러를 조합하는 방법을 알아보세요.
state.request
섹션 제목: “state.request”타입: Request
들어오는 Request 객체입니다.
state.url
섹션 제목: “state.url”타입: URL
요청에서 파생된 정규화된 URL입니다.
state.pathname
섹션 제목: “state.pathname”타입: string
요청에서 기본 경로를 제외하고 디코딩한 경로명입니다 (예: /about 또는 /blog/my-post).
state.routeData
섹션 제목: “state.routeData”타입: RouteData | undefined
이 요청과 일치하는 라우트입니다 (존재하는 경우). FetchState가 생성될 때 자동으로 해석됩니다.
state.cookies
섹션 제목: “state.cookies”타입: AstroCookies
이 요청에 대한 쿠키를 읽고 설정하기 위한 AstroCookies 인스턴스입니다.
state.locals
섹션 제목: “state.locals”타입: App.Locals
사용자 정의 데이터를 저장하기 위한 요청 스코프의 객체입니다. 이는 미들웨어 및 API 라우트에서 사용할 수 있는 locals 객체와 동일합니다.
state.params
섹션 제목: “state.params”타입: Params | undefined
일치하는 라우트와 경로명에서 파생된 라우트 매개변수입니다 (예: [slug].astro 라우트에 대한 { slug: 'my-post' }).
state.status
섹션 제목: “state.status”타입: number
기본값: 200
응답에 대한 HTTP 상태 코드입니다. 렌더링 전에 이 값을 설정하여 응답 상태를 제어할 수 있습니다 (예: state.status = 404).
state.response
섹션 제목: “state.response”타입: Response | undefined
기본값: undefined
렌더링 완료 후 핸들러에 의해 생성된 Response입니다. 이 값은 pages() 및 middleware()에 의해 자동으로 설정되며, 파이프라인 후반부에서 응답을 검사하거나 사용할 수 있게 해줍니다:
import { FetchState, middleware, pages } from "astro/fetch";
export default { async fetch(request: Request): Promise<Response> { const state = new FetchState(request); const response = await middleware(state, (s) => pages(s)); // 이제 state.response는 response와 동일한 객체입니다. return response; },};메서드
섹션 제목: “메서드”state.rewrite()
섹션 제목: “state.rewrite()”타입: (payload: RewritePayload) => Promise<Response>
다른 라우트로 리라이트를 트리거합니다. payload는 경로명 문자열 ('/other-page'), URL, 또는 Request일 수 있습니다.
import { FetchState, middleware, pages } from "astro/fetch";
export default { async fetch(request: Request): Promise<Response> { const state = new FetchState(request); const response = await state.rewrite("/other-page"); return response; },};astro()
섹션 제목: “astro()”타입: (state: FetchState) => Promise<Response>
전체 Astro 파이프라인(세션, 캐시, 리다이렉트, 트레일링 슬래시, 액션, 미들웨어, 페이지, i18n)을 기본 순서로 실행하는 올인원 핸들러입니다. 내부 파이프라인 순서를 변경하지 않고 Astro 실행 전후에 로직을 추가하려는 경우 사용하세요.
import { FetchState, astro } from 'astro/fetch';
export default { async fetch(request: Request): Promise<Response> { const state = new FetchState(request); // 사용자 정의 전처리 const response = await astro(state); // 사용자 정의 후처리 return response; },};actions()
섹션 제목: “actions()”타입: (state: FetchState) => Promise<Response | undefined> | undefined
Astro 액션 (RPC 및 폼 제출)을 처리합니다. RPC 액션의 경우 Response를 반환하고, 폼 액션이나 액션이 아닌 요청의 경우 undefined를 반환합니다. 반환 값을 확인하여 렌더링을 계속할지 결정하세요.
import { actions, FetchState } from "astro/fetch";
export default { async fetch(request: Request): Promise<Response> { const state = new FetchState(request); const actionResponse = await actions(state); if (actionResponse) return actionResponse; // 그렇지 않으면 페이지 렌더링을 계속합니다... },};cache()
섹션 제목: “cache()”타입: (state: FetchState, next: () => Promise<Response>) => Promise<Response>
캐시 공급자 로직으로 렌더링 콜백을 래핑합니다. 런타임 캐싱, CDN 기반 공급자 및 캐시 없는 경우를 처리합니다.
i18n()
섹션 제목: “i18n()”타입: (state: FetchState, response: Response) => Promise<Response>
i18n 설정에 따라 응답을 후처리합니다. 로케일 리다이렉트, 잘못된 로케일에 대한 404 및 대체 라우팅을 처리합니다. 렌더링 후 이를 호출하세요:
import { FetchState, i18n, middleware, pages } from "astro/fetch";
export default { async fetch(request: Request): Promise<Response> { const state = new FetchState(request); const response = await middleware(state, (s) => pages(s)); return i18n(state, response); },};middleware()
섹션 제목: “middleware()”타입: (state: FetchState, next: (state: FetchState) => Promise<Response>) => Promise<Response>
Astro의 미들웨어 체인(src/middleware.ts)을 실행합니다. next 콜백은 체인의 가장 마지막에 호출되어 응답을 생성하며, 일반적으로 pages()를 호출하는 방식으로 동작합니다.
import { FetchState, middleware, pages } from "astro/fetch";
export default { async fetch(request: Request): Promise<Response> { const state = new FetchState(request); const response = await middleware(state, (s) => pages(s)); return response; },};notFound()
섹션 제목: “notFound()”타입: (state: FetchState) => Promise<Response> | undefined
astro@7.4.0
새로운 기능
일치하는 라우트가 없을 때 사전 렌더링된 404.astro를 포함한 사용자 정의 404 페이지를 렌더링합니다. 일치하는 라우트가 있으면 undefined를 반환하고, 요청 경로가 과도하게 인코딩된 경우에는 빈 400 응답을 반환합니다. 호출 측에서는 반환 값을 확인하여 처리를 계속할지 결정할 수 있습니다.
astro()에는 이미 이 처리가 포함되어 있습니다. 대신 개별 핸들러를 조합하는 경우, middleware()와 pages() 앞에 notFound()를 추가하여 일치하는 라우트가 없는 요청에 대해 404 페이지를 렌더링하세요.
import { FetchState, middleware, notFound, pages } from 'astro/fetch';
export default { async fetch(request: Request): Promise<Response> { const state = new FetchState(request); const notFoundResponse = await notFound(state); if (notFoundResponse) return notFoundResponse; return middleware(state, (s) => pages(s)); },};pages()
섹션 제목: “pages()”타입: (state: FetchState) => Promise<Response>
요청을 일치하는 Astro 라우트(페이지, 엔드포인트, 또는 폴백)로 전달합니다. 이는 핵심 렌더링 핸들러로, 대부분의 커스텀 파이프라인에 포함됩니다.
일치하는 라우트가 없는 요청에 대해 사용자 정의 404 페이지를 렌더링하려면 pages() 앞에 notFound()를 추가하세요.
redirects()
섹션 제목: “redirects()”타입: (state: FetchState) => Promise<Response> | undefined
Astro 설정에 정의된 리다이렉트 라우트를 처리합니다. 일치하는 라우트가 리다이렉트인 경우 리다이렉트 Response를 반환하고, 호출 측에서 처리를 계속 진행해야 할 때는 undefined를 반환합니다.
sessions()
섹션 제목: “sessions()”타입: (state: FetchState) => Promise<void> | void
세션 프로바이더를 등록합니다. 세션은 코드가 ctx.session에 접근할 때 지연 생성되며, 요청이 끝날 때 자동으로 저장됩니다. 파이프라인 앞부분(미들웨어가 실행되기 전)에서 이를 호출하세요.
import { FetchState, sessions } from "astro/fetch";
export default { async fetch(request: Request): Promise<Response> { const state = new FetchState(request); await sessions(state); // ...렌더링 파이프라인... },};세션 드라이버가 구성되지 않았거나 세션이 비활성화된 경우에는 이 핸들러가 프로바이더를 등록하지 않습니다. 두 경우 모두 ctx.session은 undefined입니다.
trailingSlash()
섹션 제목: “trailingSlash()”타입: (state: FetchState) => Response | undefined
요청 경로명에 트레일링 슬래시 정규화가 필요한지 확인하고, 필요한 경우 리다이렉트 Response를 반환합니다. 리다이렉트가 필요하지 않을 때는 undefined를 반환합니다.