Function that receives the next handler and request parameters
A fetch middleware function
// Create custom authentication middleware
const customAuthMiddleware = createMiddleware(async (next, input, init) => {
const headers = new Headers(init?.headers);
headers.set('X-Custom-Auth', 'my-token');
const response = await next(input, { ...init, headers });
if (response.status === 401) {
console.log('Authentication failed');
}
return response;
});
// Create conditional middleware
const conditionalMiddleware = createMiddleware(async (next, input, init) => {
const url = typeof input === 'string' ? input : input.toString();
// Only add headers for API routes
if (url.includes('/api/')) {
const headers = new Headers(init?.headers);
headers.set('X-API-Version', 'v2');
return next(input, { ...init, headers });
}
// Pass through for non-API routes
return next(input, init);
});
// Create caching middleware
const cacheMiddleware = createMiddleware(async (next, input, init) => {
const cacheKey = typeof input === 'string' ? input : input.toString();
// Check cache first
const cached = await getFromCache(cacheKey);
if (cached) {
return new Response(cached, { status: 200 });
}
// Make request and cache result
const response = await next(input, init);
if (response.ok) {
await saveToCache(cacheKey, await response.clone().text());
}
return response;
});
Helper function to create custom fetch middleware with cleaner syntax. Provides the next handler and request details as separate parameters for easier access.