Last active
February 8, 2026 01:43
-
-
Save teklynk/d238f3b41bc2442ea6720330e3cdfd49 to your computer and use it in GitHub Desktop.
Fallback Service Using Cloudflare Workers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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