### Nuxt 3 Route Cache Configuration with useRouteCache Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/overview/migrating-from-v1.md Demonstrates how to configure route caching in Nuxt 3 using the useRouteCache composable. This example shows setting cacheability and adding tags within a setup script, providing a more declarative approach. ```vue ``` -------------------------------- ### Install nuxt-multi-cache using npm Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/overview/introduction.md This snippet shows how to install the nuxt-multi-cache module using the npm package manager. It's a prerequisite for configuring and using the module in a Nuxt.js project. ```sh npm install --save nuxt-multi-cache ``` -------------------------------- ### Full nuxt-multi-cache Configuration Example Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/overview/configuration.md This comprehensive configuration example showcases all available options for the nuxt-multi-cache module. It demonstrates enabling component, data, and CDN caching, disabling route caching, and configuring the Cache Management API with custom settings. ```typescript export default defineNuxtConfig({ modules: ['nuxt-multi-cache'], multiCache: { // Component cache is enabled. component: { enabled: true, }, // Data cache enabled. data: { enabled: true, }, // Route cache is disabled. But because the `route` property is set the // useRouteCache composable is still added to the build, it just doesn't // cache. route: { enabled: false, }, // CDN Cache Control Headers feature. cdn: { enabled: true, // Set custom cache control for Cloudflare. cacheControlHeader: 'CDN-Cache-Control', // Set custom cache tags header for Cloudflare. cacheTagHeader: 'Cache-Tag', }, // Cache Management API. api: { enabled: true, // Use a different prefix for the API endpoints. prefix: '/api/nuxt-multi-cache', // Disable authorization check on the API. authorization: false, // Cache tag invaldiations should be buffered for 5 minutes before the // cache items are actually purged. cacheTagInvalidationDelay: 300000, // 5 minutes }, // Log detailled debugging messages, e.g. when items are cached or returned from cache. debug: true, // Disable logging a cache overview when the app starts. disableCacheOverviewLogMessage: true, }, }) ``` -------------------------------- ### Compress Specific Routes with h3-fast-compression (TypeScript) Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/advanced/route-cache-with-compression.md This example demonstrates how to compress specific routes using the `h3-fast-compression` library within a Nuxt application. It utilizes the `beforeResponse` Nitro hook to conditionally apply compression based on the request URL, excluding paths starting with '/no-compression'. ```typescript import { useCompression } from 'h3-fast-compression' import { getRequestURL } from 'h3' import { defineNitroPlugin } from 'nitropack/runtime' export default defineNitroPlugin((nitro) => { nitro.hooks.hook('beforeResponse', async (event, response) => { const url = getRequestURL(event) // Prevent some paths from being compressed. if (url.pathname.startsWith('/no-compression')) { return } await useCompression(event, response) }) }) ``` -------------------------------- ### Full useCachedAsyncData example with cache options Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/composables/useCachedAsyncData.md Provides a comprehensive example of useCachedAsyncData, showcasing server-side caching with a specific age and tags, client-side caching, and data transformation. This allows for fine-grained control over cache duration and invalidation. ```typescript const { data: users } = await useCachedAsyncData( 'all-users', () => $fetch('/api/users'), { // Cache for an hour on the server. serverMaxAge: 60 * 60, // Add a tag to make it possible to invalidate the cache item. serverCacheTags: ['users-list'], // Allow the client/browser to cache it for 10 minutes. clientMaxAge: 10 * 60, // Transform the data. The transformed data will be put in the cache. transform: function (data) { return data.users }, }, ) ``` -------------------------------- ### RenderCacheable Component Props Example (Vue) Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/features/component-cache.md An example showcasing the various props available for the RenderCacheable component, including tag, async-data-keys, cache-tags, cache-key, and no-cache. ```vue ``` -------------------------------- ### Configure Custom Cache Storage Drivers (e.g., Redis) Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/overview/server-options.md This example shows how to configure custom storage drivers for different cache types (data and component) using `unstorage` with the Redis driver. It allows specifying a custom base path for each cache type. ```typescript import { defineMultiCacheOptions } from 'nuxt-multi-cache/server-options' import redisDriver from 'unstorage/drivers/redis' export default defineMultiCacheOptions(() => { return { data: { storage: { driver: redisDriver({ base: 'data:', }), }, }, component: { storage: { driver: redisDriver({ base: 'component:', }), }, }, } }) ``` -------------------------------- ### Full Example: Caching Component Data with useComponentCache (Vue) Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/composables/useComponentCache.md This Vue example showcases the full integration of useComponentCache within a Nuxt application. It fetches user data using useAsyncData and then configures the component cache to include the user data payload and associated cache tags. This ensures that both the component markup and its relevant data are cached effectively. ```vue ``` -------------------------------- ### Configure Route Caching in Nuxt Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/README.md Illustrates how to configure route caching for pages or API responses using the `useRouteCache` composable. This example shows how to mark a route as cacheable, set its maximum age, and associate cache tags for invalidation purposes. ```typescript useRouteCache((route) => { // Mark the page as cacheable for 1 hour and add a cache tag. route.setCacheable().setMaxAge(3600).addTags(['page:2']) }) ``` -------------------------------- ### Implement a Dynamic Cache Key Prefix per Request Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/overview/server-options.md This example demonstrates how to dynamically determine the cache key prefix for each request. It uses a function that receives the H3Event and returns a Promise resolving to the prefix, allowing for logic based on request headers like `Accept-Language`. ```typescript import { defineMultiCacheOptions } from 'nuxt-multi-cache/server-options' import { H3Event, getHeader } from 'h3' function getCacheKeyPrefix(event: H3Event): string { const acceptLanguage = getHeader(event, 'accept-language') || '' if (acceptLanguage.includes('de')) { return 'de' } return 'en' } export default defineMultiCacheOptions(() => { return { cacheKeyPrefix: (event) => { return Promise.resolve(getCacheKeyPrefix(event)) }, } }) ``` -------------------------------- ### Return Value of useDataCacheCallback Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/composables/useDataCacheCallback.md Shows a complete example of using useDataCacheCallback, including setting cache tags and max age, and logging the returned data. The example demonstrates fetching user data and returning it, which will then be cached. ```typescript const data = await useDataCacheCallback('users', async (cache) => { if (cache && import.meta.server) { cache.addTags('users').setMaxAge('1h') } return { firstName: 'John', lastName: 'Wayne', } }) console.log(data) // [{ firstName: "John", lastName: "Wayne" }] ``` -------------------------------- ### Configure Cacheability with DataCacheHelper Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/composables/useDataCacheCallback.md Illustrates how to use the cache helper object passed to the useDataCacheCallback. This example shows setting cache tags, maximum age, and stale-if-error duration. The helper is only available on the server, so checks like `import.meta.server` are crucial. ```typescript const data = await useDataCacheCallback( 'data-cache-callback-key', function (helper) { if (helper && import.meta.server) { // Add cache tags. helper.addTags(['one', 'two', 'three']) // Revalidate after 4 hours. helper.setMaxAge('4h') // Allows the composable to return a stale value for up to one day if // this callback throws an error. helper.setStaleIfError('1d') } return { timestamp: Date.now(), } }, ) ``` -------------------------------- ### Purge Component Cache via API Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/README.md Provides an example using `curl` to interact with the Nuxt Multi Cache API for purging component cache entries. It shows how to send a POST request with a specific token and data payload to target components for invalidation. ```bash curl -X POST -i \ -H "x-nuxt-multi-cache-token: hunter2" \ --data '["Navbar::de--chf"]' \ http://localhost:3000/__nuxt_multi_cache/purge/component ``` -------------------------------- ### Token-Based API Authorization (Fetch and Curl) Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/features/api.md Demonstrates how to authorize API requests using a token in the 'x-nuxt-multi-cache-token' header. Examples are provided for both fetch API and curl. ```typescript fetch('http://localhost:3000/__nuxt_multi_cache/purge/component', { method: 'POST', headers: { // [!code focus] 'x-nuxt-multi-cache-token': 'hunter2', // [!code focus] }, // [!code focus] body: JSON.stringify(['Navbar::de--chf']) }) ``` ```bash curl -X POST -i \ -H "Content-Type: application/json" \ -H "x-nuxt-multi-cache-token: hunter2" \ // [!code focus] --data '["Navbar::de--chf"]' \ http://localhost:3000/__nuxt_multi_cache/purge/component ``` -------------------------------- ### Add Cache Tags for Invalidation (Bash) Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/composables/useRouteCache.md This example demonstrates how to add cache tags to a cache entry using the `addTags` method. It also shows a `curl` command to purge cache items associated with a specific tag, such as 'language:de'. ```bash curl -X POST -i -H "Content-Type: application/json" \ --data '["language:de"]' \ http://localhost:3000/__nuxt_multi_cache/purge/tags ``` -------------------------------- ### Set CDN Headers in Page (Vue/TypeScript) Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/features/cdn-cache-control.md Shows how to apply CDN headers directly within a Vue component's script setup using `useCDNHeaders`. This example sets a 'maxAge' of 3600 for the page's response. ```vue ``` -------------------------------- ### Get Cache Statistics Source: https://context7.com/dulnan/nuxt-multi-cache/llms.txt Retrieves statistics for the component cache, providing insights into cache usage and performance. ```APIDOC ## GET /__nuxt_multi_cache/stats/component ### Description Retrieves statistics for the component cache, providing insights into cache usage and performance. ### Method GET ### Endpoint http://localhost:3000/__nuxt_multi_cache/stats/component ### Parameters No parameters required. ### Response #### Success Response (200) - **status** (string) - Indicates the status of the request ('OK'). - **rows** (array) - An array of objects containing cache statistics. - **total** (integer) - The total number of cache entries. #### Response Example ```json { "status": "OK", "rows": [...], "total": 25 } ``` ``` -------------------------------- ### Configure Route Cache with useRouteCache (TypeScript) Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/composables/useRouteCache.md This example demonstrates the basic usage of the useRouteCache composable to configure caching options. It sets the maximum age for the cache entry, marks the response as cacheable, and adds a tag for potential invalidation. ```typescript useRouteCache((helper) => { helper.setMaxAge(3600).setCacheable().addTags(['page:1']) }) ``` -------------------------------- ### Fetch Cached Components List (Bash) Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/features/api.md Retrieves a list of all cached components using curl. This command-line utility sends a GET request to the Nuxt Multi Cache stats endpoint, including the necessary authentication token. ```bash curl -i \ -H "x-nuxt-multi-cache-token: hunter2" \ http://localhost:3000/__nuxt_multi_cache/stats/component ``` -------------------------------- ### useCachedAsyncData with client-side caching duration Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/composables/useCachedAsyncData.md Illustrates how to configure client-side caching for a specific duration using `clientMaxAge`. This example caches the request for 10 minutes on the client while using midnight caching on the server. ```typescript const { data } = await useCachedAsyncData( 'all-users', () => $fetch('/api/users'), { // Cache this request for 10 minutes. clientMaxAge: 60 * 10, serverMaxAge: 'midnight', }, ) ``` -------------------------------- ### Create Custom In-Memory Cache Driver for Nuxt Multi Cache Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/advanced/cache-backend.md This example shows how to create a custom in-memory cache driver for Nuxt Multi Cache by recreating the default storage behavior. It defines functions for cache operations like hasItem, getItem, setItem, removeItem, getKeys, clear, and dispose. This is useful for development or specific use cases where an external cache is not needed. ```typescript import { defineMultiCacheOptions } from 'nuxt-multi-cache/server-options' import { defineDriver } from 'unstorage' const customDriver = defineDriver((_opts) => { let cache = {} return { hasItem(key: string) { return !!cache[key] }, getItem(key: string) { return cache[key] }, setItem(key, value) { return (cache[key] = value) }, removeItem(key) { cache[key] = undefined }, getKeys() { return Object.keys(cache) }, clear() { cache = {} }, dispose() {}, } }) export default defineMultiCacheOptions(() => { return { component: { storage: { driver: customDriver(), }, }, } }) ``` -------------------------------- ### Cache Route in Nuxt Server Handler with useRouteCache Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/features/route-cache.md Shows how to apply route caching within a Nuxt server handler using the `useRouteCache` composable. This example sets the route as cacheable and returns a delayed result, demonstrating that subsequent requests will be served from cache. ```typescript import { useRouteCache } from '#imports' const getResult = function () { return new Promise((resolve) => { setTimeout(() => { resolve({ data: 'I am very delayed.' }) }, 1000) }) } export default defineEventHandler((event) => { useRouteCache((helper) => { helper.setCacheable() }, event) return getResult() }) ``` -------------------------------- ### Accessing Cache Instances in Nitro (TypeScript) Source: https://context7.com/dulnan/nuxt-multi-cache/llms.txt Shows how to access and manipulate cache instances directly within Nitro server handlers using the `useMultiCacheApp` composable. Allows clearing route cache, getting data cache keys, and checking/getting/removing specific items. ```typescript export default defineEventHandler(async (event) => { const multiCache = useMultiCacheApp() // Clear the entire route cache await multiCache.cache.route?.storage.clear() // Get all data cache keys const dataCacheKeys = await multiCache.cache.data?.storage.getKeys() // Check if a specific item exists const hasItem = await multiCache.cache.data?.storage.hasItem('weather') // Get a specific item const item = await multiCache.cache.data?.storage.getItem('weather') // Remove a specific item await multiCache.cache.data?.storage.removeItem('weather') // Access server options and config const options = multiCache.serverOptions const config = multiCache.config return { cachedKeys: dataCacheKeys, hasWeatherCache: hasItem, } }) ``` -------------------------------- ### Fetch Data with Cache Interceptor in Nuxt Page Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/composables/useCacheAwareFetchInterceptor.md Illustrates how to use the `useCacheAwareFetchInterceptor` within a Nuxt page's script setup to fetch data from an API. It also shows how to define cache headers for the page itself, demonstrating the merging of cache control information. ```vue ``` -------------------------------- ### Merge Cache Control from Response in Nitro Server Context Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/composables/useCDNHeaders.md This example shows how to use useCDNHeaders in a Nitro server context to merge cache control information from a fetch response. It retrieves the event object, fetches data, and then uses the mergeFromResponse method of the CDN helper to apply cache settings from the response. The result is then parsed as JSON. ```typescript const event = useRequestEvent() const { data } = await useAsyncData(() => { return $fetch.raw('/api/load-users').then((response) => { useCDNHeaders((cdn) => { cdn.mergeFromResponse(response) }, event) return response.json() }) }) ``` -------------------------------- ### Conditional Caching Middleware in TypeScript Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/advanced/route-and-cdn.md This middleware example demonstrates how to conditionally apply route caching and CDN headers based on the request URL. It uses `useCDNHeaders` and `useRouteCache` to control caching behavior for different paths. The `getRequestURL` function from 'h3' is used to extract the request URL. ```typescript import { useCDNHeaders } from '#imports' import { getRequestURL } from 'h3' export default defineEventHandler((event) => { const url = getRequestURL(event) if (url.pathname.startsWith('/dashboard')) { // Page will be cached locally in the route cache. useCDNHeaders((v) => v.private()) useRouteCache((v) => v.setCacheable()) } else { // Page will be cached on CDN. useCDNHeaders((v) => v.public()) useRouteCache((v) => v.setUncacheable()) } }) ``` -------------------------------- ### CDN Header Configuration Source: https://context7.com/dulnan/nuxt-multi-cache/llms.txt Reference for configuring CDN-specific headers for cache control and cache tagging. ```APIDOC ## CDN Header Configuration Reference ### Description Configuration for common CDN providers to manage cache control and cache tags. ### Configuration Options - `cdn.enabled` (boolean): Enables or disables CDN integration. - `cdn.cacheControlHeader` (string): Specifies the header used for cache control directives (e.g., 'Surrogate-Control', 'CDN-Cache-Control'). - `cdn.cacheTagHeader` (string): Specifies the header used for cache tags (e.g., 'Surrogate-Key', 'Cache-Tag'). ### Example Configurations #### Fastly ```typescript export default defineNuxtConfig({ multiCache: { cdn: { enabled: true, cacheControlHeader: 'Surrogate-Control', cacheTagHeader: 'Surrogate-Key', }, }, }) ``` #### Cloudflare ```typescript export default defineNuxtConfig({ multiCache: { cdn: { enabled: true, cacheControlHeader: 'CDN-Cache-Control', cacheTagHeader: 'Cache-Tag', }, }, }) ``` #### Akamai ```typescript export default defineNuxtConfig({ multiCache: { cdn: { enabled: true, cacheControlHeader: 'Edge-Control', cacheTagHeader: 'Edge-Cache-Tag', }, }, }) ``` #### Varnish ```typescript export default defineNuxtConfig({ multiCache: { cdn: { enabled: true, cacheControlHeader: 'X-Cache-Control', cacheTagHeader: 'X-Cache-Tags', }, }, }) ``` ``` -------------------------------- ### Programmatic Cache Purging (TypeScript) Source: https://context7.com/dulnan/nuxt-multi-cache/llms.txt Demonstrates programmatic cache invalidation using the fetch API. Includes functions to purge a specific product cache by tag and to purge all caches. ```typescript // Programmatic API usage with fetch async function purgeProductCache(productId: string) { await fetch('http://localhost:3000/__nuxt_multi_cache/purge/tags', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-nuxt-multi-cache-token': process.env.CACHE_API_TOKEN, }, body: JSON.stringify([`product:${productId}`]), }) } async function purgeAllCaches() { await fetch('http://localhost:3000/__nuxt_multi_cache/purge/all', { method: 'POST', headers: { 'x-nuxt-multi-cache-token': process.env.CACHE_API_TOKEN, }, }) } ``` -------------------------------- ### Get Cache Statistics Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/features/api.md Retrieves statistics about the cache, such as the number of items or memory usage. This endpoint provides insights into the current state of the cache. ```APIDOC ## GET /__nuxt_multi_cache/stats ### Description Retrieves statistics about the cache. ### Method GET ### Endpoint `http://localhost:3000/__nuxt_multi_cache/stats` ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **stats** (object) - An object containing cache statistics (details depend on implementation). #### Response Example ```json { "stats": { "itemCount": 150, "memoryUsage": "10MB" } } ``` ``` -------------------------------- ### Purge All Cache Items (Fetch and Curl) Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/features/api.md API endpoint to purge all items from all caches. Requires token-based authorization. Examples provided for fetch and curl. ```typescript fetch('http://localhost:3000/__nuxt_multi_cache/purge/all', { method: 'POST', headers: { 'x-nuxt-multi-cache-token': 'hunter2', }, }) ``` ```bash curl -X POST -i \ -H "x-nuxt-multi-cache-token: hunter2" \ http://localhost:3000/__nuxt_multi_cache/purge/all ``` -------------------------------- ### Get Cache Statistics (cURL) Source: https://context7.com/dulnan/nuxt-multi-cache/llms.txt Retrieves statistics for the component cache. Requires a secret token for authorization and returns status, rows, and total count of cache entries. ```bash curl \ -H "x-nuxt-multi-cache-token: your-secret-token" \ http://localhost:3000/__nuxt_multi_cache/stats/component ``` -------------------------------- ### CDN Header Configuration - Fastly (TypeScript) Source: https://context7.com/dulnan/nuxt-multi-cache/llms.txt Configures Nuxt Multi Cache for Fastly CDN integration. Specifies `Surrogate-Control` for cache directives and `Surrogate-Key` for cache tags. ```typescript // Fastly configuration export default defineNuxtConfig({ multiCache: { cdn: { enabled: true, cacheControlHeader: 'Surrogate-Control', cacheTagHeader: 'Surrogate-Key', }, }, }) ``` -------------------------------- ### Get All Cached Components Source: https://github.com/dulnan/nuxt-multi-cache/blob/main/docs/features/api.md Retrieves a list of all components currently stored in the cache, along with their associated data. This endpoint is useful for monitoring and debugging cache usage. ```APIDOC ## GET /__nuxt_multi_cache/stats/component ### Description Retrieves a list of all components currently stored in the cache, along with their associated data. This endpoint is useful for monitoring and debugging cache usage. ### Method GET ### Endpoint /__nuxt_multi_cache/stats/component ### Parameters #### Query Parameters - **x-nuxt-multi-cache-token** (string) - Required - Authentication token for accessing cache statistics. ### Request Example ```bash curl -i \ -H "x-nuxt-multi-cache-token: hunter2" \ http://localhost:3000/__nuxt_multi_cache/stats/component ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the request (e.g., "OK"). - **rows** (array) - An array of objects, where each object represents a cached component. - **key** (string) - The unique identifier for the cached component. - **data** (string | object) - The cached data for the component. This can be a string (e.g., HTML) or an object containing structured data. #### Response Example ```json { "status": "OK", "rows": [ { "key": "RandomNumber", "data": "

Component with random number

RANDOM_NUMBER__686204309__
" }, { "key": "Navbar:navbar", "data": { "payload": { "navbar": [ { "userId": "39a2cbd1-5355-42ee-b519-a378ac12ecf4", "username": "Morris.Sipes93", "email": "Eda_Barton@hotmail.com", "avatar": "https://cloudflare-ipfs.com/ipfs/Qmd3W5DuhgHirLHGVixi6V76LhCkZUz6pnFt5AJBiyvHye/avatar/1116.jpg", "password": "KQ6UY3mgK6VZsJd", "birthdate": "1948-01-06T21:31:06.050Z", "company": "Ward Group", "registeredAt": "2022-01-06T19:41:51.910Z" } ] }, "data": "