본문 바로가기
버전: 9.x

응답 캐싱

비공식 베타 번역

이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →

아래 예제들은 사용자에게 가능한 한 빠르게 데이터를 제공하기 위해 Vercel의 에지 캐싱을 활용합니다.

⚠️ 주의 사항 ⚠️

캐싱 시 항상 주의하세요 - 특히 개인 정보를 다룰 때는 더욱 신경 써야 합니다.

배칭(batching)이 기본적으로 활성화되어 있으므로, responseMeta 함수에서 캐시 헤더를 설정하고 개인 데이터가 포함될 수 있는 동시 호출이 없는지 확인하는 것이 좋습니다. 또는 인증 헤더나 쿠키가 존재할 경우 캐시 헤더를 완전히 생략해야 합니다.

splitLink를 사용하여 공개 요청과 비공개/캐싱되지 않아야 할 요청을 분리할 수도 있습니다.

애플리케이션 캐싱

앱에서 SSR을 활성화하면 Vercel 등의 환경에서 로딩 속도가 느려질 수 있지만, SSG를 사용하지 않고도 전체 앱을 정적으로 렌더링할 수 있습니다. 자세한 내용은 이 트위터 스레드를 참조하세요.

예제 코드

pages/_app.tsx
tsx
export default withTRPC({
config(config) {
if (typeof window !== 'undefined') {
return {
url: '/api/trpc',
};
}
const url = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}/api/trpc`
: 'http://localhost:3000/api/trpc';
return {
url,
};
},
ssr: true,
responseMeta(config) {
if (config.clientErrors.length) {
// propagate http first error from API calls
return {
status: config.clientErrors[0].data?.httpStatus ?? 500,
};
}
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
return {
headers: {
'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
},
})(MyApp);
pages/_app.tsx
tsx
export default withTRPC({
config(config) {
if (typeof window !== 'undefined') {
return {
url: '/api/trpc',
};
}
const url = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}/api/trpc`
: 'http://localhost:3000/api/trpc';
return {
url,
};
},
ssr: true,
responseMeta(config) {
if (config.clientErrors.length) {
// propagate http first error from API calls
return {
status: config.clientErrors[0].data?.httpStatus ?? 500,
};
}
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
return {
headers: {
'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
},
})(MyApp);

API 응답 캐싱

모든 쿼리가 일반 HTTP GET 요청이므로 표준 HTTP 헤더를 사용해 응답을 캐싱할 수 있습니다. 이를 통해 응답 속도를 높이고 데이터베이스 부하를 줄이며, API를 수많은 사용자에게 쉽게 확장할 수 있습니다.

responseMeta를 활용한 응답 캐싱

Vercel처럼 stale-while-revalidate 캐시 헤더를 처리할 수 있는 환경에 API를 배포한다고 가정합니다.

server.ts
tsx
import * as trpc from '@trpc/server';
import { inferAsyncReturnType } from '@trpc/server';
import * as trpcNext from '@trpc/server/adapters/next';
export const createContext = async ({
req,
res,
}: trpcNext.CreateNextContextOptions) => {
return {
req,
res,
prisma,
};
};
type Context = inferAsyncReturnType<typeof createContext>;
export function createRouter() {
return trpc.router<Context>();
}
const waitFor = async (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));
export const appRouter = createRouter().query('public.slow-query-cached', {
async resolve({ ctx }) {
await waitFor(5000); // wait for 5s
return {
lastUpdated: new Date().toJSON(),
};
},
});
// Exporting type _type_ AppRouter only exposes types that can be used for inference
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export
export type AppRouter = typeof appRouter;
// export API handler
export default trpcNext.createNextApiHandler({
router: appRouter,
createContext,
responseMeta({ ctx, paths, type, errors }) {
// assuming you have all your public routes with the keyword `public` in them
const allPublic = paths && paths.every((path) => path.includes('public'));
// checking that no procedures errored
const allOk = errors.length === 0;
// checking we're doing a query request
const isQuery = type === 'query';
if (ctx?.res && allPublic && allOk && isQuery) {
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
return {
headers: {
'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
}
return {};
},
});
server.ts
tsx
import * as trpc from '@trpc/server';
import { inferAsyncReturnType } from '@trpc/server';
import * as trpcNext from '@trpc/server/adapters/next';
export const createContext = async ({
req,
res,
}: trpcNext.CreateNextContextOptions) => {
return {
req,
res,
prisma,
};
};
type Context = inferAsyncReturnType<typeof createContext>;
export function createRouter() {
return trpc.router<Context>();
}
const waitFor = async (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));
export const appRouter = createRouter().query('public.slow-query-cached', {
async resolve({ ctx }) {
await waitFor(5000); // wait for 5s
return {
lastUpdated: new Date().toJSON(),
};
},
});
// Exporting type _type_ AppRouter only exposes types that can be used for inference
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export
export type AppRouter = typeof appRouter;
// export API handler
export default trpcNext.createNextApiHandler({
router: appRouter,
createContext,
responseMeta({ ctx, paths, type, errors }) {
// assuming you have all your public routes with the keyword `public` in them
const allPublic = paths && paths.every((path) => path.includes('public'));
// checking that no procedures errored
const allOk = errors.length === 0;
// checking we're doing a query request
const isQuery = type === 'query';
if (ctx?.res && allPublic && allOk && isQuery) {
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
return {
headers: {
'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
}
return {};
},
});