Node 24 runs .ts files directly (type stripping), so a small TypeScript tool no longer needs tsc, ts-node or a bundler. In this tutorial we use that to build a typed command-line reader for a free Quran JSON sample from SunnahSource:
-
Free Quran API (Quran Translations):
https://sunnahsource.org/data/json/quran-translations.json
The tool will:
- describe the JSON with TypeScript interfaces, and validate it at runtime (types disappear when the code runs)
- print ayahs of Surah Al-Fatiha in any of 9 languages, with an English fallback
- search translations and transliteration
- cache the file and revalidate with
ETag/If-None-Match(a304reuses the local copy) - work offline from the cache
- export an accessible HTML page where every paragraph has the right
langanddir(Urdu and Arabic are right-to-left) - have unit tests with the built-in
node:testrunner
No npm packages are needed at runtime.
1. Look at the data first
curl -s https://sunnahsource.org/data/json/quran-translations.json | head -c 600
The root object has title, description, is_free, a surah object, an ayahs array and a languages array:
{
"surah": { "number": 1, "name_arabic": "الفاتحة", "name_english": "Al-Fatiha",
"name_urdu": "الفاتحہ", "ayah_count": 7, "revelation": "Makkah" },
"ayahs": [
{ "number": 1,
"arabic": "بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ",
"transliteration": "Bismillahir Rahmanir Raheem",
"translations": { "en": "In the name of Allah, the Entirely Merciful, the Especially Merciful.",
"ur": "شروع اللہ کے نام سے جو بڑا مہربان نہایت رحم والا ہے۔", "...": "..." } }
],
"languages": [{ "code": "en", "name": "English" }, { "code": "ur", "name": "Urdu" }, "..."]
}
The 9 language codes are en ur fr de ru tr ms zh-CN ja.
2. Project setup
You need Node.js 24 or newer (node --version). Create a folder with this package.json. "type": "module" allows top-level await:
{
"name": "quran-ts",
"type": "module",
"scripts": { "test": "node --test" }
}
3. The typed client: quran.ts
This file has the interfaces, a runtime validator, helpers and the cached loader.
// quran.ts: typed client for the SunnahSource Quran Translations sample (Node 24+, no dependencies)
import { readFile, writeFile, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { homedir } from "node:os";
export const URL_JSON = "https://sunnahsource.org/data/json/quran-translations.json";
export interface Language { code: string; name: string }
export interface Ayah {
number: number;
arabic: string;
transliteration: string;
translations: Record<string, string>;
}
export interface Surah {
number: number;
name_arabic: string;
name_english: string;
name_urdu: string;
ayah_count: number;
revelation: string;
}
export interface QuranSample {
title: string;
description: string;
is_free: boolean;
surah: Surah;
ayahs: Ayah[];
languages: Language[];
}
// ---- runtime validation (TypeScript types disappear at runtime) ----
const isObj = (v: unknown): v is Record<string, unknown> =>
typeof v === "object" && v !== null && !Array.isArray(v);
export function parseSample(raw: unknown): QuranSample {
if (!isObj(raw)) throw new Error("root is not an object");
const { surah, ayahs, languages } = raw;
if (!isObj(surah) || typeof surah.number !== "number" || typeof surah.name_english !== "string")
throw new Error("bad 'surah'");
if (!Array.isArray(ayahs) || ayahs.length === 0) throw new Error("bad 'ayahs'");
for (const a of ayahs) {
if (!isObj(a) || typeof a.number !== "number" || typeof a.arabic !== "string" || !isObj(a.translations))
throw new Error(`bad ayah: ${JSON.stringify(a).slice(0, 80)}`);
}
if (!Array.isArray(languages) || !languages.every((l) => isObj(l) && typeof l.code === "string"))
throw new Error("bad 'languages'");
if (surah.ayah_count !== ayahs.length)
throw new Error(`ayah_count ${String(surah.ayah_count)} != ${ayahs.length} ayahs`);
return raw as unknown as QuranSample;
}
// ---- helpers ----
const RTL = new Set(["ar", "ur", "fa", "he"]);
export const dirOf = (lang: string): "rtl" | "ltr" => (RTL.has(lang.split("-")[0]) ? "rtl" : "ltr");
export function translation(a: Ayah, lang: string): { lang: string; text: string } {
const text = a.translations[lang];
return text ? { lang, text } : { lang: "en", text: a.translations.en ?? "" };
}
export function search(s: QuranSample, q: string): Ayah[] {
const needle = q.toLocaleLowerCase();
return s.ayahs.filter((a) =>
[a.transliteration, ...Object.values(a.translations)].some((t) => t.toLocaleLowerCase().includes(needle)),
);
}
const esc = (t: string) =>
t.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]!);
export function toHtml(s: QuranSample, langs: string[]): string {
const rows = s.ayahs.map((a) => {
const tr = langs.map((l) => {
const t = translation(a, l);
return ` <p lang="${t.lang}" dir="${dirOf(t.lang)}">${esc(t.text)}</p>`;
});
return [
` <section id="ayah-${a.number}">`,
` <p lang="ar" dir="rtl" class="ar">${esc(a.arabic)} (${a.number})</p>`,
` <p class="tr"><i>${esc(a.transliteration)}</i></p>`,
...tr,
` </section>`,
].join("\n");
});
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Surah ${esc(s.surah.name_english)} (${s.surah.number})</title>
<style>body{font-family:system-ui;max-width:46rem;margin:2rem auto;padding:0 1rem}.ar{font-size:1.8rem;line-height:2.4}section{border-bottom:1px solid #ddd;padding:.5rem 0}</style>
</head>
<body>
<h1 lang="ar" dir="rtl">${esc(s.surah.name_arabic)}</h1>
<p>Surah ${esc(s.surah.name_english)}: ${s.surah.ayah_count} ayahs, revealed in ${esc(s.surah.revelation)}</p>
${rows.join("\n")}
<p><small>Data: <a href="https://sunnahsource.org/apis/quran-translations/">SunnahSource Quran API</a></small></p>
</body>
</html>
`;
}
// ---- fetch with an ETag cache (304 = reuse the local copy) ----
const CACHE_DIR = process.env.QURAN_CACHE ?? join(homedir(), ".cache", "quran-ts");
export async function load(opts: { offline?: boolean } = {}): Promise<{ data: QuranSample; source: string }> {
const body = join(CACHE_DIR, "quran-translations.json");
const tag = join(CACHE_DIR, "etag.txt");
const cached = await readFile(body, "utf8").catch(() => null);
if (opts.offline) {
if (!cached) throw new Error("offline and no cache yet");
return { data: parseSample(JSON.parse(cached)), source: "cache (offline)" };
}
const etag = cached ? await readFile(tag, "utf8").catch(() => "") : "";
const res = await fetch(URL_JSON, {
headers: etag ? { "If-None-Match": etag } : {},
signal: AbortSignal.timeout(15_000),
});
if (res.status === 304 && cached) return { data: parseSample(JSON.parse(cached)), source: "cache (304)" };
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const text = await res.text();
const data = parseSample(JSON.parse(text)); // validate before caching
await mkdir(CACHE_DIR, { recursive: true });
await writeFile(body, text);
await writeFile(tag, res.headers.get("etag") ?? "");
return { data, source: "network (200)" };
}
A few notes:
-
parseSamplechecks the shape and a real invariant:surah.ayah_countmust equal the number of ayahs. If the server ever returns something unexpected, you get a clear error instead ofundefineddeep in your UI. - The cache is only written after validation, so a broken response never replaces a good cached copy.
- The server sends an
ETag. We store it and send it back asIf-None-Match; when nothing changed, the server answers304with no body. -
dirOfkeeps a tiny list of right-to-left languages.zh-CNis split on-so region codes work. - The code only uses "erasable" TypeScript (interfaces, type annotations,
as), which is exactly what Node's type stripping supports. Noenumand no parameter properties.
4. The CLI: cli.ts
node:util's parseArgs handles flags without a dependency:
// cli.ts: node cli.ts [--lang ur,fr] [--ayah 5] [--search mercy] [--html out.html] [--offline]
import { parseArgs } from "node:util";
import { writeFile } from "node:fs/promises";
import { load, translation, search, toHtml } from "./quran.ts";
const { values } = parseArgs({
options: {
lang: { type: "string", default: "en" },
ayah: { type: "string" },
search: { type: "string" },
html: { type: "string" },
offline: { type: "boolean", default: false },
langs: { type: "boolean", default: false },
},
});
const { data, source } = await load({ offline: values.offline });
const langs = values.lang.split(",").map((l) => l.trim());
console.error(`# ${data.surah.name_english} (${data.surah.name_arabic}), ${data.ayahs.length} ayahs, ${source}`);
if (values.langs) {
for (const l of data.languages) console.log(`${l.code.padEnd(6)} ${l.name}`);
} else if (values.html) {
await writeFile(values.html, toHtml(data, langs));
console.log(`wrote ${values.html}`);
} else {
let ayahs = data.ayahs;
if (values.ayah) ayahs = ayahs.filter((a) => a.number === Number(values.ayah));
if (values.search) ayahs = search(data, values.search);
if (ayahs.length === 0) {
console.error("no matching ayah");
process.exitCode = 1;
}
for (const a of ayahs) {
console.log(`\n[1:${a.number}] ${a.arabic}`);
console.log(` ${a.transliteration}`);
for (const l of langs) {
const t = translation(a, l);
console.log(` ${t.lang}${t.lang !== l ? ` (no '${l}', fallback)` : ""}: ${t.text}`);
}
}
}
5. Run it
node cli.ts --ayah 1 --lang en,ur
# Al-Fatiha (الفاتحة), 7 ayahs, network (200)
[1:1] بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ
Bismillahir Rahmanir Raheem
en: In the name of Allah, the Entirely Merciful, the Especially Merciful.
ur: شروع اللہ کے نام سے جو بڑا مہربان نہایت رحم والا ہے۔
Run it again and the header says cache (304). An unknown language falls back to English:
node cli.ts --ayah 5 --lang ja,xx
# Al-Fatiha (الفاتحة), 7 ayahs, cache (304)
[1:5] إِيَّاكَ نَعْبُدُ وَإِيَّاكَ نَسْتَعِينُ
Iyyaka na'budu wa iyyaka nasta'een
ja: 我々は只あなたに仕え、只あなたに助けを求める。
en (no 'xx', fallback): It is You we worship and You we ask for help.
Other commands:
node cli.ts --langs # list the 9 languages
node cli.ts --search merciful # matches ayahs 1 and 3
node cli.ts --html fatiha.html --lang en,ur,fr
node cli.ts --offline --ayah 7 # no network, uses the cache
node cli.ts --ayah 9; echo $? # "no matching ayah", exit code 1
The HTML export writes one <section id="ayah-N"> per ayah. The Arabic line has lang="ar" dir="rtl", the Urdu line lang="ur" dir="rtl", and the other languages dir="ltr". Screen readers pick the right voice and browsers lay out each paragraph correctly, even when Arabic, Urdu and French are on the same page. All text is HTML-escaped.
6. Tests: quran.test.ts
import { test } from "node:test";
import assert from "node:assert/strict";
import { parseSample, translation, dirOf, search, toHtml, type QuranSample } from "./quran.ts";
const sample: QuranSample = {
title: "t", description: "d", is_free: true,
surah: { number: 1, name_arabic: "الفاتحة", name_english: "Al-Fatiha", name_urdu: "الفاتحہ", ayah_count: 1, revelation: "Makkah" },
ayahs: [{ number: 1, arabic: "بِسْمِ اللَّهِ", transliteration: "Bismillah", translations: { en: "In the name of Allah <x>", ur: "اللہ کے نام سے" } }],
languages: [{ code: "en", name: "English" }],
};
test("parseSample accepts valid data", () => assert.equal(parseSample(structuredClone(sample)).surah.number, 1));
test("parseSample rejects count mismatch", () => {
const bad = structuredClone(sample); bad.surah.ayah_count = 7;
assert.throws(() => parseSample(bad), /ayah_count/);
});
test("parseSample rejects missing ayahs", () => assert.throws(() => parseSample({ surah: sample.surah }), /ayahs/));
test("translation falls back to English", () => {
assert.equal(translation(sample.ayahs[0], "ur").lang, "ur");
assert.equal(translation(sample.ayahs[0], "xx").lang, "en");
});
test("dirOf handles RTL and region codes", () => {
assert.equal(dirOf("ur"), "rtl"); assert.equal(dirOf("ar"), "rtl"); assert.equal(dirOf("zh-CN"), "ltr");
});
test("search is case-insensitive", () => assert.equal(search(sample, "BISMILLAH").length, 1));
test("toHtml escapes text and sets lang/dir", () => {
const html = toHtml(sample, ["en", "ur"]);
assert.match(html, /<x>/);
assert.match(html, /<p lang="ur" dir="rtl">/);
assert.doesNotMatch(html, /<x>/);
});
node --test
ℹ tests 7
ℹ pass 7
ℹ fail 0
If you also want a strict type check in CI, add TypeScript as a dev dependency and run:
npx tsc --noEmit --strict --allowImportingTsExtensions --erasableSyntaxOnly \
--module nodenext --target es2022 --types node quran.ts cli.ts quran.test.ts
(npm i -D typescript @types/node.) It passes with no errors.
7. Ideas to extend it
- Turn
toHtmlinto a static site: one page per language, withhreflanglinks between them. - Show a "verse of the day" in a terminal greeting or a cron job.
- Reuse the same validate-then-cache pattern for other datasets, for example the Word by Word Quran API, the Tafseer API or the Hadith API.
Notes
- Arabic and Urdu print fine in any UTF-8 terminal; right-to-left shaping depends on your terminal. The HTML export is the better way to read them.
- Please cache. With the
ETagcheck, repeat runs only cost a tiny304. - The public JSON file is a free sample (Surah Al-Fatiha). For the full API and an API key, apply on the Quran API page or see pricing.
More examples and the list of endpoints are in the GitHub repo: sunnahsourceofficial-droid/sunnahsource-islamic-api.
Top comments (0)