Prayer times are the first feature almost every Muslim app needs. In this tutorial we build a small Next.js 15 (App Router) widget that:

  • fetches prayer times JSON on the server (so browser CORS rules never get in the way),
  • caches it with ISR (revalidate: 3600),
  • shows Fajr, Dhuhr, Asr, Maghrib and Isha with their Arabic names,
  • highlights the next prayer and counts down to it, in the city's own time zone, not the visitor's or the server's,
  • keeps the time logic in plain functions you can unit test with node --test.

The data comes from the public sample of the SunnahSource Prayer Times API:

https://sunnahsource.org/data/json/prayer-times.json 

The sample is a fixed day for one city (Makkah, Umm Al-Qura method). The full API covers any city with several calculation methods. You request a key on the Prayer Times API page. The widget below works the same way with both, because it only reads timezone, times and items.

1. What the JSON looks like

{ "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": "…" } } // … Dhuhr, Asr, Maghrib, Isha ], "note": "Sample prayer times. …" } 

Two details matter:

  1. times is a plain "HH:MM" map that includes sunrise. Sunrise is not a prayer, so the countdown has to skip it.
  2. timezone is an IANA zone. A visitor in London who opens a Makkah timetable should see the countdown to Makkah's next prayer, so we calculate "now" in that zone.

The file has no Access-Control-Allow-Origin header, so a browser fetch() from your domain would be blocked. Fetching in a Server Component avoids that.

2. Project setup

npx create-next-app@latest prayer-widget --js --app --no-tailwind --no-eslint cd prayer-widget 

(Or add next@15 react@19 react-dom@19 to an existing project.) Final structure:

app/ layout.jsx page.jsx # Server Component: fetches + caches the JSON PrayerWidget.jsx # Client Component: countdown + highlight lib/ getPrayerTimes.js # server-only fetch helper prayer.mjs # pure time helpers prayer.test.mjs # node:test unit tests 

3. Pure time helpers (lib/prayer.mjs)

Keep the date maths out of React. That makes it easy to test, and the same file works in the browser and in Node.

// lib/prayer.mjs — pure helpers, no React, easy to unit test export const ORDER = ["fajr", "sunrise", "dhuhr", "asr", "maghrib", "isha"]; /** "HH:MM" -> minutes since midnight */ export function toMinutes(hhmm) { const [h, m] = hhmm.split(":").map(Number); return h * 60 + m; } /** Current wall-clock minutes in an IANA time zone (e.g. "Asia/Riyadh") */ export function minutesInZone(timeZone, now = new Date()) { const parts = new Intl.DateTimeFormat("en-GB", { timeZone, hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23", }).formatToParts(now); const get = (t) => Number(parts.find((p) => p.type === t).value); return get("hour") * 60 + get("minute") + get("second") / 60; } /** Next prayer after `nowMin`; wraps to tomorrow's Fajr after Isha. Sunrise is skipped. */ export function nextPrayer(times, nowMin) { const list = ORDER.filter((k) => k !== "sunrise" && times[k]) .map((k) => ({ key: k, at: toMinutes(times[k]) })); const upcoming = list.find((p) => p.at > nowMin); if (upcoming) return { ...upcoming, minutesLeft: upcoming.at - nowMin, tomorrow: false }; const first = list[0]; return { ...first, minutesLeft: 24 * 60 - nowMin + first.at, tomorrow: true }; } /** 125.5 -> "2h 05m" */ export function formatLeft(min) { const total = Math.max(0, Math.floor(min)); const h = Math.floor(total / 60); const m = String(total % 60).padStart(2, "0"); return h ? `${h}h ${m}m` : `${m}m`; } 

minutesInZone uses Intl.DateTimeFormat with timeZone, so no date library is needed. hourCycle: "h23" avoids the 24:00 that some engines return at midnight with hour12: false.

4. Test it before touching React (lib/prayer.test.mjs)

