DEV Community

How We Use Nuxt Nitro SWR Caching and Cloudflare Workers to Serve Real-Time Sports Data at Scale

Serving real-time sports statistics and match predictions comes with a unique architectural challenge: unpredictable traffic spikes paired with constantly changing data.

When major European football leagues kick off on weekends, thousands of users and search engine bots hit the same match pages simultaneously. Pure Server-Side Rendering (SSR) will quickly melt your Node.js server and database, while static site generation (SSG) falls apart because lineups, odds, and probabilities change minutes before kickoff.

While building and scaling Tipsfoot, we solved this by combining Nuxt's Nitro SWR (Stale-While-Revalidate) caching with Cloudflare Workers for automated cache warming. Here is how the architecture works in production.


The Core Problem: Freshness vs. TTFB

For an SEO-driven sports platform, you need two things at the same time:

  1. Instant TTFB (< 100ms) so Googlebot can crawl thousands of fixture URLs efficiently and users don't bounce.
  2. Fresh data (updated xG models, 1X2 probabilities, and pre-match lineups) without hammering your upstream API or Redis/MongoDB instances on every single request.

Standard SSR renders the Vue tree on every request. Even with Redis backing your API, rendering complex match matrices under heavy load burns CPU fast.


Step 1: Configuring Nitro SWR in nuxt.config.ts

Nuxt's built-in server engine, Nitro, makes route-level caching remarkably clean via routeRules. Instead of caching everything blindly, we split our routes by how frequently their data changes:

  • Match & Prediction pages: Cached with swr for 5 to 15 minutes. Users always get an instant cached HTML response, while Nitro silently regenerates the page in the background once the TTL expires.
  • League & Static Guides: Longer SWR window (1 to 6 hours).
  • API endpoints: Short edge caching or bypassed depending on real-time needs.

typescript
// nuxt.config.ts
export default defineNuxtConfig({
  nitro: {
    routeRules: {
      // Homepage & daily fixtures: revalidate every 5 minutes
      '/': { swr: 300 },

      // Individual match analysis pages: revalidate every 10 minutes
      '/pronostic/**': { swr: 600 },

      // League tables & historical stats: revalidate every hour
      '/classement/**': { swr: 3600 },

      // Ensure API routes don't get stuck with stale responses
      '/api/**': { cors: true, headers: { 'cache-control': 'no-cache' } }
    }
  }
})

With this setup, if 500 users request the same match page within 10 minutes, Nitro only executes the SSR render once.
Step 2: Eliminating Cold Starts with Cloudflare Workers

SWR has one well-known drawback: the first visitor after a cache expires still gets the stale version, and if a brand-new fixture page has never been visited yet, the first user (or Googlebot) pays the full SSR latency cost.

To eliminate cold starts on high-traffic matchdays, we use a lightweight Cloudflare Worker running on a Cron Trigger to warm up our priority routes right after our Node.js background workers finish ingesting new match data.

// cloudflare-worker-warmer.js
export default {
  async scheduled(event, env, ctx) {
    const priorityUrls = [
      '[https://tipsfoot.com/](https://tipsfoot.com/)',
      '[https://tipsfoot.com/loto-foot](https://tipsfoot.com/loto-foot)',
      // You can also fetch a dynamic JSON list of today's top fixtures
    ];

    const warmCache = async (url) => {
      try {
        const response = await fetch(url, {
          headers: {
            'User-Agent': 'Tipsfoot-Cache-Warmer/1.0',
          },
        });
        console.log(`Warmed ${url} - Status: ${response.status}`);
      } catch (err) {
        console.error(`Failed to warm ${url}:`, err);
      }
    };

    // Execute requests concurrently
    ctx.waitUntil(Promise.all(priorityUrls.map(warmCache)));
  },
};

By scheduling this worker every 10 minutes via wrangler.toml:

[triggers]
crons = ["*/10 * * * *"]

The cache stays permanently warm before kickoff, meaning both users and crawlers consistently hit an already-rendered HTML payload.
Step 3: Cache Busting for Dynamic Assets

One subtle gotcha when pairing Nuxt with Cloudflare Edge Caching is stale media assets (team logos, player avatars, or generated graphics). If a team updates its crest or an image fails to process initially, Cloudflare might cache the broken or outdated version.

Appending a lightweight version query string (?v=2) or handling image transformations cleanly at the origin ensures you never serve broken visuals while keeping aggressive Cache-Control: public, max-age=31536000 headers for static assets.
Key Takeaways

Moving from pure SSR to Nitro SWR + Cloudflare Worker warming gave us three immediate wins:

    CPU usage dropped by over 70% during weekend matchday peaks.

    Consistent sub-100ms TTFB across thousands of programmatic fixture pages.

    Zero database bottlenecks, allowing our Node.js workers to focus purely on data ingestion and probability calculations.

If you are building content-heavy or data-driven apps with Nuxt, routeRules with SWR is easily one of the highest-ROI optimizations you can ship in under 20 lines of code.

We share more technical notes and football data updates over on Bluesky. How are you handling SSR caching for high-frequency data in your Nuxt apps? Let me know in the comments!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)