惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
WordPress大学
WordPress大学
T
Tailwind CSS Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
Secure Thoughts
博客园 - 【当耐特】
Know Your Adversary
Know Your Adversary
NISL@THU
NISL@THU
博客园 - 司徒正美
Last Week in AI
Last Week in AI
C
Cybersecurity and Infrastructure Security Agency CISA
P
Privacy & Cybersecurity Law Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
B
Blog
The GitHub Blog
The GitHub Blog
小众软件
小众软件
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Spread Privacy
Spread Privacy
Martin Fowler
Martin Fowler
博客园 - 叶小钗
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Tenable Blog
S
Securelist
博客园 - 三生石上(FineUI控件)
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
罗磊的独立博客
T
Threat Research - Cisco Blogs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
F
Full Disclosure
Cloudbric
Cloudbric
The Cloudflare Blog
Y
Y Combinator Blog
Hugging Face - Blog
Hugging Face - Blog
Microsoft Azure Blog
Microsoft Azure Blog
H
Hacker News: Front Page
腾讯CDC
L
Lohrmann on Cybersecurity
C
CERT Recently Published Vulnerability Notes
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
TaoSecurity Blog
TaoSecurity Blog
I
Intezer
The Last Watchdog
The Last Watchdog
G
GRAHAM CLULEY
Google Online Security Blog
Google Online Security Blog
T
The Blog of Author Tim Ferriss

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Cache Everything: Advanced Caching Strategies in Vue 3 & Nuxt 4
Parsa Jiravand · 2026-05-25 · via DEV Community

Table of Contents

  1. Layer 1 — Reactive Variable Caching (Vue Reactivity System)
  2. Layer 2 — Computed Property Caching & Memoization
  3. Layer 3 — Composable-Level Data Caching
  4. Layer 4 — Nuxt Data Fetching Cache (useFetch / useAsyncData)
  5. Layer 5 — Server Route Caching with Nitro
  6. Layer 6 — Route-Level Cache Rules (routeRules)
  7. Layer 7 — HTTP & Browser Caching Headers
  8. Layer 8 — Pinia as a Client-Side Cache Store
  9. Quick Reference Cheat Sheet

