Caching Images

Getting to know how the Caching works with Nuxt OG Image.

In cases where you need to generate images at runtime, Nuxt OG Image provides a caching layer to reduce the load on your server.

This caching layer uses SWR caching is enabled by default with a cache time of 72 hours.

Cache Storage

Nitro caching by default will use the memory as a cache storage. This means that if you restart your server, the cache will be cleared.

It's recommended to set a persistent cache storage. This can be done using the runtimeCacheStorage option.

The option takes the same configuration as the Nuxt nitro.storage option. See the Nitro Storage Layer documentation for more details.

For example:

export default defineNuxtConfig({
  ogImage: {
    // cloudflare kv binding example, set your own config
    runtimeCacheStorage: {
      driver: 'cloudflare-kv-binding',
      binding: 'OG_IMAGE_CACHE'
    }
  }
})

Cache Time

You can change the cache time of an image by providing cacheMaxAgeSeconds in milliseconds when defining the image.

defineOgImage({
  cacheMaxAgeSeconds: 30 // 30 seconds
})

Alternatively, you can change the default cache time in your nuxt.config.

nuxt.config.ts
export default defineNuxtConfig({
  ogImage: {
    defaults: {
      cacheMaxAgeSeconds: 60 * 60 * 24 * 7 // 7 days
    }
  }
})

Purging the cache

If you need to purge the cache, you can do so by visiting the OG Image URL appended with a ?purge query param.

For example, to purge the OG Image cache for this page you could visit:

https://nuxtseo.com/__og-image__/image/og-image/guides/cache/og.png?purge

Bypassing the cache

While not recommended, if you prefer to opt-out of caching, you can do so by providing a 0 second cacheMaxAgeSeconds or disabling runtimeCacheStorage.

<script lang="ts" setup>
defineOgImage({
  cacheMaxAgeSeconds: 0 // disable at an individual image level
})
</script>
Did this page help you?