import { NextApiResponse } from 'next'; import { NextResponse } from 'next/server'; type NarrowedResponse = T extends NextResponse ? NextResponse : T extends NextApiResponse ? NextApiResponse : never; export const withStaleWhileRevalidate = ( res: NarrowedResponse, cacheInSeconds = 60, staleCacheInSeconds = 300, ) => { if ('headers' in res) { res.headers.set( 'Cache-Control', `public, s-maxage=${cacheInSeconds}, stale-while-revalidate=${staleCacheInSeconds}`, ); } else { res.setHeader( 'Cache-Control', `public, s-maxage=${cacheInSeconds}, stale-while-revalidate=${staleCacheInSeconds}`, ); } return res; };