Layer 1 — Reactive Variable Caching {#layer-1}

Before we talk about network caches, let's talk about reactivity overhead — because creating unnecessary deep reactive proxies is a silent performance killer in large Vue apps.

shallowRef and shallowReactive for large data

By default, ref() and reactive() deeply proxy every nested property. For large API responses, table rows, or chart datasets this is wasteful — you're paying to track changes you'll never make.

// ❌ Deep reactive — tracks every nested field on every item
const rows = ref<Row[]>([])

// ✅ Shallow reactive — triggers only when the array reference changes
const rows = shallowRef<Row[]>([])

async function loadPage(page: number) {
  rows.value = await $fetch(`/api/rows?page=${page}`)
  // Replacing the whole reference triggers reactivity cheaply
}

Rule: Use shallowRef when you replace the whole object wholesale (pagination, API responses). Use deep ref only when you mutate individual nested properties.

Object.freeze for truly static data

If your data never changes after fetch — config objects, lookup tables, static lists — freeze it entirely to opt out of Vue's proxy system:

const countries = shallowRef(Object.freeze(await $fetch('/api/countries')))
// Vue won't bother tracking any of this — zero reactivity overhead

v-once and v-memo in templates

<!-- Renders once and never re-renders, even if parent does -->
<HeavyStaticChart v-once :data="staticConfig" />

<!-- Re-renders only when userId changes -->
<UserCard
  v-memo="[userId]"
  :user="user"
  :metadata="metadata"
/>

v-memo is especially powerful inside v-for loops with large stable lists.


Layer 2 — Computed Property Caching & Memoization {#layer-2}

Vue's computed() is itself a cache — it stores its last result and only recomputes when a tracked dependency changes. But there are patterns that break this guarantee.

Keep computed pure

// ❌ Breaks caching — Math.random() makes it non-deterministic
const discountedPrice = computed(() => price.value * Math.random())

// ✅ Pure — Vue can cache this safely
const discountedPrice = computed(() => price.value * 0.9)

Chain computed for granular invalidation

Instead of one giant computed with many dependencies, chain smaller ones. Each step caches independently:

const rawOrders = shallowRef<Order[]>([])

// Each computed caches its own slice of the pipeline
const paidOrders = computed(() =>
  rawOrders.value.filter(o => o.status === 'paid')
)

const sortedOrders = computed(() =>
  [...paidOrders.value].sort((a, b) => b.total - a.total)
)

const topTenOrders = computed(() => sortedOrders.value.slice(0, 10))

Changing rawOrders recomputes all three. But if only sortedOrders's sort key changes, only sortedOrders and topTenOrders invalidate.

Manual memoization for argument-based caching

computed doesn't accept arguments. For functions that take parameters, build a Map-based memo:

function useMemoized<A, R>(fn: (arg: A) => R) {
  const cache = new Map<A, R>()
  return (arg: A): R => {
    if (cache.has(arg)) return cache.get(arg)!
    const result = fn(arg)
    cache.set(arg, result)
    return result
  }
}

// Usage in a composable
const getProductTax = useMemoized((productId: string) => {
  return expensiveTaxCalculation(productId)
})


Layer 3 — Composable-Level Data Caching {#layer-3}

A composable defined outside the component instance acts as a singleton module-level cache — data persists across component mounts and unmounts.

// composables/useProductCatalog.ts

// Defined at module scope — shared across all consumers
const catalog = shallowRef<Product[]>([])
const lastFetched = ref<number | null>(null)
const TTL = 5 * 60 * 1000 // 5 minutes

export function useProductCatalog() {
  async function fetchIfStale() {
    const now = Date.now()
    if (lastFetched.value && now - lastFetched.value < TTL) {
      return // Still fresh, use the cache
    }
    catalog.value = await $fetch('/api/products')
    lastFetched.value = now
  }

  return { catalog, fetchIfStale }
}

Any component calling useProductCatalog() shares the same catalog ref. The network request fires once and the result is reused until TTL expires.

Nuxt note: Be aware that module-level state is shared across all SSR requests on the server. Use useState() or useNuxtApp() for server-safe singleton state in Nuxt.


Layer 4 — Nuxt Data Fetching Cache (useFetch / useAsyncData) {#layer-4}

This is where Nuxt 4 brings the most significant improvements over Nuxt 3.

How the built-in cache works

useFetch and useAsyncData key-deduplicate requests. Multiple components calling the same key share one data, error, and status ref:

// components/UserProfile.vue AND components/UserBadge.vue
// Both call this — only ONE network request fires
const { data: user } = await useAsyncData('user-123', () =>
  $fetch('/api/users/123')
)

In Nuxt 4, data fetched on the server is forwarded to the client in the payload, eliminating the double-fetch (server + hydration) problem entirely.

Reactive keys for dynamic data

// pages/users/[id].vue
const route = useRoute()

// computed key — Nuxt refetches when route.params.id changes
const userId = computed(() => `user-${route.params.id}`)

const { data: user } = await useAsyncData(
  userId,
  () => $fetch(`/api/users/${route.params.id}`)
)

In Nuxt 4, changing userId automatically purges the old cached data and triggers a fresh fetch.

getCachedData — custom client-side cache logic

This is the most underused feature. getCachedData lets you intercept the cache lookup and decide whether to return stale data or trigger a fresh request:

const nuxtApp = useNuxtApp()

const { data: posts } = await useAsyncData(
  'blog-posts',
  () => $fetch('/api/posts'),
  {
    getCachedData(key) {
      // Return payload data if it already exists — skip the fetch
      return nuxtApp.payload.data[key] ?? nuxtApp.static.data[key]
    }
  }
)

For a TTL-aware variant:

const CACHE_TTL = 60_000 // 1 minute
const cache = new Map<string, { data: unknown; ts: number }>()

const { data } = await useAsyncData('dashboard-stats', () =>
  $fetch('/api/stats'), {
    getCachedData(key) {
      const entry = cache.get(key)
      if (!entry) return undefined
      if (Date.now() - entry.ts > CACHE_TTL) {
        cache.delete(key)
        return undefined
      }
      return entry.data
    }
  }
)

staleTime — the declarative TTL option

Nuxt 4 introduced staleTime as a first-class option, eliminating the need for manual getCachedData in most cases:

const { data } = await useFetch('/api/products', {
  key: 'products-list',
  staleTime: 5 * 60 * 1000 // Data is considered fresh for 5 minutes
})

Lazy loading and deferred fetching

// useLazyFetch — doesn't block navigation; shows loading state immediately
const { data, pending } = useLazyFetch('/api/recommendations', {
  key: 'recommendations',
  server: false // Only fetch on client — excludes from SSR payload
})

Abort signals for cancelled requests

Nuxt 4 exposes an AbortSignal in useAsyncData's handler, letting you cancel in-flight requests:

const { data, refresh } = await useAsyncData(
  'live-feed',
  (_nuxtApp, { signal }) => $fetch('/api/feed', { signal })
)


Layer 5 — Server Route Caching with Nitro {#layer-5}

Nuxt's server engine (Nitro) exposes two powerful caching primitives for API routes.

cachedEventHandler — cache entire route responses

// server/api/products.get.ts
import { cachedEventHandler } from 'nitropack/runtime'
import type { H3Event } from 'h3'

export default cachedEventHandler(
  async (event) => {
    const products = await db.product.findMany({ where: { active: true } })
    return products
  },
  {
    maxAge: 60 * 10,           // Cache for 10 minutes
    staleMaxAge: 60 * 60,      // Serve stale for up to 1 hour while revalidating
    swr: true,                 // Stale-While-Revalidate behaviour
    getKey: (event: H3Event) => event.path, // Cache key per URL
    varies: ['accept-language'] // Vary by header
  }
)

cachedFunction — cache individual server functions

For shared logic called across multiple routes:

// server/utils/catalog.ts
import { defineCachedFunction } from 'nitropack/runtime'

export const getCatalog = defineCachedFunction(
  async (category: string) => {
    return db.product.findMany({ where: { category } })
  },
  {
    maxAge: 60 * 30, // 30 minutes
    name: 'catalog',
    getKey: (category: string) => category
  }
)

// server/api/electronics.get.ts
export default defineEventHandler(() => getCatalog('electronics'))

// server/api/apparel.get.ts
export default defineEventHandler(() => getCatalog('apparel'))

Cache storage backends

Configure the Nitro cache driver in nuxt.config.ts:

// nuxt.config.ts
export default defineNuxtConfig({
  nitro: {
    storage: {
      cache: {
        driver: 'redis',
        url: process.env.REDIS_URL
      }
    }
  }
})

Nitro's unstorage layer supports redis, fs, memory, cloudflare-kv, vercel-kv, and more — no code change required when switching backends.


Layer 6 — Route-Level Cache Rules (routeRules) {#layer-6}

routeRules lets you set rendering strategy and caching behaviour per route pattern directly in config — no middleware, no per-page logic.

// nuxt.config.ts
export default defineNuxtConfig({
  routeRules: {
    // Marketing pages — full static, cached forever at CDN
    '/': { prerender: true },
    '/about': { prerender: true },

    // Product pages — ISR: regenerate every 60 seconds
    '/products/**': { isr: 60 },

    // API responses — cached at CDN edge for 10 minutes
    '/api/catalog/**': { cache: { maxAge: 60 * 10 } },

    // Dashboard — always SSR, never cached
    '/dashboard/**': { ssr: true, cache: false },

    // User-specific pages — no caching, always fresh
    '/account/**': { cache: false },

    // Admin — redirect to login
    '/admin/**': { redirect: '/login' }
  }
})

Pro tip: Start with conservative TTLs and increase them over time. Stale pages are almost always better than slow pages, but you need to understand your data freshness requirements first.


Layer 7 — HTTP & Browser Caching Headers {#layer-7}

Nuxt and Nitro let you set fine-grained HTTP cache headers on any response.

// server/api/static-config.get.ts
export default defineEventHandler((event) => {
  setResponseHeaders(event, {
    'Cache-Control': 'public, max-age=3600, stale-while-revalidate=86400',
    'CDN-Cache-Control': 'max-age=86400',
    'Vary': 'Accept-Encoding'
  })

  return getStaticConfig()
})

Cache-Control directive cheat sheet

Directive Meaning
public CDNs and proxies can cache this
private Only the end browser should cache this
max-age=N Fresh for N seconds
s-maxage=N CDN-specific TTL (overrides max-age for proxies)
stale-while-revalidate=N Serve stale for N seconds while refreshing in the background
no-store Never cache (auth, sensitive data)
immutable Asset will never change — skip revalidation entirely

For Nuxt's static assets (JS, CSS, images), Nitro automatically appends content-hash fingerprints and sets immutable headers, so these are cached forever at the browser and CDN level.


Layer 8 — Pinia as a Client-Side Cache Store {#layer-8}

Pinia is more than state management — it's your application's runtime cache layer for data that needs to be shared and reused across many routes and components.

// stores/products.ts
import { defineStore } from 'pinia'

interface ProductCache {
  data: Product[]
  fetchedAt: number
}

export const useProductStore = defineStore('products', () => {
  const cache = new Map<string, ProductCache>()
  const TTL = 5 * 60 * 1000

  function isStale(key: string): boolean {
    const entry = cache.get(key)
    if (!entry) return true
    return Date.now() - entry.fetchedAt > TTL
  }

  async function fetchByCategory(category: string): Promise<Product[]> {
    if (!isStale(category)) {
      return cache.get(category)!.data
    }

    const data = await $fetch<Product[]>(`/api/products`, {
      params: { category }
    })

    cache.set(category, { data, fetchedAt: Date.now() })
    return data
  }

  function invalidate(category?: string) {
    if (category) cache.delete(category)
    else cache.clear()
  }

  return { fetchByCategory, invalidate }
})

Persisting Pinia state across page reloads

Use pinia-plugin-persistedstate for selective persistence:

// stores/userPreferences.ts
export const usePreferencesStore = defineStore('preferences', () => {
  const theme = ref<'light' | 'dark'>('light')
  const language = ref('en')
  return { theme, language }
}, {
  persist: {
    storage: localStorage,
    pick: ['theme', 'language'] // Only persist these fields
  }
})


Quick Reference Cheat Sheet {#cheatsheet}

Problem Solution Where
Large API array re-renders unnecessarily shallowRef instead of ref Vue component / composable
Static template subtree re-renders v-once Template
Expensive list items re-render v-memo="[id]" Template v-for
Derived state re-computed too often Chain computed() Component / composable
Same request fired by multiple components Same useAsyncData key Nuxt pages
Data fetched on server AND client useAsyncData / useFetch (never raw $fetch in setup) Nuxt pages
Client navigates back, unnecessary refetch getCachedData or staleTime useAsyncData options
API route hammered by many users cachedEventHandler with Nitro server/api/
Shared server function called redundantly defineCachedFunction server/utils/
Marketing page slow to load prerender: true in routeRules nuxt.config.ts
Product page needs periodic freshness isr: 60 in routeRules nuxt.config.ts
State shared across components Pinia store with TTL map stores/
Preferences survive page reload pinia-plugin-persistedstate Pinia plugin

Key Takeaways

Caching in Vue and Nuxt isn't a single decision — it's a strategy applied at every layer of the stack:

  • Reactivity layer: Reach for shallowRef by default for data that's replaced wholesale. Reserve deep reactivity for objects you mutate in place.
  • Computed layer: Keep them pure, chain them for granular invalidation, and use manual memos for argument-based functions.
  • Composable layer: Module-scope state is a free singleton cache — use it deliberately.
  • Data fetching layer: useAsyncData with getCachedData or staleTime gives you precise control over client-side request deduplication.
  • Server layer: cachedEventHandler and defineCachedFunction push caching to the edge, absorbing load before it ever touches your database.
  • Route layer: routeRules lets you declaratively assign the right rendering and caching strategy per page pattern.
  • HTTP layer: Set Cache-Control headers correctly to get CDN and browser caching without extra infrastructure.
  • State layer: Pinia with a TTL map is a battle-tested pattern for runtime client cache that survives navigation.

The right combination depends on your data's freshness requirements, your traffic patterns, and your deployment target. Start conservative, measure, and increase TTLs once you understand the shape of your data.


Found this useful? Follow me for more deep dives into Vue and Nuxt performance. Got a caching pattern you swear by that I missed? Drop it in the comments.