If you build a Muslim app (prayer times, a Hijri calendar, morning/evening azkar), you usually call more than one JSON source. Calling them straight from the browser or the mobile app causes three problems:
-
CORS. Many JSON files are served without
Access-Control-Allow-Origin, so the browser blocks afetch()from your own domain. - Latency and quota. Every user downloads the same data again, and if the upstream needs an API key you can't put that key in front-end code.
- Resilience. If the upstream has a short outage, your app shows an empty screen.
A small backend proxy with caching fixes all three. In this tutorial we build one in Node.js + Express (about 100 lines, no database). It sits in front of the public JSON samples of the SunnahSource Islamic API.
Quick-start snippets for JavaScript, Python and Flutter are in the GitHub repo README: https://github.com/sunnahsourceofficial-droid/sunnahsource-islamic-api
The data we will proxy
SunnahSource publishes a free sample file for each API under https://sunnahsource.org/data/json/<name>.json. We will use four of them:
| Dataset | Sample URL | API page |
|---|---|---|
| Prayer times | https://sunnahsource.org/data/json/prayer-times.json |
Prayer Times API |
| Hijri months | https://sunnahsource.org/data/json/hijri-calendar.json |
Hijri Calendar API |
| Azkar | https://sunnahsource.org/data/json/azkar.json |
Azkar API |
| Duas | https://sunnahsource.org/data/json/duas.json |
Duas API |
Here is the start of the prayer-times sample, exactly as served (shortened):
{
"city": "Makkah",
"country": "Saudi Arabia",
"date": "2026-07-30",
"timezone": "Asia/Riyadh",
"method": "Umm Al-Qura",
"times": {
"fajr": "04:42",
"sunrise": "05:58",
"dhuhr": "12:35",
"asr": "15:52",
"maghrib": "19:12",
"isha": "20:42"
},
"items": [
{
"prayer": "Fajr",
"arabic": "الفجر",
"time": "04:42",
"translations": { "en": "Dawn prayer before sunrise", "ur": "...", "ar": "...", "id": "...", "ms": "..." }
}
],
"note": "Sample prayer times. Full API supports any city worldwide with multiple calculation methods."
}
And the Hijri sample lists months with Arabic and English names plus translated notes:
{
"title": "Hijri Calendar",
"current_hijri": "1447 AH",
"months": [
{ "number": 1, "name_ar": "مُحَرَّم", "name_en": "Muharram", "days": 30, "translations": { "en": "...", "ur": "..." } }
]
}
These files are samples: the prayer-times file is one fixed day for Makkah, so it is good for building and testing your UI, not for showing real times to users. For live data in any city, you request an API key on the Prayer Times API page. Because the key then lives only on your server, the proxy we build here is also where it will go.
Project setup
You need Node.js 18 or newer, because we use the built-in fetch and AbortSignal.timeout.
mkdir islamic-proxy && cd islamic-proxy
npm init -y
npm pkg set type=module
npm i express
The design in one paragraph
The proxy only forwards an allowlist of dataset names, so it can't be abused as an open proxy. Each dataset is cached in memory for one hour. If ten requests arrive while the cache is cold, only one upstream request is made (request coalescing). Every response carries an ETag, so clients that already have the data get a 304 Not Modified with no body. If the upstream fails and we have an old copy, we serve the stale copy instead of an error. CORS is opened only for your own front-end origins.
The code
Create server.js:
// server.js — a tiny caching proxy for SunnahSource JSON samples
import express from "express";
import { createHash } from "node:crypto";
const UPSTREAM = "https://sunnahsource.org/data/json";
// Only these sample files may be proxied (no open proxy!)
const ALLOWED = new Set(["prayer-times", "hijri-calendar", "azkar", "duas"]);
const TTL_MS = 60 * 60 * 1000; // 1 hour
const PORT = process.env.PORT || 3000;
const cache = new Map(); // name -> { body, etag, fetchedAt }
const inflight = new Map(); // name -> Promise (request coalescing)
async function fetchUpstream(name) {
const res = await fetch(`${UPSTREAM}/${name}.json`, {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(8000),
});
if (!res.ok) throw new Error(`Upstream ${res.status} for ${name}`);
const data = await res.json(); // throws if not valid JSON
const body = JSON.stringify(data);
const etag = `"${createHash("sha1").update(body).digest("hex")}"`;
const entry = { body, etag, fetchedAt: Date.now() };
cache.set(name, entry);
return entry;
}
async function getCached(name) {
const hit = cache.get(name);
const fresh = hit && Date.now() - hit.fetchedAt < TTL_MS;
if (fresh) return { entry: hit, status: "HIT" };
if (!inflight.has(name)) {
inflight.set(name, fetchUpstream(name).finally(() => inflight.delete(name)));
}
try {
return { entry: await inflight.get(name), status: "MISS" };
} catch (err) {
if (hit) return { entry: hit, status: "STALE" }; // serve stale on error
throw err;
}
}
const app = express();
app.disable("x-powered-by");
// CORS for your own front-ends only
const ORIGINS = (process.env.ALLOWED_ORIGINS || "http://localhost:5173").split(",");
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && ORIGINS.includes(origin)) {
res.set("Access-Control-Allow-Origin", origin);
res.set("Vary", "Origin");
}
next();
});
// A small "today" endpoint that merges two datasets
// (registered before /api/:name so "today" is not treated as a dataset name)
app.get("/api/today", async (_req, res) => {
try {
const [pt, az] = await Promise.all([getCached("prayer-times"), getCached("azkar")]);
const prayer = JSON.parse(pt.entry.body);
const azkar = JSON.parse(az.entry.body);
res.json({
city: prayer.city,
method: prayer.method,
times: prayer.times,
morningAdhkar: azkar.items
.filter((i) => i.category === "morning")
.map(({ arabic, transliteration, repeat, translations }) => ({
arabic, transliteration, repeat, en: translations?.en,
})),
});
} catch {
res.status(502).json({ error: "upstream unavailable" });
}
});
app.get("/api/:name", async (req, res) => {
const { name } = req.params;
if (!ALLOWED.has(name)) return res.status(404).json({ error: "unknown dataset" });
try {
const { entry, status } = await getCached(name);
res.set({
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "public, max-age=300",
ETag: entry.etag,
"X-Cache": status,
});
if (req.headers["if-none-match"] === entry.etag) return res.status(304).end();
res.send(entry.body);
} catch (err) {
console.error(err.message);
res.status(502).json({ error: "upstream unavailable" });
}
});
app.listen(PORT, () => console.log(`Proxy on http://localhost:${PORT}`));
Run it:
node server.js
# Proxy on http://localhost:3000
Try it
First call (cold cache):
curl -i http://localhost:3000/api/prayer-times
# HTTP/1.1 200 OK
# ETag: "775be138f320c6f34724984ef3af62ea3c0a6243"
# X-Cache: MISS
Repeat the call with the ETag. You get a 304 with an empty body, served from memory:
curl -i -H 'If-None-Match: "775be138f320c6f34724984ef3af62ea3c0a6243"' \
http://localhost:3000/api/prayer-times
# HTTP/1.1 304 Not Modified
# X-Cache: HIT
(Your ETag will be different if the sample file changes. Copy it from your own first response.)
The merged endpoint returns the sample times plus the morning items of the azkar sample in one small payload. Your home screen then needs only one request:
curl http://localhost:3000/api/today
# {"city":"Makkah","method":"Umm Al-Qura",
# "times":{"fajr":"04:42","sunrise":"05:58","dhuhr":"12:35","asr":"15:52","maghrib":"19:12","isha":"20:42"},
# "morningAdhkar":[ { "arabic": "...", "transliteration": "...", "repeat": ..., "en": "..." }, ... ]}
Names outside the allowlist are rejected:
curl http://localhost:3000/api/anything-else
# {"error":"unknown dataset"}
Calling it from the front-end
From React, Vue, Svelte or plain JS, you now call your own origin. There's no CORS error, and the browser handles the ETag for you:
const res = await fetch("http://localhost:3000/api/hijri-calendar");
const { months } = await res.json();
for (const m of months) {
console.log(m.number, m.name_en, m.name_ar);
}
Start the server with your real origins:
ALLOWED_ORIGINS="https://myapp.com,http://localhost:5173" node server.js
Why each piece matters
-
Allowlist (
ALLOWED). Without it,/api/:namecould be pointed at any file. Keep the list explicit. -
TTL cache. Prayer-time and calendar data change at most daily, so a one-hour TTL removes almost all upstream traffic. Tune
TTL_MSper dataset if you like. -
Request coalescing (
inflight). This prevents a "thundering herd" when the cache expires during a traffic spike, for example right before Maghrib in Ramadan. - Stale-on-error. A short upstream outage becomes invisible to your users.
-
ETag +
Cache-Control. Mobile clients save bandwidth, and a CDN in front of the proxy can cache it too. -
Timeout (
AbortSignal.timeout(8000)). A slow upstream can't hold your Express workers forever.
Going to production
- Replace the sample URLs with the production endpoint and send your API key from the server (for example in a header read from
process.env). Never ship the key in app code. You get the endpoint and key after applying on any API page, for example the Prayer Times API. - If you run several instances, swap the
Mapfor Redis and keep the samegetCached()interface. - Put real prayer-time logic (the user's city, calculation method, timezone) on the server side, next to the cache key, for example
prayer-times:jeddah:umm-al-qura:2026-11-21. - Add rate limiting (for example
express-rate-limit) before you expose the proxy publicly.
Wrapping up
With about 100 lines of Express you get CORS control, caching, ETags and resilience in front of Islamic JSON data. The same proxy can serve every dataset your app needs. Add quran-translations, hadith, asma-ul-husna or others to the allowlist when you need them. See all of them at sunnahsource.org: the Quran API, the Hadith API and the 99 Names of Allah API.
If you're building a full Muslim app and want help, SunnahSource also does Islamic app development. Quick-start snippets for other stacks are in the repo README: https://github.com/sunnahsourceofficial-droid/sunnahsource-islamic-api. Stars and issues are welcome.
Top comments (0)