cached-middleware-fetch-next
Version:
A Next.js fetch wrapper for edge middleware that uses Vercel Runtime Cache as its caching backend
69 lines (66 loc) • 2.39 kB
TypeScript
/**
* Extended fetch options that mirror Next.js fetch API
*
* The returned Response will include cache status headers:
* - X-Cache-Status: 'HIT' | 'MISS' | 'STALE'
* - X-Cache-Age: Age of cached data in seconds (0 for fresh/miss)
* - X-Cache-Expires-In: Time until cache expires in seconds (if applicable)
*/
interface CachedFetchOptions extends Omit<RequestInit, 'cache'> {
/**
* Configure how the request should interact with the cache.
* - 'auto no cache' (default): Fetches on every request in development, once during build for static routes
* - 'no-store': Always fetches from the remote server
* - 'force-cache': Looks for a match in cache first, fetches if not found or stale
*/
cache?: 'auto no cache' | 'no-store' | 'force-cache';
/**
* Next.js specific options
*/
next?: {
/**
* Set the revalidation time for SWR-style caching (in seconds)
* - false: Never revalidate (cache indefinitely)
* - 0: Prevent caching
* - number: Revalidate after specified seconds
*/
revalidate?: false | 0 | number;
/**
* Set the absolute expiry time for cache entries (in seconds)
* If not specified, defaults to 24 hours (86400 seconds)
* Must be greater than revalidate time
*/
expires?: number;
/**
* Set cache tags for manual cache invalidation
* Note: Tag-based revalidation is not automatically supported,
* but tags can be used with Vercel's cache APIs for manual clearing
*/
tags?: string[];
/**
* Optional prefix for cache key generation
*/
fetchCacheKeyPrefix?: string;
};
}
/**
* Cache entry structure
*/
interface CacheEntry {
data: any;
headers: Record<string, string>;
status: number;
statusText: string;
timestamp: number;
revalidateAfter?: number;
expiresAt?: number;
tags?: string[];
isBinary?: boolean;
contentType?: string;
}
/**
* A fetch wrapper that uses Vercel Runtime Cache for caching
* Mimics Next.js Data Cache API for use in edge middleware
*/
declare function cachedFetch(input: RequestInfo | URL, init?: CachedFetchOptions): Promise<Response>;
export { type CacheEntry, type CachedFetchOptions, cachedFetch, cachedFetch as default, cachedFetch as fetch };