This project fetches stock and commodity history through api/stock/historical.ts. The browser should call this server endpoint instead of calling market data providers directly.
Yahoo Finance can hit rate limits on Vercel because serverless deployments may share outbound IP addresses. The API proxy keeps the browser code simple and lets the server fall back to other providers when Yahoo Finance fails.
- Yahoo Finance via
yahoo-finance2 - Twelve Data when
TWELVE_DATA_API_KEYis configured - Alpha Vantage using
ALPHA_VANTAGE_API_KEY, or the Alpha Vantagedemokey when the variable is missing
Twelve Data is tried before Alpha Vantage because its free quota is higher.
Twelve Data provides a larger free quota than Alpha Vantage.
- Create an account: https://twelvedata.com/pricing
- Get a free API key.
- Add this variable in Vercel:
TWELVE_DATA_API_KEY=your_key_hereAlpha Vantage is the last fallback. The free quota is small, so it is best used as a backup.
- Get a free API key: https://www.alphavantage.co/support/#api-key
- Add this variable in Vercel:
ALPHA_VANTAGE_API_KEY=your_key_hereGET /api/stock/historical
| Parameter | Required | Description |
|---|---|---|
symbol |
Yes | Market symbol, converted to uppercase on the server. |
interval |
No | 1d, 1wk, or 1mo. Defaults to 1d. |
start and end |
No | Date strings or millisecond timestamps. Both must be present when used. |
rangeDays |
No | Lookback window in days when start and end are not provided. Defaults to 200. |
The response shape is:
{
"symbol": "AAPL",
"interval": "1d",
"points": [{ "time": 1719792000000, "close": 216.75 }]
}- The endpoint checks the in-memory cache first.
- On cache miss, it tries Yahoo Finance.
- If Yahoo Finance fails, it retries once for rate-limit errors.
- If Yahoo still fails, it tries Twelve Data when
TWELVE_DATA_API_KEYexists. - If no Twelve Data result is available, it tries Alpha Vantage.
- If every provider fails, the endpoint returns a
500response with an error message.
- In-memory cache: 1 hour
- Vercel CDN cache:
s-maxage=3600 - Stale revalidation window:
stale-while-revalidate=7200
Successful responses include:
X-Cache: HITorMISSX-Data-Source: yahoo,twelvedata, oralphavantageon cache misses
- Add at least one fallback API key in Vercel when possible:
TWELVE_DATA_API_KEY=xxx
ALPHA_VANTAGE_API_KEY=xxx- Deploy the app:
git push- Verify a response:
curl -I "https://your-domain.example/api/stock/historical?symbol=AAPL&rangeDays=30"Check X-Data-Source and X-Cache in the response headers.
- Yahoo Finance can work without fallback keys, but it is more exposed to rate limits.
- Twelve Data is the preferred fallback when available.
- Alpha Vantage can run with the
demokey, but the limits are strict. - The 1-hour cache is intentional because this endpoint is used for historical data.