Skip to content

Real-time dashboard for monitoring global news, markets, and geopolitical events

TypeScript

Add CORS proxy fallback mechanism

Sean Thielen-Esparza0a9d22b580fd
diff --git a/src/lib/api/markets.ts b/src/lib/api/markets.ts
index 6668d8a..593d878 100644
--- a/src/lib/api/markets.ts
+++ b/src/lib/api/markets.ts
@@ -7,7 +7,7 @@
import { INDICES, SECTORS, COMMODITIES, CRYPTO } from '$lib/config/markets';
import type { MarketItem, SectorPerformance, CryptoItem } from '$lib/types';
-import { CORS_PROXY_URL, logger, FINNHUB_API_KEY, FINNHUB_BASE_URL } from '$lib/config/api';
+import { fetchWithProxy, logger, FINNHUB_API_KEY, FINNHUB_BASE_URL } from '$lib/config/api';
interface CoinGeckoPrice {
usd: number;
@@ -96,11 +96,9 @@ export async function fetchCryptoPrices(): Promise<CryptoItem[]> {
const ids = CRYPTO.map((c) => c.id).join(',');
const coinGeckoUrl = `https://api.coingecko.com/api/v3/simple/price?ids=${ids}&vs_currencies=usd&include_24hr_change=true`;
- // Use proxy to avoid CORS/rate limiting issues
- const proxyUrl = CORS_PROXY_URL + encodeURIComponent(coinGeckoUrl);
- logger.log('Markets API', 'Fetching crypto from:', proxyUrl);
+ logger.log('Markets API', 'Fetching crypto from CoinGecko');
- const response = await fetch(proxyUrl);
+ const response = await fetchWithProxy(coinGeckoUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
diff --git a/src/lib/api/news.ts b/src/lib/api/news.ts
index 90fa2fb..9cdfada 100644
--- a/src/lib/api/news.ts
+++ b/src/lib/api/news.ts
@@ -5,7 +5,7 @@
import { FEEDS } from '$lib/config/feeds';
import type { NewsItem, NewsCategory } from '$lib/types';
import { containsAlertKeyword, detectRegion, detectTopics } from '$lib/config/keywords';
-import { CORS_PROXY_URL, API_DELAYS, logger } from '$lib/config/api';
+import { fetchWithProxy, API_DELAYS, logger } from '$lib/config/api';
/**
* Simple hash function to generate unique IDs from URLs
@@ -107,11 +107,9 @@ export async function fetchCategoryNews(category: NewsCategory): Promise<NewsIte
// Build the raw GDELT URL with timespan=7d to get recent articles
const gdeltUrl = `https://api.gdeltproject.org/api/v2/doc/doc?query=${fullQuery}&timespan=7d&mode=artlist&maxrecords=20&format=json&sort=date`;
- // Use proxy to avoid CORS - encode the whole URL once
- const proxyUrl = CORS_PROXY_URL + encodeURIComponent(gdeltUrl);
- logger.log('News API', `Fetching ${category} from:`, proxyUrl);
+ logger.log('News API', `Fetching ${category} from GDELT`);
- const response = await fetch(proxyUrl);
+ const response = await fetchWithProxy(gdeltUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
diff --git a/src/lib/config/api.ts b/src/lib/config/api.ts
index e8e1279..a80873c 100644
--- a/src/lib/config/api.ts
+++ b/src/lib/config/api.ts
@@ -22,10 +22,40 @@ export const FINNHUB_BASE_URL = 'https://finnhub.io/api/v1';
const isDev = browser ? (import.meta.env?.DEV ?? false) : false;
/**
- * CORS proxy URL for external API requests
- * Using corsproxy.io for both dev and production
+ * CORS proxy URLs for external API requests
+ * Primary: Custom Cloudflare Worker (faster, dedicated)
+ * Fallback: corsproxy.io (public, may rate limit)
*/
-export const CORS_PROXY_URL = 'https://corsproxy.io/?url=';
+export const CORS_PROXIES = {
+ primary: 'https://situation-monitor-proxy.seanthielen-e.workers.dev/?url=',
+ fallback: 'https://corsproxy.io/?url='
+} as const;
+
+// Default export for backward compatibility
+export const CORS_PROXY_URL = CORS_PROXIES.fallback;
+
+/**
+ * Fetch with CORS proxy fallback
+ * Tries primary proxy first, falls back to secondary on failure
+ */
+export async function fetchWithProxy(url: string): Promise<Response> {
+ const encodedUrl = encodeURIComponent(url);
+
+ // Try primary proxy first
+ try {
+ const response = await fetch(CORS_PROXIES.primary + encodedUrl);
+ if (response.ok) {
+ return response;
+ }
+ // If we get an error response, try fallback
+ logger.warn('API', `Primary proxy failed (${response.status}), trying fallback`);
+ } catch (error) {
+ logger.warn('API', 'Primary proxy error, trying fallback:', error);
+ }
+
+ // Fallback to secondary proxy
+ return fetch(CORS_PROXIES.fallback + encodedUrl);
+}
/**
* API request delays (ms) to avoid rate limiting