Cache API

Nitro provides a powerful caching system built on top of the storage layer.

It stores the data in the cache mountpoint.

  • In development, it will use the FS driver writting to .nitro/cache or .nuxt/cache if using Nuxt.
  • In production, it will use the memory driver by default.

To overwrite the production storage, set the cache mountpoint using the storage option:

nitro.config.ts
import { defineNitroConfig } from "nitropack/config";

export default defineNitroConfig({
  storage: {
    cache: {
      driver: 'redis',
      /* redis connector options */
    }
  }
})
nuxt.config.ts
export default defineNuxtConfig({
  nitro: {
    storage: {
      cache: {
        driver: 'redis',
        /* redis connector options */
      }
    }
  }
})

To overwrite the cache mountpoint in development, use the devStorage option to add the cache mountpoint.

Usage

Router Handler
// Cache an API handler
export default cachedEventHandler((event) => {
  // My event handler
}, options);
Function
const myFn = cachedFunction(() => {
  // My function
}, options);

Examples

If you come from Nuxt, all the examples below should be placed inside the server/ directory.

Route Handler

Cache a route with stale-while-revalidate behavior for 10 second:

routes/cached.ts
export default cachedEventHandler(async () => {
  return `Response generated at ${new Date().toISOString()}`;
}, {
  swr: true, maxAge: 10
});

The response will be cached for 10 second and a stale value will be sent to the client while the cache is being updated in the background.

The cached answer will be store in development inside .nitro/cache/handlers/_/*.json.

Function

Cache for 1 hour the result of a function fetching the GitHub stars for a repository:

utils/github.ts
export const cachedGHStars = cachedFunction(async (repo: string) => {
  const data: any = await $fetch(`https://api.github.com/repos/${repo}`)

  return data.stargazers_count
}, {
  maxAge: 60 * 60,
  name: 'ghStars',
  getKey: (repo: string) => repo
})
api/stars/[...repo
export default eventHandler(async (event) => {
  const repo = event.context.params.repo
  const stars = await cachedGHStars(repo).catch(() => 0)

  return { repo, stars }
})

The stars will be cached in development inside .nitro/cache/functions/ghStars/<owner>/<repo>.json with value being the number of stars.

{"expires":1677851092249,"value":43991,"mtime":1677847492540,"integrity":"ZUHcsxCWEH"}

Route Rules

This feature enables you to add caching routes based on a glob pattern directly in the main configuration file.

This feature is still experimental and may evolve in the future.

Cache all the blog routes for 1 hour with stale-while-revalidate behavior:

nitro.config.ts
import { defineNitroConfig } from "nitropack/config";

export default defineNitroConfig({
  routeRules: {
    "/blog/**": {
      swr: 60 * 60,
      // or
      cache: {
        maxAge: 60 * 60
      }
    },
  },
});
nuxt.config.ts
export default defineNuxtConfig({
  routeRules: {
    "/blog/**": {
      swr: 60 * 60,
      // or
      cache: {
        maxAge: 60 * 60
      }
    },
  }
});

If we want to use a custom storage mountpoint, we can use the base option. Let's store our cache result for the blog routes in a Redis storage for production:

nitro.config.ts
import { defineNitroConfig } from "nitropack/config";

export default defineNitroConfig({
  storage: {
    redis: {
      driver: "redis",
      url: "redis://localhost:6379",
    },
  },
  routeRules: {
    "/blog/**": {
      swr: 60 * 60,
      cache: {
        base: "redis",
      },
    },
  },
});
nuxt.config.ts
export default defineNuxtConfig({
  nitro: {
    storage: {
      redis: {
        driver: "redis",
        url: "redis://localhost:6379",
      },
    },
  },
  routeRules: {
    "/blog/**": {
      swr: 60 * 60,
      cache: {
        base: "redis",
      },
    },
  },
});

Options

The cachedEventHandler and cachedFunction functions accept the following options:

  • name: Handler name.
    • Type: String
    • Default: Guessed from function name if not provided and fallback to _ otherwise.
  • group: Part of cache name. Useful to organize cache storage.
    • Type: String
    • Default: 'nitro/handlers' for handlers and 'nitro/functions' for functions.
  • getKey: A function that accepts the same arguments of the function and returns a cache key (String).
    • Type: Function
    • Default: If not provided, a built-in hash function will be used.
  • integrity: A value that invalidates the cache when changed.
    • Type: String
    • Default: Computed from function code, used in development to invalidate the cache when the function code changes.
  • maxAge: Maximum age that cache is valid in seconds.
    • Type: Number
    • Default: 1 (second).
  • staleMaxAge: Maximum age that a stale cache is valid in seconds. If set to -1 a stale value will still be sent to the client, while updating the cache in the background.
    • Type: Number
    • Default: 0 (disabled).
  • swr: Enable stale-while-revalidate behavior.
    • Default: true
  • base: Name of the storage mountpoint to use for caching.
    • Default: cache.
  • shouldInvalidateCache: A function that returns a Boolean to invalidate the current cache and create a new one.
    • Type: Function
  • shouldBypassCache: A function that returns a boolean to bypass the current cache without invalidating the existing entry.
    • Type: Function