The user wants a plan for a hybrid Server-Side Rendering (SSR) / Client-Side Rendering (CSR) architecture.
Key requirements:
- Hybrid SSR/CSR: Needs to render initial content on the server for SEO/performance but hydrate and behave like a Single Page App (SPA) on the client.
- Prefetching with React Query: Use TanStack Query (React Query) for data fetching and state management.
- Caching on the Edge: Use a CDN or Edge Network to cache API responses or HTML closer to the user.
- Offline Operations: Handle data access and mutations when the user is disconnected.
Target Audience: Likely a developer or architect looking for a high-level but technical implementation strategy.
Tools & Technologies:
- Framework: Next.js (App Router or Pages Router) or Remix. Next.js is the standard choice for this specific hybrid requirement, especially with its recent focus on Server Components and caching. Let's assume Next.js (App Router) as it provides the most robust toolset for Edge/SSR integration currently, though Remix is a valid alternative. I will frame the answer generally but use Next.js concepts (Server Components, Route Handlers) as concrete examples.
- Data Layer: TanStack Query (React Query). Essential for the "prefetch" and client-side state requirement.
- Database/API: Generic REST or GraphQL.
- Edge/CDN: Vercel Edge Cache, Cloudflare, or generic CDN headers.
- Offline/Persistence: IndexedDB (via libraries like
idb or localforage) or localStorage. Service Workers (optional but robust).
Architecture Breakdown:
-
The "Hybrid" Core (SSR + Hydration):
- How to mix SSR and CSR?
- Approach: Use Server Components (RSC) to fetch initial data on the server. Pass this data to the client.
- React Query Integration:
HydrationBoundary and dehydrate/hydrate. This is the specific mechanism React Query uses to bridge server and client state.
-
Edge Caching (The Delivery Layer):
- Where does the cache live?
- Level 1: CDN (Static Assets).
- Level 2: Full Page Cache (ISR/SSG). Statically generate pages where possible.
- Level 3: Edge Functions/Data Cache. If using dynamic SSR, cache the fetch requests at the edge (using
fetch extended APIs or specific Edge caching headers).
- Strategy: "Stale-While-Revalidate" is the gold standard here.
-
React Query (The State Layer):
- Server: Prefetch queries in a server-side
queryClient. Dehydrate to JSON.
- Client: Wrap app in
HydrationBoundary. Initialize client queryClient with dehydrated state.
- Background Refetching: Once hydrated, React Query updates data in the background if stale.
-
Offline & Persistence (The Resilience Layer):
- React Query doesn't persist to disk by default. We need a persister.
- Libraries:
tanstack-query-sync-storage-persister or async-storage-persister.
- Storage: IndexedDB is better for larger datasets than LocalStorage.
- Network Detection: Use
navigator.onLine or listeners to pause mutations.
- Retry Logic: Configure
retry to handle flaky connections.
Detailed Plan Structure:
- Phase 1: Architecture Overview (The Diagram)
- Visualizing the flow: Request -> Edge -> Server -> Client -> Offline.
- Phase 2: The Server-Side (Prefetching & SSR)
- Using Next.js App Router (or Remix loaders).
- Dehydrating state.
- Phase 3: Edge Caching Strategy
- Cache-Control headers.
- CDN configuration (Vercel/Cloudflare).
- Phase 4: Client-Side (Hydration & React Query)
- Hydration Boundary.
- Query Client setup.
- Phase 5: Offline Persistence
- IndexedDB integration.
- Persisters.
- Phase 6: Offline Mutations (The tricky part)
- Optimistic Updates.
- Queuing mutations (retry logic).
Refining the details:
- Prefetching: In Next.js App Router, we can fetch directly in Server Components. However, React Query v5 prefers the
HydrationBoundary pattern where we create a server-side queryClient, prefetch, dehydrate, and pass to the client.
- Edge: Next.js
fetch API automatically caches. We need to explain how to configure next: { revalidate: ... } or cache: 'no-store' appropriately.
- Offline: The "Persist Query Client" plugin is key here.
Self-Correction/Review during thought process:
Drafting the Plan:
- Stack Selection: Next.js + React Query + IndexedDB.
- Data Flow Diagram:
- Request hits Edge.
- Edge checks cache.
- If miss -> Server runs.
- Server prefetches RQ -> Dehydrates JSON -> Renders HTML.
- Client receives HTML + JSON.
- Client hydrates RQ.
- Persistor saves RQ cache to IndexedDB.
- Implementation Steps:
- Server Setup (Routers/Loaders).
- Persister Setup (IndexedDB).
- Cache Headers.
Specific Code Snippets to Include:
- Server-side prefetch logic (Next.js wrapper).
- Client-side QueryClient setup with Persister.
HydrationBoundary usage.
Final Polish: Ensure the distinction between Edge Cache (HTML/JSON payload) and Browser Cache (Offline IndexedDB) is clear.
Let's write out the response following this structure.
This architecture combines Next.js (App Router) for the hybrid rendering engine, TanStack Query (React Query v5) for state management, Upstash Redis (or Vercel KV) for edge caching, and IndexedDB (via Dexie.js) for offline persistence.
Here is the comprehensive architectural plan.
1. High-Level Architecture Diagram
The flow follows a "Waterfall" strategy: Edge Cache → Server Prefetch → Client Hydration → Offline DB.
- Request: User requests a page.
- Edge: CDN checks if cached HTML/API response exists.
- Hit: Serve immediately.
- Miss: Forward to Origin Server.
- Server (SSR):
- Next.js generates the HTML.
- Prefetch: A service layer fetches data from the DB/API.
- Dehydrate: Data is serialized into the HTML payload.
- Client (Hydration):
- React hydrates the HTML.
- Hydrate: React Query ingests the prefetched data instantly.
- Persist: Data is written to IndexedDB for offline access.
- Subsequent Navigation (CSR):
- React Query checks IndexedDB first.
- Fetches updates in the background.
2. The Data Layer: React Query Configuration
We need a robust Query Client configuration that handles "Stale-While-Revalidate" patterns and knows how to talk to a persistent storage layer.
The Client Setup (Client-Side):
// lib/queryClient.ts
import { QueryClient } from '@tanstack/react-query';
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client';
// We will use IndexedDB for larger offline storage instead of LocalStorage
// See Section 4 for the Offline Adapter implementation.
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
// Cache data for 5 minutes
staleTime: 1000 * 60 * 5,
// Keep unused data in memory for 10 minutes
gcTime: 1000 * 60 * 10,
// Retry logic optimized for flaky connections
retry: (failureCount, error) => failureCount < 3 && error.message !== 'Unauthorized',
// Use 'always' to trigger refetching even when data is fresh if window regains focus
refetchOnWindowFocus: 'always',
},
},
});
3. The Edge Caching Strategy
To reduce latency, we cache the responses of our data fetches at the Edge (e.g., Vercel Edge Config, Cloudflare Workers KV, or Upstash Redis).
The Edge Fetcher (Server-Side Helper):
This function wraps standard fetch and adds caching headers or Redis checks.
// lib/edgeFetcher.ts
import { cache } from 'react'; // Next.js unstable_cache or React 'cache'
import { kv } from '@vercel/kv'; // Example using Vercel KV (Redis)
export const fetchWithEdgeCache = async <T>(
key: string,
fetcher: () => Promise<T>
): Promise<T> => {
// 1. Try KV Cache (Edge)
const cached = await kv.get<T>(key);
if (cached) {
console.log(`HIT: Edge Cache ${key}`);
return cached;
}
// 2. Fetch from Source (DB/API)
console.log(`MISS: Fetching ${key} from source`);
const data = await fetcher();
// 3. Set Edge Cache
// 'ex' sets expiry in seconds (e.g., 1 hour)
await kv.set(key, data, { ex: 3600 });
return data;
};
4. The Offline Strategy (IndexedDB)
LocalStorage is too small and synchronous. We use IndexedDB via Dexie.js for a robust offline experience.
The Persister Adapter:
React Query needs an adapter to talk to IndexedDB.
// lib/offlinePersister.ts
import Dexie from 'dexie';
import { persisters } from '@tanstack/react-query-persist-client';
// 1. Setup Database
const db = new Dexie('OfflineAppDB');
db.version(1).stores({
queries: '&queryKey', // Use queryKey as primary key
});
// 2. Create Custom Persister
export const idbPersister = persisters.createCustomPersister({
storage: {
getItem: async (key: string) => {
const result = await db.table('queries').get(key);
return result ? result.data : null;
},
setItem: async (key: string, value: string) => {
await db.table('queries').put({ queryKey: key, data: value });
},
removeItem: async (key: string) => {
await db.table('queries').delete(key);
},
},
key: 'REACT_QUERY_OFFLINE_CACHE',
});
5. The Hybrid Architecture Assembly
Now we combine these pieces into the Next.js App Router structure.
A. The Server Component (SSR + Prefetch)
In Next.js App Router, we fetch data on the server and dehydrate it.
// app/users/page.tsx
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query';
import { fetchUsers } from '@/api/users';
import { fetchWithEdgeCache } from '@/lib/edgeFetcher';
import UserList from './UserList';
export default async function UsersPage() {
// 1. Initialize Query Client for this request
const queryClient = new QueryClient();
// 2. Prefetch Data with Edge Caching
// This call hits Edge Cache first, then DB.
await queryClient.prefetchQuery({
queryKey: ['users'],
queryFn: () => fetchWithEdgeCache('users-list', fetchUsers),
});
return (
// 3. Dehydrate: Embed the cache into HTML payload
<HydrationBoundary state={dehydrate(queryClient)}>
<UserList />
</HydrationBoundary>
);
}
B. The Client Component (CSR + Offline Sync)
This component consumes the prefetched data and sets up offline persistence.
// app/users/UserList.tsx
'use client';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect } from 'react';
import { fetchUsers } from '@/api/users';
import { useOnlineManager } from '@/hooks/useOnlineManager'; // Custom hook to detect network
export default function UserList() {
const { isOnline } = useOnlineManager();
const queryClient = useQueryClient();
const { data, isError, error } = useQuery({
queryKey: ['users'],
queryFn: fetchUsers,
// If offline, keep showing stale data instead of erroring immediately
networkMode: isOnline ? 'online' : 'offlineFirst',
});
// Handle "Back Online" Resync
useEffect(() => {
if (isOnline) {
// Revalidate all queries when connection returns
queryClient.invalidateQueries();
}
}, [isOnline, queryClient]);
if (isError) return <div>Error: {error.message}</div>;
return (
<div>
<h1>Users {!isOnline && <span>(Offline Mode)</span>}</h1>
<ul>
{data?.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
</div>
);
}
C. The Root Layout (Persistence Provider)
Wrap the application to enable the IndexedDB persister.
// app/layout.tsx
'use client';
import { QueryClientProvider } from '@tanstack/react-query';
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client';
import { queryClient } from '@/lib/queryClient';
import { idbPersister } from '@/lib/offlinePersister';
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<PersistQueryClientProvider
client={queryClient}
persistOptions={{
persister: idbPersister,
maxAge: 86400000, // 24 hours
}}
>
{children}
</PersistQueryClientProvider>
</body>
</html>
);
}
6. Handling Mutations (Writes) Offline
The hardest part of offline architecture is handling POST/PUT requests when the user is offline. We use a Queue pattern.
- Optimistic Update: Update the UI immediately (React Query's
context.previousData).
- Queue: If offline, store the mutation payload in IndexedDB.
- Sync: Listen for the 'online' event, process the queue.
Simplified Mutation Hook:
// hooks/useOfflineMutation.ts
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { db } from '@/lib/offlinePersister'; // Dexie instance
import { v4 as uuidv4 } from 'uuid';
export const useAddUser = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (newUser) => {
if (!navigator.onLine) {
// 1. If offline, save to 'outbox' in IndexedDB
await db.table('outbox').add({ id: uuidv4(), type: 'ADD_USER', payload: newUser });
return { offline: true };
}
// 2. If online, send to API
return await api.addUser(newUser);
},
// 3. Optimistic Update
onMutate: async (newUser) => {
await queryClient.cancelQueries({ queryKey: ['users'] });
const previousUsers = queryClient.getQueryData(['users']);
queryClient.setQueryData(['users'], (old) => [...old, newUser]);
return { previousUsers };
},
// 4. Rollback on Error
onError: (err, newUser, context) => {
queryClient.setQueryData(['users'], context.previousUsers);
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['users'] });
},
});
};
The Sync Worker (Service Worker or useEffect):
You need a background process that detects online status, reads the 'outbox' table, sends requests, and removes them from the table upon success.
Summary of Benefits
| Feature | Technology Used | Benefit |
|---|
| Initial Load | SSR + Edge Cache | TTFB < 100ms. SEO friendly. |
| Navigation | React Query + Prefetch | Instant page transitions. |
| Data Freshness | Stale-While-Revalidate | Users see content immediately, updated in background. |
| Offline Read | IndexedDB + Persister | Users can read data they've previously viewed. |
| Offline Write | IndexedDB Outbox | Users can submit forms offline; synced later. |