Skip to content

Instantly share code, notes, and snippets.

@teklynk
Last active February 8, 2026 01:43
Show Gist options
  • Select an option

  • Save teklynk/d238f3b41bc2442ea6720330e3cdfd49 to your computer and use it in GitHub Desktop.

Select an option

Save teklynk/d238f3b41bc2442ea6720330e3cdfd49 to your computer and use it in GitHub Desktop.
Fallback Service Using Cloudflare Workers
export default {
async fetch(request) {
const primaryUrl = 'https://api.example.com';
const fallbackUrl = 'https://api2.example.com';
const url = new URL(request.url);
const path = url.pathname + url.search;
// Try primary
try {
const response = await fetch(primaryUrl + path, request);
// If origin responds with a redirect (301/302), return it
if ([301, 302].includes(response.status)) {
return new Response(null, {
status: response.status,
headers: { 'Location': response.headers.get('Location') }
});
}
// Otherwise, return normal response
if (response.ok) {
return response;
}
} catch (e) {
console.error('Primary failed:', e);
}
// Fallback: try the same logic on secondary
try {
const response = await fetch(fallbackUrl + path, request);
if ([301, 302].includes(response.status)) {
return new Response(null, {
status: response.status,
headers: { 'Location': response.headers.get('Location') }
});
}
return response;
} catch (e) {
console.error('Fallback failed:', e);
}
return new Response('Service unavailable', { status: 503 });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment