Plan a hybrid SSR/CSR architecture that prefetches data with React Query, caches on the…
- User
Plan a hybrid SSR/CSR architecture that prefetches data with React Query, caches on the edge, and handles offline operations.
- Assistant
Hybrid SSR/CSR Architecture Plan with React Query Prefetching, Edge Caching, and Offline Support
This plan outlines a scalable, performant web app architecture using Next.js 13+ (App Router) for hybrid SSR/CSR, TanStack Query (v5) for data management/prefetching, Vercel Edge Network (or Cloudflare Workers) for caching, and service workers + IndexedDB persistence for offline ops. It prioritizes fast initial loads (SSR + prefetch), seamless hydration (CSR), global caching (edge), and resilience (offline).
Key Benefits
- SSR: SEO-friendly, fast TTFB with prefetched data.
- CSR: Interactive SPA feel post-hydration.
- Prefetching: React Query dehydrates server-fetched data for instant client cache.
- Edge Caching: Reduces latency via global CDN/edge compute (e.g., ISR on Vercel).
- Offline: Queue mutations, sync on reconnect, cache reads.
High-Level Architecture
┌─────────────────────┐ ┌──────────────────┐ ┌─────────────────┐ │ User Browser │ │ Edge Network │ │ Origin │ │ │ │ (Vercel/CDN) │ │ (Next.js Server)│ │ Service Worker ──▶ │◀───│ Cache (ISR/HTTP) │◀───│ API/DB │ │ IndexedDB (RQ Pers)│ │ React Query Keys │ │ (Supabase/Planet│ │ Optimistic UI │ │ Background Sync │ │ Scale/Redis) │ └────────┬────────────┘ └────────┬────────┘ └────────┬────────┘ │ │ │ ▼ ▼ ▼ ┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐ │ Offline │ │ Cached SSR │ │ Prefetch │ │ Mutations │◀──Hydration──│+ RQ State │◀───SSR──│ RQ Queries│ │ Background│ │ (Dehydrated│ │ (Server) │ │ Sync │ │ Cache) │ └───────────┘ └───────────┘ └───────────┘- Flow:
- Edge serves cached SSR HTML + dehydrated React Query state.
- Client hydrates: Instant UI from cache, offline-ready.
- Interactions: CSR fetches (cached/offline), mutations queue offline.
- Reconnect: Background sync mutations.
Tech Stack
Component Tool/Library Purpose Framework Next.js 13+ App Router Hybrid SSR/CSR Data Fetching TanStack Query v5 Prefetch, cache, sync Edge Caching Vercel Edge Runtime + ISR Page/API caching Persistence @tanstack/query-persist-client-core+idb-keyvalOffline cache Offline Workbox (via next-pwa) + BroadcastChannel SW, background sync DB/API Supabase/PlanetScale + Upstash Redis (optional RQ cache invalidation) Data source Deployment Vercel Edge-optimized hosting Implementation Steps
1. Setup Next.js + TanStack Query
Install deps:
npm i @tanstack/react-query @tanstack/query-persist-client-core idb-keyval next-pwa workbox-window workbox-background-sync npm i -D @tanstack/react-query-devtoolsProvider Setup (
app/providers.tsx):'use client'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client-core'; import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'; import { useState, useEffect } from 'react'; export function Providers({ children }: { children: React.ReactNode }) { const [queryClient] = useState(() => new QueryClient({ defaultOptions: { queries: { gcTime: 1000 * 60 * 60 * 24, staleTime: 5 * 60 * 1000 } } // 24h GC, 5m stale })); const persister = createSyncStoragePersister({ storage: window.localStorage }); // Or idb for larger data return ( <PersistQueryClientProvider client={queryClient} persistOptions={{ persister }}> {children} </PersistQueryClientProvider> ); }Wrap in
app/layout.tsx:<Providers>{children}</Providers>2. SSR Prefetching with React Query
Use server-side
QueryClientto prefetch in Server Components.Page Example (
app/dashboard/page.tsx- Server Component):import { HydrationBoundary, QueryClient, dehydrate } from '@tanstack/react-query'; import { PostsList } from './PostsList'; // Client Component async function prefetchPosts(queryClient: QueryClient) { await queryClient.fetchQuery({ queryKey: ['posts'], queryFn: () => fetch('/api/posts').then(res => res.json()) }); } export default async function Dashboard() { const queryClient = new QueryClient(); await prefetchPosts(queryClient); return ( <HydrationBoundary state={dehydrate(queryClient)}> <PostsList /> </HydrationBoundary> ); }Client Component (
PostsList.tsx):'use client'; import { useQuery } from '@tanstack/react-query'; export function PostsList() { const { data } = useQuery({ queryKey: ['posts'], queryFn: () => fetch('/api/posts').then(res => res.json()) }); return <ul>{data?.map(post => <li key={post.id}>{post.title}</li>)}</ul>; }- Hydrates instantly from SSR cache.
3. Edge Caching
Leverage Next.js + Vercel for ISR/Edge caching.
- ISR for Pages (
app/dashboard/page.tsx): Addexport const revalidate = 60;(revalidate every 60s). - API Routes as Edge Functions (
app/api/posts/route.ts):// @ts-ignore - Edge Runtime export const runtime = 'edge'; export async function GET(request: Request) { const posts = await fetch('https://your-db.supabase.co/posts'); // Edge-compatible DB const data = await posts.json(); return Response.json(data, { headers: { 'Cache-Control': 's-maxage=60, stale-while-revalidate=300' } // Edge cache 60s, stale 5m }); } - Middleware for Cache Invalidation (
middleware.ts): Invalidate RQ cache keys on mutations via Upstash Redis pub/sub. - Vercel Config: Enables global edge caching automatically.
React Query keys ensure granular invalidation (e.g.,
queryClient.invalidateQueries({ queryKey: ['posts'] })).4. Offline Operations
- Persistence: Already in Provider (uses IndexedDB via
idb-keyvalfor >5MB). - Service Worker (via
next-pwa): Register innext.config.js.const withPWA = require('next-pwa')({ dest: 'public', runtimeCaching: [...] }); module.exports = withPWA({}); - Offline Mutations (use
useMutationwith optimistic updates):const queryClient = useQueryClient(); const mutation = useMutation({ mutationFn: (newPost) => fetch('/api/posts', { method: 'POST', body: JSON.stringify(newPost) }), onMutate: async (newPost) => { await queryClient.cancelQueries({ queryKey: ['posts'] }); const previousPosts = queryClient.getQueryData(['posts']); queryClient.setQueryData(['posts'], (old: any[]) => [...old, newPost]); // Optimistic return { previousPosts }; }, onError: (err, newPost, context) => queryClient.setQueryData(['posts'], context?.previousPosts), onSettled: () => queryClient.invalidateQueries({ queryKey: ['posts'] }) }); - Background Sync: Use Workbox in SW (
public/sw.js):import { BackgroundSyncPlugin } from 'workbox-background-sync'; const bgSync = new BackgroundSyncPlugin('mutationQueue', { maxRetentionTime: 24 * 60 }); // Queue failed POST/PUT/DELETE fetches, retry on reconnect. - Network Status: Use
navigator.onLine+window.addEventListener('online')to triggerqueryClient.refetchQueries().
5. Deployment & Optimization
- Deploy to Vercel: Auto edge caching/ISR.
- Monitoring: TanStack Query DevTools, Vercel Analytics.
- Scaling: Use Redis for shared RQ cache across edge nodes (via
createSyncStoragePersister({ storage: redisAdapter })). - Testing Offline: Chrome DevTools > Application > Service Workers > Offline.
Potential Challenges & Solutions
Challenge Solution Hydration Mismatch Always prefetch exact queries used client-side. Large Payloads Compress dehydrated state (RQ auto-optimizes); lazy-load non-critical queries. Edge-DB Latency Use edge-compatible DBs (Supabase Edge Functions, PlanetScale Vitess). Cache Invalidation RQ query keys + ISR revalidation + Redis pub/sub for mutations. SW + SSR next-pwahandles precaching SSR shells.iOS Safari Quirks Fallback to localStorage; test PWA installability. This architecture delivers sub-100ms loads globally, full offline UX, and scales to millions. Prototype in a monorepo, measure with Lighthouse/Web Vitals. For custom tweaks (e.g., SWR instead), provide more app details!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.