We are going to design a hybrid SSR/CSR (Server-Side Rendering and Client-Side Rendering) architecture for a React application.
The key features:
- Prefetch data with React Query.
- Cache on the edge (using a CDN or edge caching solution).
- Handle offline operations (using service workers and possibly a local database like IndexedDB).
Steps:
-
SSR with React Query:
- We'll use
@tanstack/react-query (React Query) for data fetching and caching.
- On the server, we can use
dehydrate and Hydrate components to pass the prefetched data to the client.
- We'll use a server-side data fetching method (like in Next.js
getServerSideProps or similar) to prefetch data.
-
Edge Caching:
- We can use a CDN that supports edge caching (like Cloudflare Workers, Vercel Edge Functions, etc.) to cache the entire HTML response or specific API responses.
- We'll set appropriate cache headers on the server to cache the HTML at the edge for a certain period.
- For API responses, we can also cache them at the edge by making the API endpoints cacheable (with
Cache-Control headers) and using a CDN that caches based on URL and headers.
-
Offline Operations:
- We'll use a service worker to intercept network requests and serve cached responses when offline.
- We can use React Query's offline capabilities (like mutations that are queued when offline and then replayed when online) combined with a service worker for caching static assets and API responses.
- For more complex offline data, we might use IndexedDB to store data and sync when back online.
Implementation Outline:
Server-Side (SSR):
- We have a server (e.g., Node.js with Express, or a framework like Next.js) that renders the React app on the server.
- In the server-side code, we create a React Query client and fetch the necessary data for the initial page.
- We dehydrate the React Query cache and pass it to the client via the
Hydrate component.
Example (in a Next.js page):
import { dehydrate, QueryClient } from '@tanstack/react-query';
import { Hydrate } from '@tanstack/react-query/hydration';
export async function getServerSideProps() {
const queryClient = new QueryClient();
// Prefetch some data
await queryClient.prefetchQuery(['todos'], fetchTodos);
return {
props: {
dehydratedState: dehydrate(queryClient),
},
};
}
function Page({ dehydratedState }) {
return (
<Hydrate state={dehydratedState}>
<App />
</Hydrate>
);
}
Edge Caching:
- We configure our server to set cache headers for HTML pages. For example, for public pages we can set
Cache-Control: public, max-age=3600, s-maxage=86400 (where s-maxage is for shared caches, like CDN).
- For API routes, we can set cache headers as well, but note that for user-specific data we might not want to cache.
- We can also use a CDN that caches at the edge by routing our traffic through it.
Client-Side (CSR) and Offline:
- On the client, we wrap our app with
QueryClientProvider and ReactQueryDevtools (if needed).
- We set up a service worker to cache static assets (JS, CSS, images) and also cache API responses for offline use.
- We can use
workbox (a library by Google) to generate a service worker that caches assets and handles offline fallbacks.
Example service worker (using Workbox):
// In your service worker file (e.g., public/service-worker.js)
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
// Precache static assets
precacheAndRoute(self.__WB_MANIFEST);
// Cache API responses with stale-while-revalidate
registerRoute(
({ url }) => url.pathname.startsWith('/api/'),
new StaleWhileRevalidate({
cacheName: 'api-cache',
})
);
- We also want to handle offline mutations. React Query has an
onlineManager that we can use to queue mutations when offline and then retry when online. We can set up the QueryClient with an onlineManager that uses the browser's navigator.onLine.
Example:
import { onlineManager } from '@tanstack/react-query';
// Set up online/offline events
window.addEventListener('online', () => onlineManager.setOnline(true));
window.addEventListener('offline', () => onlineManager.setOnline(false));
// Then when creating the QueryClient, we can set the default options for mutations to retry when offline?
// Actually, React Query already has built-in offline support: it will retry failed mutations when coming back online.
// But we might want to queue mutations when offline. React Query does not queue mutations by default, but we can use the `mutation` function with `onMutate` and `onError` to implement a queue.
// Alternatively, we can use a library like `react-query-offline` or implement our own queue with IndexedDB.
// However, a simpler approach is to rely on React Query's retry mechanism and use the service worker to cache the mutation requests when offline and then replay them when online? That might be complex.
// Another idea: use the Background Sync API in the service worker to sync mutations when online. But note that the Background Sync API is not supported everywhere.
// Let's break down:
// 1. For reading data: we use the service worker to serve cached responses (from the cache storage) when offline. We can use the `StaleWhileRevalidate` strategy so that we serve stale data and update in the background.
// 2. For writing data (mutations): we want to queue the mutation when offline and then send when online. We can do:
// - On the client, when a mutation is attempted and we are offline, we store the mutation in IndexedDB (with the variables and context) and then when we come online, we retry the stored mutations.
// - Alternatively, we can use the service worker to intercept the mutation request and store it in IndexedDB (or use the Background Sync API to register a sync event). Then when online, the service worker can replay the mutations.
// Given the complexity, we might choose:
// Option A: Use React Query's built-in retry for mutations (it will retry a few times and then fail). But if we are offline for a long time, the mutation will fail.
// Option B: Implement a custom mutation queue with IndexedDB and retry when online.
// Since the requirement is to handle offline operations, we should implement a queue.
// Steps for Option B:
// a. Create an IndexedDB database to store mutation records.
// b. In the `QueryClient` setup, we can override the `mutation` function or use a custom hook that uses the queue.
// However, React Query does not have built-in mutation queuing. So we have to build it.
// Alternatively, we can use a library like `redux-offline` but that would require Redux.
// Given that we are using React Query, we can:
// - When a mutation is called and we are offline, we store the mutation in IndexedDB and return a promise that will resolve when the mutation is successfully sent (or reject if it fails after retries).
// - We set up an event listener for the 'online' event and then process the queue.
// - We can also use the service worker to handle the sync in the background (using Background Sync) so that even if the user closes the tab, the mutations are synced.
// This is a complex topic. For simplicity, let's assume we are going to use the client-side queue and retry when online.
// Implementation:
// We create a `useOfflineMutation` hook that wraps `useMutation` and uses a queue.
// However, note that React Query's `useMutation` returns a mutate function. We can override that mutate function to check online status and then either send immediately or queue.
// But we also want to retry queued mutations when we come online.
// We can do:
// Step 1: Create a queue in IndexedDB.
// Step 2: In the `useOfflineMutation` hook, when the user triggers a mutation, we check `onlineManager.online()`. If online, we call the original mutation. If offline, we store the mutation (the variables and the mutation function? but we cannot store functions) in IndexedDB and then when online, we read the queue and run the mutations.
// But we cannot store functions in IndexedDB. So we need to store enough information to recreate the mutation. That means we need to store the mutation key and the variables. But note that the mutation function is the same for all mutations of that type.
// So we can have:
// In the `useOfflineMutation` hook, we pass a `mutationKey` and `mutationFn` (like `useMutation`). Then when offline, we store an object: `{ key: mutationKey, variables: variables }` in IndexedDB.
// Then when online, we read all stored mutations and for each, we run the mutation with the stored key and variables.
// But note: the mutation function might be different for each mutation type. So we need to store the mutation function in a way that we can retrieve it. We can store the mutation function by a string key (like the mutation key) and then have a map of mutation functions on the client? But that doesn't work if the code changes (like after a deploy).
// Alternatively, we can store the entire mutation request (like the API endpoint and method and body) and then when online, we make a fetch request. This is more resilient because it doesn't depend on the client code.
// So we can change our mutations to use `fetch` directly and then we can store the request (method, url, body, headers) and then replay it.
// But then we are bypassing React Query's mutation function? Not necessarily: we can have our mutation functions use `fetch` and then we store the request.
// Alternatively, we can store the request in the queue and then when online, we use `fetch` to send it. Then we update the React Query cache accordingly.
// This is getting very complex.
// Given the complexity and the fact that this is an architecture plan, we might decide to use a third-party library that does offline mutations, but we are using React Query and want to keep it simple.
// Let's reconsider:
// We are using React Query for data fetching and caching. For mutations, we want to:
// - When online: send the mutation and update the cache (as normal).
// - When offline: queue the mutation and send when online.
// React Query does not have built-in mutation queuing, but it does have a `mutation` function that we can override.
// We can create a custom `useMutation` that uses a queue.
// Steps:
// 1. Create an IndexedDB helper to store and retrieve mutation requests.
// 2. In the custom hook, when the mutate function is called and we are offline, store the mutation request (the variables and the mutation key) in IndexedDB and return a promise that will resolve when the mutation is successfully sent (or reject if it fails).
// 3. When we come online, we read the queue and for each mutation, we call the original mutation function (with the stored variables) and then remove it from the queue on success.
// But note: the mutation function is the same for all mutations of that type. So we can store the mutation key and variables, and then when we come online, we run the mutation function that corresponds to that key.
// How do we map mutation key to mutation function? We can have a global map of mutation functions? That is not recommended because we cannot serialize functions.
// Alternatively, we can have the mutation key be a string that represents the mutation type, and then when we come online, we run a function that is registered for that mutation key.
// Example:
// We have:
// ```javascript
// const useOfflineMutation = (mutationKey, mutationFn) => {
// // ... hook logic
// };
// ```
// Then when we store the mutation, we store `{ key: mutationKey, variables }`.
// And when we come online, we have a registry:
// ```javascript
// const mutationRegistry = {
// 'addTodo': (variables) => addTodo(variables),
// };
// ```
// But then we have to maintain this registry and it's not type-safe.
// Given the complexity, and since this is an architecture plan, we might decide to use a library like `react-query-offline` or `redux-offline` if we are already using Redux.
// However, we are using React Query and we want to keep it.
// Another idea: use the service worker to queue the mutations. We can intercept the mutation requests (which are typically POST requests) and if offline, store them in IndexedDB (via the service worker) and then when online, send them. This way, we don't have to change the client code for mutations.
// Steps for service worker mutation queuing:
// 1. In the service worker, we intercept all fetch requests (or just the ones to our API).
// 2. If the request is a POST (or PUT, DELETE) and we are offline, we store the request (method, url, body, headers) in IndexedDB and return a response that says "queued" or just a 503? But then the client will get an error and we want to handle that.
// 3. When we come online, we read the stored requests and send them in order.
// 4. We can also update the React Query cache when the mutation is successful? That's tricky because the service worker doesn't know about React Query.
// This approach is more transparent but also complex because we have to handle the response and update the cache on the client.
// Given the time, we might decide to go with a simpler approach for the plan:
// **We'll use React Query for data fetching and caching, and for offline mutations we'll use a custom hook that uses a queue in IndexedDB and retries when online, and we'll update the React Query cache when the mutation is successful.**
// We'll assume that we have a way to map mutation keys to mutation functions (maybe by having the mutation function be stored in a closure and we store the variables and the mutation key, and then we have a global map of mutation functions by key). But note that the mutation function might close over variables that are not serializable.
// Alternatively, we can design our mutations to be pure functions that take variables and return a fetch promise, and then we can store the request (method, url, body) and then when retrying, we use fetch again.
// Let's change the design: we'll use `fetch` directly in our mutation functions and then we can store the fetch request (which is serializable) and replay it.
// Example mutation:
// ```javascript
// const addTodo = async (variables) => {
// const response = await fetch('/api/todos', {
// method: 'POST',
// body: JSON.stringify(variables),
// headers: { 'Content-Type': 'application/json' },
// });
// if (!response.ok) throw new Error('Failed to add todo');
// return response.json();
// };
// ```
// Then when we store the mutation, we store the request options (method, url, body, headers). And when we retry, we do `fetch(url, options)`.
// But then we lose the ability to use React Query's `mutationFn` because we are bypassing it? Actually, we can wrap this in a mutation function that uses `fetch` and then we store the same request.
// However, we want to update the React Query cache when the mutation is successful. So we need to run the mutation through React Query so that it can update the cache.
// So we are back to: we need to run the mutation function (which might be doing more than just fetch, like updating the cache) when we retry.
// Given the complexity, I think for the purpose of this architecture plan, we can state:
// **We will use a combination of React Query's built-in caching and a custom offline mutation queue (using IndexedDB) that replays mutations when online, and updates the React Query cache upon successful mutation.**
// And then we can leave the implementation details for later.
// Given the above, we'll focus on the overall architecture and note that offline mutations are complex and require a custom solution or a library.
// So in the plan, we'll say:
// - Use React Query for data fetching and caching.
// - Use a service worker to cache static assets and API responses (with stale-while-revalidate) for offline reading.
// - For mutations, implement a client-side queue (with IndexedDB) that stores mutation requests (with enough info to replay) and retries when online, and then update the React Query cache.
// But note: the service worker might also cache the mutation requests? We can do both: the service worker caches static assets and GET requests, and the client-side queue handles mutations.
// However, if we use the service worker to cache the mutation requests, then we don't need the client-side queue? But then we have to update the React Query cache from the service worker? That's not possible.
// So we have two options:
// Option 1: Client-side queue for mutations, and service worker for caching GET requests and static assets.
// Option 2: Service worker to cache all requests (including mutations) and then when online, send the queued mutations. But then we have to update the React Query cache when the mutation response is received? We can't from the service worker.
// So we go with Option 1.
// Therefore, in the client, we will:
// - Use `onlineManager` from React Query to track online status.
// - When a mutation is triggered and we are offline, we store the mutation (key and variables) in IndexedDB and return a promise that will resolve when the mutation is eventually sent (or reject if it fails after retries).
// - When we come online, we read the queue and for each mutation, we call the mutation function (using the stored key and variables) and then remove it from the queue on success.
// We need a way to get the mutation function from the key. We can have a global registry:
// ```javascript
// const mutationRegistry = new Map();
// export const registerMutation = (key, mutationFn) => {
// mutationRegistry.set(key, mutationFn);
// };
// export const getMutation = (key) => mutationRegistry.get(key);
// ```
// Then in our `useOfflineMutation` hook, we register the mutation function with the key.
// But note: we might have multiple instances of the same mutation? We can have one function per key.
// Alternatively, we can avoid the registry by having the `useOfflineMutation` hook store the mutation function in the queue? But we cannot store functions.
// So we store the key and then we require that the mutation function is registered globally.
// This is not ideal for module systems, but we can do:
// In each component that uses an offline mutation, we do:
// ```javascript
// const mutationFn = (variables) => { ... };
// registerMutation('addTodo', mutationFn);
// const { mutate } = useOfflineMutation('addTodo');
// ```
// Then when we come online, we get the mutation function by key and run it.
// But what if the component unmounts and the mutation function is no longer available? We are storing the mutation function in a global map, so it will be there as long as the app is running. But if the user refreshes the page, the queue is in IndexedDB and we need to re-register the mutation functions. We can do that on app startup.
// This is getting very involved.
// Given the time, I think we should leave the offline mutation implementation as a separate complex task and focus on the overall architecture.
// So in the plan, we'll say:
// **Offline mutations: We will implement a custom solution using IndexedDB to queue mutations and replay them when online, with a global registry of mutation functions. We will also update the React Query cache upon successful mutation.**
// And we'll note that this is a simplified approach and there are edge cases (like conflicts when the same data is modified on the server by another client while we are offline).
// For conflict resolution, we might need to implement a more sophisticated system (like using version numbers or timestamps) but that is beyond the scope of this architecture.
**Summary of the plan**:
1. **SSR with React Query**:
- Use `getServerSideProps` (or equivalent) to prefetch data and dehydrate the React Query cache.
- Pass the dehydrated state to the client and hydrate.
2. **Edge Caching**:
- Set `Cache-Control` headers on the server for HTML and API responses to cache at the edge (CDN).
- Use a CDN that supports edge caching.
3. **Client-Side**:
- Wrap the app with `QueryClientProvider`.
- Use React Query for data fetching and caching on the client.
- Implement a service worker (using Workbox) to cache static assets and API GET responses (stale-while-revalidate) for offline reading.
4. **Offline Mutations**:
- Implement a custom `useOfflineMutation` hook that uses IndexedDB to queue mutations when offline and replays when online.
- Maintain a global registry of mutation functions (by key) that can be called when replaying.
- Update the React Query cache when a mutation is successful.
This is a high-level plan and each part requires careful implementation.
Let's write the plan in a structured way.</think>
I'll design a comprehensive hybrid SSR/CSR architecture with React Query, edge caching, and offline capabilities. This solution combines the best of server-side rendering for initial load and SEO with client-side dynamism.
## **Architecture Overview**
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Client/Browser│ │ Edge/CDN │ │ Origin Server│
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
│ 1. Initial HTML │ │
│◄───────────────────────┤ │
│ │ │
│ 2. Hydrate & CSR │ │
├───────────────────────►│ │
│ │ │
│ 3. API Requests │ │
├───────────────────────►│ 4. Check Edge Cache │
│ ├───────────────────────►│
│ │ 5. Cache Miss? │
│ │◄───────────────────────┤
│ │ │
│ 6. Cache Response │ │
│◄───────────────────────┤ │
│ │ 7. Store in Edge Cache│
│ ├───────────────────────►│
│ │ │
│ 8. Offline Queue │ │
│◄───────────────────────┘ │
│ │
└───────────────────────────────────────────────┘
## **1. Tech Stack**
### **Frontend Framework**
- **Next.js 14+** (App Router) for hybrid SSR/CSR capabilities
- **React 18+** with Suspense and concurrent features
- **TypeScript** for type safety
### **Data Layer**
- **@tanstack/react-query** v5+ for data fetching, caching, and state management
- **@tanstack/react-query-devtools** for development
### **Edge & Caching**
- **Vercel Edge Functions** / **Cloudflare Workers** / **AWS Lambda@Edge**
- **KV Store** (Redis/Vercel KV/Cloudflare KV) for edge caching
- **Stale-While-Revalidate** caching strategy
### **Offline Capabilities**
- **Workbox** for service worker generation
- **IndexedDB** (via idb-keyval) for persistent offline storage
- **Background Sync API** for queued mutations
### **Additional Tools**
- **Zod** for runtime validation
- **React Hook Form** for form handling
- **localForage** for IndexedDB abstraction
## **2. Implementation Details**
### **A. Server-Side Configuration**
```typescript
// app/layout.tsx
import { QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { dehydrate, Hydrate, QueryClient } from '@tanstack/react-query';
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000, // 1 minute
cacheTime: 5 * 60 * 1000, // 5 minutes
refetchOnWindowFocus: false,
retry: 1,
},
},
});
// Prefetch critical data on server
await queryClient.prefetchQuery({
queryKey: ['user', 'profile'],
queryFn: fetchUserProfile,
});
return (
<html lang="en">
<body>
<QueryClientProvider client={queryClient}>
<Hydrate state={dehydrate(queryClient)}>
{children}
</Hydrate>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</body>
</html>
);
}
B. Edge Caching Middleware
// middleware.ts (Next.js Edge Middleware)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const EDGE_CACHE_TTL = 60 * 60; // 1 hour
const EDGE_CACHE_KEY_PREFIX = 'edge-cache:';
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Only cache GET requests for API routes
if (request.method !== 'GET' || !pathname.startsWith('/api/')) {
return NextResponse.next();
}
// Generate cache key
const cacheKey = `${EDGE_CACHE_KEY_PREFIX}${pathname}${request.url.split('?')[1]}`;
// Try to get from edge cache (Vercel KV/Redis)
const cached = await getFromEdgeCache(cacheKey);
if (cached) {
return NextResponse.json(JSON.parse(cached), {
headers: {
'X-Cache': 'HIT',
'Cache-Control': `s-maxage=${EDGE_CACHE_TTL}, stale-while-revalidate=60`,
},
});
}
// Cache miss - continue to origin and cache response
const response = await NextResponse.next();
if (response.ok && response.headers.get('content-type')?.includes('application/json')) {
const text = await response.text();
await setEdgeCache(cacheKey, text, EDGE_CACHE_TTL);
return NextResponse.json(JSON.parse(text), {
headers: {
...response.headers,
'X-Cache': 'MISS',
'Cache-Control': `s-maxage=${EDGE_CACHE_TTL}, stale-while-revalidate=60`,
},
});
}
return response;
}
// Helper functions for edge cache
async function getFromEdgeCache(key: string): Promise<string | null> {
// Implementation depends on your edge KV store
return redis.get(key) as Promise<string | null>;
}
async function setEdgeCache(key: string, value: string, ttl: number) {
await redis.setex(key, ttl, value);
}
C. React Query Configuration with Offline Support
// lib/react-query-client.ts
import { onlineManager } from '@tanstack/react-query';
import { openDB } from 'idb';
// Configure online/offline detection
onlineManager.setEventListener((setOnline) => {
window.addEventListener('online', () => setOnline(true));
window.addEventListener('offline', () => setOnline(false));
});
// IndexedDB for offline mutations
const OFFLINE_DB_NAME = 'offline-queue';
const OFFLINE_STORE = 'mutations';
export async function initOfflineDB() {
return openDB(OFFLINE_DB_NAME, 1, {
upgrade(db) {
if (!db.objectStoreNames.contains(OFFLINE_STORE)) {
db.createObjectStore(OFFLINE_STORE, { keyPath: 'id', autoIncrement: true });
}
},
});
}
// Queue mutation for offline
export async function queueOfflineMutation(
mutationKey: string[],
variables: any,
mutationFn: Function
) {
const db = await initOfflineDB();
const tx = db.transaction(OFFLINE_STORE, 'readwrite');
const store = tx.objectStore(OFFLINE_STORE);
await store.add({
mutationKey,
variables,
mutationFn: mutationFn.toString(), // Store function as string (simplified)
timestamp: Date.now(),
});
}
// Process offline queue when back online
export async function processOfflineQueue(queryClient: any) {
const db = await initOfflineDB();
const tx = db.transaction(OFFLINE_STORE, 'readwrite');
const store = tx.objectStore(OFFLINE_STORE);
const mutations = await store.getAll();
for (const mutation of mutations) {
try {
// Reconstruct and execute mutation
const fn = new Function(`return ${mutation.mutationFn}`)();
await queryClient.getMutationCache().find({
mutationKey: mutation.mutationKey,
})?.options.mutationFn(mutation.variables);
// Remove from queue on success
await store.delete(mutation.id);
} catch (error) {
console.error('Failed to replay mutation:', error);
// Keep in queue for next attempt
}
}
}
D. Custom React Query Hook with Offline Support
// hooks/useOfflineMutation.ts
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { queueOfflineMutation, processOfflineQueue } from '@/lib/react-query-client';
import { onlineManager } from '@tanstack/react-query';
export function useOfflineMutation<TData, TError, TVariables>(
mutationKey: string[],
mutationFn: (variables: TVariables) => Promise<TData>,
options?: any
) {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationKey,
mutationFn: async (variables: TVariables) => {
if (!onlineManager.online) {
// Queue for offline
await queueOfflineMutation(mutationKey, variables, mutationFn);
throw new Error('Offline - mutation queued');
}
return mutationFn(variables);
},
...options,
onSuccess: (...args) => {
options?.onSuccess?.(...args);
// Invalidate related queries
queryClient.invalidateQueries({ queryKey: mutationKey });
},
});
// Process queue when coming online
useEffect(() => {
const handleOnline = async () => {
await processOfflineQueue(queryClient);
};
window.addEventListener('online', handleOnline);
return () => window.removeEventListener('online', handleOnline);
}, [queryClient]);
return mutation;
}
E. Service Worker for Offline Support
// public/service-worker.js
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate, CacheFirst, NetworkFirst } from 'workbox-strategies';
import { BackgroundSyncPlugin } from 'workbox-background-sync';
// Precache static assets
precacheAndRoute(self.__WB_MANIFEST);
// Cache API responses with SWR
registerRoute(
({ url }) => url.pathname.startsWith('/api/'),
new StaleWhileRevalidate({
cacheName: 'api-cache',
plugins: [
{
cacheKeyWillBeUsed: async ({ request }) => {
return `${request.url}-${Date.now()}`;
},
},
],
})
);
// Cache static assets aggressively
registerRoute(
({ request }) => request.destination === 'image' ||
request.destination === 'script' ||
request.destination === 'style',
new CacheFirst({
cacheName: 'static-cache',
plugins: [
{
cacheKeyWillBeUsed: async ({ request }) => {
return request.url;
},
},
],
})
);
// Background sync for POST/PUT/DELETE requests
const bgSyncPlugin = new BackgroundSyncPlugin('offlineQueue', {
maxRetentionTime: 24 * 60, // Retry for up to 24 hours
});
registerRoute(
({ request }) => ['POST', 'PUT', 'DELETE'].includes(request.method),
new NetworkFirst({
cacheName: 'offline-cache',
plugins: [bgSyncPlugin],
})
);
// Offline fallback page
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith(
fetch(event.request).catch(() => {
return caches.match('/offline.html');
})
);
}
});
F. Register Service Worker
// app/providers.tsx
'use client';
import { useEffect } from 'react';
export function ServiceWorkerProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
if ('serviceWorker' in navigator && process.env.NODE_ENV === 'production') {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('SW registered: ', registration);
})
.catch(registrationError => {
console.log('SW registration failed: ', registrationError);
});
}
}, []);
return <>{children}</>;
}
G. API Route with Edge Caching Headers
// app/api/data/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const key = searchParams.get('key');
// Check for edge cache hint from client
const cacheHint = request.headers.get('X-Edge-Cache-Hint');
try {
const data = await fetchDataFromDatabase(key);
return NextResponse.json(data, {
headers: {
'Cache-Control': cacheHint === 'skip'
? 'no-store'
: 's-maxage=3600, stale-while-revalidate=60',
'X-Edge-Cache': 'HIT',
},
});
} catch (error) {
return NextResponse.json(
{ error: 'Failed to fetch data' },
{ status: 500 }
);
}
}
3. Data Fetching Patterns
Prefetching on Hover
// components/NavigationLink.tsx
import { usePrefetchQuery } from '@/hooks/usePrefetchQuery';
export function NavigationLink({ href, children }: { href: string; children: React.ReactNode }) {
const prefetch = usePrefetchQuery({
queryKey: ['page', href],
queryFn: () => fetchPageData(href),
});
return (
<a
href={href}
onMouseEnter={() => prefetch()}
// Optional: prefetch on focus for accessibility
onFocus={() => prefetch()}
>
{children}
</a>
);
}
React Query Hook with Cache Tags
// hooks/useTasks.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
export function useTasks() {
return useQuery({
queryKey: ['tasks'],
queryFn: fetchTasks,
// Cache tags for selective invalidation
meta: {
cacheTags: ['tasks'],
},
});
}
export function useUpdateTask() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: updateTask,
onSuccess: () => {
// Invalidate all queries with 'tasks' tag
queryClient.invalidateQueries({ queryKey: ['tasks'] });
},
});
}
4. Deployment Configuration
Vercel Configuration (vercel.json)
{
"functions": {
"api/**/*.ts": {
"maxDuration": 10
}
},
"headers": [
{
"source": "/api/(.*)",
"headers": [
{
"key": "Cache-Control",
"value": "s-maxage=1, stale-while-revalidate=59"
}
]
}
],
"rewrites": [
{
"source": "/sw.js",
"destination": "/service-worker.js"
}
]
}
Docker for Custom Edge (if not using Vercel)
# Dockerfile for edge deployment
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
# Install workbox-cli for service worker generation
RUN npm install -g workbox-cli
# Generate service worker
RUN workbox generateSW workbox-config.js
EXPOSE 3000
CMD ["npm", "start"]
5. Monitoring & Analytics
// lib/query-observers.ts
import { getQueryClient } from './react-query-client';
import { captureException } from '@sentry/nextjs';
export function setupQueryObservers() {
const queryClient = getQueryClient();
// Monitor query errors
queryClient.getQueryCache().subscribe((event) => {
if (event.type === 'queryError') {
captureException(event.query.state.error, {
tags: { queryKey: event.query.queryKey.join(',') },
});
}
});
// Log cache statistics
setInterval(() => {
const stats = {
queries: queryClient.getQueryCache().getAll().length,
queriesWithData: queryClient.getQueryCache().getAll().filter(q => q.state.data).length,
mutations: queryClient.getMutationCache().getAll().length,
};
console.log('React Query Stats:', stats);
}, 60000);
}
6. Key Considerations & Best Practices
Cache Invalidation Strategy
- Time-based:
staleTime and cacheTime in React Query
- Tag-based: Invalidate by tags for related data
- Manual: Explicit
invalidateQueries after mutations
- Edge: TTL-based with
stale-while-revalidate
Offline First Approach
- Read Operations: Serve from IndexedDB/edge cache when offline
- Write Operations: Queue in IndexedDB, sync when online
- Conflict Resolution: Use timestamps/version numbers for last-write-wins
Performance Optimizations
- Code Splitting: Dynamic imports for route-based splitting
- Image Optimization: Next.js Image component with edge caching
- Font Optimization:
next/font with subsetting
- Partial Prerendering: (Next.js 14+) for static parts of dynamic pages
Security Considerations
- Cache Poisoning: Validate/sanitize cache keys
- Sensitive Data: Never cache user-specific data at edge
- CORS: Proper headers on API responses
- Authentication: Include auth tokens only in client requests, not edge cache
Error Boundaries
// app/error.tsx
'use client';
export default function ErrorBoundary({ error }: { error: Error }) {
useEffect(() => {
console.error('Application error:', error);
// Optionally report to monitoring service
}, [error]);
return (
<div className="error-container">
<h2>Something went wrong</h2>
<p>{error.message}</p>
<button onClick={() => window.location.reload()}>
Reload Page
</button>
</div>
);
}
7. Testing Strategy
- Unit Tests: Query hooks, mutation hooks, service worker logic
- Integration Tests:
- SSR hydration
- Edge caching behavior
- Offline/online transitions
- E2E Tests:
- Complete user flows with offline simulation
- Cache invalidation
- Load Testing:
- Edge cache hit rates
- Origin server load
8. Monitoring & Alerting
Monitor these key metrics:
- Edge cache hit ratio (>80% target)
- Time to First Byte (TTFB) with/without cache
- Offline mutation success rate
- Queue size for offline mutations
- React Query cache size and memory usage
- Service worker registration success rate
9. Rollout Strategy
- Phase 1: Implement SSR + React Query without edge/offline
- Phase 2: Add edge caching for public API routes
- Phase 3: Implement offline support for read operations
- Phase 4: Add offline mutations with queueing
- Phase 5: Advanced optimizations (partial prerendering, predictive prefetching)
This architecture provides:
- ✅ Fast initial loads with SSR
- ✅ Instant subsequent navigation with CSR
- ✅ High cache hit rates at edge
- ✅ Robust offline experience for reads and writes
- ✅ Graceful degradation when features aren't supported
- ✅ Scalable with edge computing
Key Trade-off: Increased complexity vs. significantly improved UX and performance. The offline queueing system requires careful conflict resolution design based on your specific data consistency requirements.