import test from "node:test"; import assert from "node:assert/strict"; import { toMinutes, nextPrayer, formatLeft, minutesInZone } from "./prayer.mjs"; const times = { fajr: "04:42", sunrise: "05:58", dhuhr: "12:35", asr: "15:52", maghrib: "19:12", isha: "20:42" }; test("toMinutes", () => assert.equal(toMinutes("12:35"), 755)); test("before Fajr", () => assert.equal(nextPrayer(times, 60).key, "fajr")); test("skips sunrise", () => assert.equal(nextPrayer(times, toMinutes("05:00")).key, "dhuhr")); test("between Asr and Maghrib", () => { const n = nextPrayer(times, toMinutes("16:00")); assert.equal(n.key, "maghrib"); assert.equal(n.minutesLeft, 192); }); test("after Isha wraps to tomorrow's Fajr", () => { const n = nextPrayer(times, toMinutes("22:00")); assert.deepEqual([n.key, n.tomorrow, n.minutesLeft], ["fajr", true, 120 + 282]); }); test("formatLeft", () => { assert.equal(formatLeft(125.9), "2h 05m"); assert.equal(formatLeft(7), "07m"); }); test("minutesInZone uses the zone, not the server clock", () => { // 2026-07-30 09:00 UTC = 12:00 in Riyadh (UTC+3, no DST) assert.equal(minutesInZone("Asia/Riyadh", new Date("2026-07-30T09:00:00Z")), 720); }); 
node --test lib/prayer.test.mjs # ℹ tests 7 # ℹ pass 7 

The last test is the important one. It pins the clock to a UTC instant and checks that we get Riyadh wall-clock time, whatever zone your laptop or CI server is in.

5. Server-side fetch with caching (lib/getPrayerTimes.js)

// lib/getPrayerTimes.js — runs on the server only const SOURCE = "https://sunnahsource.org/data/json/prayer-times.json"; export async function getPrayerTimes() { const res = await fetch(SOURCE, { next: { revalidate: 3600 } }); // cache for 1 hour if (!res.ok) throw new Error(`Prayer times request failed: ${res.status}`); const data = await res.json(); // keep only what the widget needs, so the client bundle stays tiny return { city: data.city, country: data.country, date: data.date, timezone: data.timezone, method: data.method, times: data.times, items: data.items.map(({ prayer, arabic, time, translations }) => ({ prayer, arabic, time, label: translations?.en ?? "", })), }; } 

next: { revalidate: 3600 } tells Next.js to cache the response and refresh it in the background at most once an hour. We also map items down to the fields we render, so less data is serialized into the page for the client component.

6. The client widget (app/PrayerWidget.jsx)

"use client"; import { useEffect, useState } from "react"; import { minutesInZone, nextPrayer, formatLeft } from "../lib/prayer.mjs"; export default function PrayerWidget({ data }) { const [now, setNow] = useState(null); // null on the server -> no hydration mismatch useEffect(() => { const tick = () => setNow(minutesInZone(data.timezone)); tick(); const id = setInterval(tick, 30_000); return () => clearInterval(id); }, [data.timezone]); const next = now === null ? null : nextPrayer(data.times, now); return ( <section style={{ maxWidth: 420, border: "1px solid #ddd", borderRadius: 12, padding: 16 }}> <header> <h2 style={{ margin: 0 }}>{data.city}, {data.country}</h2> <small>{data.method} · {data.timezone}</small> </header> <p aria-live="polite" style={{ fontSize: 18 }}> {next ? <>Next: <strong style={{ textTransform: "capitalize" }}>{next.key}</strong>{" "} in {formatLeft(next.minutesLeft)}{next.tomorrow ? " (tomorrow)" : ""}</> : "Loading…"} </p> <ul style={{ listStyle: "none", padding: 0, margin: 0 }}> {data.items.map((p) => { const active = next && p.prayer.toLowerCase() === next.key; return ( <li key={p.prayer} style={{ display: "flex", justifyContent: "space-between", padding: "8px 4px", borderTop: "1px solid #eee", fontWeight: active ? 700 : 400, background: active ? "#eef8f1" : "transparent", }}> <span title={p.label}>{p.prayer} <span lang="ar" dir="rtl">{p.arabic}</span></span> <time>{p.time}</time> </li> ); })} </ul> <small>Sunrise: {data.times.sunrise}</small> </section> ); } 

Notes:

  • Hydration safety. now starts as null, so the server HTML and the first client render match ("Loading…"). The real time is set in useEffect. If you compute the time during render, you get a hydration mismatch warning.
  • 30-second tick. We show minutes, so a 1-second interval only wastes battery.
  • Accessibility. aria-live="polite" lets screen readers announce the next-prayer line. The Arabic names get lang="ar" and dir="rtl".
  • The English description from translations.en is shown as a tooltip. Swap it for ur, ar, id or ms to localise.

7. The page (app/page.jsx) and layout

import PrayerWidget from "./PrayerWidget"; import { getPrayerTimes } from "../lib/getPrayerTimes"; export const revalidate = 3600; export default async function Page() { const data = await getPrayerTimes(); return ( <main> <h1>Prayer times</h1> <PrayerWidget data={data} /> <p style={{ fontSize: 12, color: "#666" }}> Data: <a href="https://sunnahsource.org/apis/prayer-times/">SunnahSource Prayer Times API</a> (sample for {data.date}) </p> </main> ); } 
export const metadata = { title: "Prayer times widget" }; export default function RootLayout({ children }) { return (<html lang="en"><body style={{ fontFamily: "system-ui, sans-serif", margin: 24 }}>{children}</body></html>); } 

8. Build and run

npx next build npx next start 

The build output shows the route as static with a 1 h revalidate:

Route (app) Size First Load JS Revalidate ┌ ○ / 1.23 kB 104 kB 1h 

Open http://localhost:3000. The server HTML already has the full timetable (good for SEO and slow phones). After hydration the countdown line switches from "Loading…" to something like "Next: maghrib in 3h 12m", and that row is highlighted.

9. Going further

  • Real cities. With an API key from the Prayer Times API, make the city a route segment (app/[city]/page.jsx) and pass it to getPrayerTimes(city). Keep the key in an environment variable. It is only read on the server, so it never reaches the browser.
  • Hijri date header. Add the month names from the Hijri Calendar API sample (/data/json/hijri-calendar.json, with months[].name_en / name_ar).
  • After-prayer adhkar. Link each prayer row to the after-prayer adhkar from the Azkar API.
  • Day rollover. After Isha the widget shows tomorrow's Fajr using today's time. That is close enough for a widget. For exact times, fetch tomorrow's timetable from the full API.

Source and links

If you build something with it, share it in the comments.