Plugins

LRU Cache

Overview

This plugin integrates an LRU (Least Recently Used) Cache using the lru-cache library into a Nuxt 3 application. It is useful for storing frequently accessed data in memory to improve performance and reduce redundant computations or API calls.


Features

  • In-memory caching using Least Recently Used strategy.
  • Automatically evicts least used entries when the limit is reached.
  • Time-based eviction (TTL).
  • Globally available in the Nuxt app via nuxtApp.$lruCache.

Plugin Source

export default defineNuxtPlugin(async () => {
  const { LRUCache } = await import("lru-cache");

  // Configure the LRU cache
  const lruCache = new LRUCache({
    max: 500, // Maximum items the cache can hold
    ttl: 1000 * 60 * 10, // Time-to-live (10 minutes)
  });

  // Provide the cache globally
  return {
    provide: {
      lruCache,
    },
  };
});

Configuration

OptionDescription
maxMaximum number of items the cache can store (default: 500)
ttlTime-to-live for each item in milliseconds (default: 10 minutes)

You can customize these values based on your app’s memory constraints and use case.


Usage

In your components or services:

const { $lruCache } = useNuxtApp();

// Set a value
$lruCache.set('key', 'value');

// Get a value
const value = $lruCache.get('key');

// Delete a key
$lruCache.delete('key');

// Check if key exists
const exists = $lruCache.has('key');

Use Cases

  • Caching results of expensive function calls
  • Temporary storage of API responses
  • Preventing duplicate requests for the same data
  • Memoizing computed values across components

Notes

  • This plugin runs client-side only unless explicitly included in the server build.
  • lru-cache handles automatic eviction, so you don’t need to manage cleanup manually.
  • Use responsibly to avoid memory leaks in long-running sessions.

Copyright © 2026