Live numbers from one web app on another, with a 50-line relay
ARLTS is a free, non-profit English-learning app. It's run by The Phan Initiatives, which has its own little home page at phaninitiatives.org.
That page lists a few numbers about our work: how many people use ARLTS, how many activities they've completed, and the value learners got for free. Until today, those numbers were typed into the page by hand, and they went out of date the day after each update.
arlts.org already has the real numbers on its own impact board, refreshed every few minutes. Could the other page read them?
The first try, and why it fails
arlts.org has a public endpoint, /api/home-stats, that hands back the counts. The obvious move is to fetch it from the other page:
fetch("https://arlts.org/api/home-stats").then(r => r.json())
Chrome, Firefox, and the rest block it. arlts.org doesn't add an Access-Control-Allow-Origin header, and without it, a page from a different domain can't read the reply. That's CORS doing what it's for.
We could have added the header on arlts.org. We didn't: we'd rather not open that endpoint to every page on the web for the good of one, and we wanted to leave arlts.org alone.
The fix: ask from the back end
CORS is a rule for pages, not for back ends. A back end can fetch any public URL it likes. Our other page now has a tiny edge function (Netlify, in our case) at its own path, /api/arlts-stats. The page asks its own domain, and the function asks arlts.org:
export default async () => {
try {
const r = await fetch("https://arlts.org/api/home-stats");
if (!r.ok) throw new Error("status " + r.status);
const d = await r.json();
const users = Number(d.visitor_count) || 0;
const activities = PARTS.reduce((sum, k) => sum + (Number(d[k]) || 0), 0);
if (!users || !activities) throw new Error("no counts");
return new Response(JSON.stringify({ users, activities }), {
headers: {
"content-type": "application/json",
"cache-control": "public, max-age=300",
"netlify-cdn-cache-control": "public, max-age=300, stale-while-revalidate=600",
},
});
} catch (e) {
return new Response(JSON.stringify({ error: "unavailable" }), { status: 503 });
}
};
export const config = { path: "/api/arlts-stats" };
The page and the function live on one domain, and the CORS problem is gone.
3 details worth copying
- Hand back only what the page needs. The endpoint on arlts.org returns many more fields than the page uses. The relay works out the 3 numbers and returns only those. The page code is lighter, and if arlts.org adds a field later, nothing leaks through by accident.
- Cache at the edge. Each answer is kept for 5 minutes. However many people open the page, arlts.org gets at most a few calls an hour from the relay.
- Keep the old numbers as a fallback. The page HTML keeps fixed numbers. The live ones replace them only when they arrive, and only if they're higher. If the relay is down, nobody gets a blank or a zero.
Round numbers on purpose
The page doesn't read 10,666 users. It reads 10,500+. The page code rounds down to a fixed unit (500 for users, 5,000 for activities), and the figure moves in clean hops, never higher than the real count.
A number that changes on every visit looks like a bug; one that ticks up now and then looks like real headway.
What it costs
Nothing. Edge functions are within Netlify's free allowance, and with the cache in front, the extra load on arlts.org is a few little calls an hour.
The numbers are live at https://phaninitiatives.org, and the app they come from is at https://arlts.org. Free, non-profit, no account needed.
Comments
No comments yet. Start the discussion.