Skip to content

Commit 3c40cbe

Browse files
author
Nathan Booker
committed
feat(middleware): add example middleware for cached-fetch integration
1 parent a2248d8 commit 3c40cbe

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

middleware.example.ts

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// @ts-nocheck
2+
import { NextRequest, NextResponse } from 'next/server';
3+
import { cachedFetch } from 'cached-middleware-fetch-next';
4+
5+
/**
6+
* Example middleware showing how to use cached-middleware-fetch-next
7+
*/
8+
export async function middleware(request: NextRequest) {
9+
const pathname = request.nextUrl.pathname;
10+
11+
try {
12+
// Example 1: Cache REST API (Products) for 30 minutes with tags
13+
// SWR behavior: returns cached data immediately; refreshes in background via waitUntil()
14+
const productsResponse = await cachedFetch('https://api.example.com/products', {
15+
next: {
16+
revalidate: 1800, // 30 minutes (SWR)
17+
tags: ['products', 'catalog'],
18+
},
19+
});
20+
21+
const products = await productsResponse.json();
22+
23+
// Example 2: Cache REST API (Settings) indefinitely with tags
24+
// Use this when data changes rarely; invalidate manually by tag when needed
25+
const settingsResponse = await cachedFetch('https://api.example.com/settings', {
26+
next: { revalidate: false, tags: ['settings'] }, // no automatic revalidation
27+
});
28+
29+
const settings = await settingsResponse.json();
30+
31+
// Example 3: Always fetch fresh (no cache) for analytics/side-effect calls
32+
await cachedFetch('https://analytics.example.com/track', {
33+
method: 'POST',
34+
body: JSON.stringify({ event: 'page_view', path: pathname }),
35+
cache: 'no-store', // never cache
36+
});
37+
38+
// Example 4: Simple GraphQL query with 30-minute caching and tags
39+
// SWR behavior applies here too via revalidate + waitUntil()
40+
const graphqlResponse = await cachedFetch('https://api.example.com/graphql', {
41+
method: 'POST',
42+
headers: {
43+
'Content-Type': 'application/json',
44+
},
45+
body: JSON.stringify({
46+
query: `
47+
query GetRoute($path: String!) {
48+
route(path: $path) {
49+
redirect
50+
}
51+
}
52+
`,
53+
variables: { path: pathname },
54+
}),
55+
next: {
56+
revalidate: 1800, // 30 minutes (SWR)
57+
tags: ['routes'],
58+
},
59+
});
60+
61+
const routeData = await graphqlResponse.json();
62+
63+
// Apply routing logic based on cached route data
64+
if (routeData.route?.redirect) {
65+
return NextResponse.redirect(new URL(routeData.route.redirect, request.url));
66+
}
67+
68+
return NextResponse.next();
69+
} catch (error) {
70+
console.error('Middleware error:', error);
71+
return NextResponse.next();
72+
}
73+
}
74+
75+
export const config = {
76+
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
77+
};

0 commit comments

Comments
 (0)