T
tRPC

trying to cache api routes

trying to cache api routes

Rrustclan12/2/2022
Hello. I am using TRPC to make a site which integrates with a third party API. I need to add caching to some of my routes. I have tried to implement a temporary global cache, as seen below. In order to stop rate limits for the third party api.
// export API handler
export default createNextApiHandler({
router: appRouter,
createContext,
responseMeta({ ctx, paths, type, errors }) {
// checking that no procedures errored
const allOk = errors.length === 0;
// checking we're doing a query request
const isQuery = type === "query";
console.log(1);
if (ctx && allOk && isQuery) {
console.log(2);
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 15000;
return {
headers: {
"cache-control": `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
}
return {};
},
});
// export API handler
export default createNextApiHandler({
router: appRouter,
createContext,
responseMeta({ ctx, paths, type, errors }) {
// checking that no procedures errored
const allOk = errors.length === 0;
// checking we're doing a query request
const isQuery = type === "query";
console.log(1);
if (ctx && allOk && isQuery) {
console.log(2);
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 15000;
return {
headers: {
"cache-control": `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
}
return {};
},
});
However, the cache-control header does not get changed, and nothing is cached. Mutiple requests are still made to the third party API. The cache code does run, as the console.log(2) appears in console. Any clue whats wrong?
Rrustclan12/7/2022
bump
AKAlex / KATT 🐱12/7/2022
can you make a reproduction and post an issue? this should work and it has worked in the past, can't confirm or deny if this is a bug without testing it myself
Rrustclan12/8/2022
yes, once I get some spare time i will try to make a reproduction.

Looking for more? Join the community!

T
tRPC

trying to cache api routes

Join Server