# Public delivery API (Prompt 5B) — for the Next.js site and apps

Base: `/api/v1/public`. No auth. JSON envelope `{data, meta, links}`; Nepali text is
`{ne, en}` objects (pick by the reader's language, fall back to `ne`). Dates are
`{iso, bs: {year, month, day, formatted_ne, formatted_en}}` (Asia/Kathmandu).
Full schemas and examples: `/docs/api` (OpenAPI in `docs/openapi.json`).

## Building the homepage design

`GET /home` returns the whole page in one call: `data.layout`, `data.today` (AD + BS for
the top bar) and `data.sections[]` in display order. Each section is
`{uid, type, title, settings, …}`; render by `type`:

| # | Design block | `type` | Payload |
| --- | --- | --- | --- |
| 1 | Top bar | `top_bar` | `settings.weather_district`, `show_bs_date`, `language_switch` (weather comes in Prompt 6) |
| 2 | Header + menu | `header` | `menu` = nested items of the `header` menu (`label`, `url`, `children`) |
| 3 | Breaking ticker | `breaking_ticker` | `items[]` (live, auto-expiring) — poll `GET /breaking` every 30 s |
| 4 | Top Stories | `top_stories` | `stories[]` — `stories[0]` is the lead, the rest the side stories |
| 5 | Latest News | `latest_news` | `tabs[] {key, label, stories[]}`; poll `GET /just-in` for "Just in" |
| 6 | News From Across Nepal | `news_across_nepal` | `provinces[] {province, story_count, stories[]}` (7 provinces; module `regions`) |
| 7 | Watch Nepal | `watch_nepal` | `stories[]` (video stories) + `settings.tabs` (module `video`; players in Prompt 6) |
| 8 | FM Radio | `fm_radio` | `settings.station`, `frequency`, `stream_url` (module `radio`; schedule in Prompt 6) |
| 9 | Business News | `business_news` | `stories[]`, `settings.chips`, `settings.market_strip` (market data in Prompt 6) |
| 10 | Explore Wild West Nepal | `explore` | `stories[]` (module `explore`) |
| 11 | Lifestyle, Food & Culture | `lifestyle_grid` | `stories[]` with `primary_category` labels |
| 12 | Events | `events` | `settings.calendar_url` (module `events`; events feed in Prompt 6) |
| 13 | Community & Inspiring Nepal | `community` | `stories[]` |
| 14 | Footer | `footer` | `menus {footer-about, footer-explore, footer-services, footer-policies}`, `site` (public settings), `settings.district_links` |

Also available: `newsletter_cta`, `ad_slot` (module `ads`), `custom_html` (purified
`settings.html`). A section is **left out** when its module is off, it is inactive or it
is outside its `starts_at`/`ends_at` window. A scheduled layout (e.g. election day)
replaces the default while live — the response shape stays the same.

Story cards (`stories[]` everywhere): `uid, slug, url, language, content_type, headline,
short_headline, summary, primary_category, district, flags, reading_time, image
{src, srcset {webp, jpg}, sizes, width, height, alt, caption, credit, og}, authors
[{username, name, verified}], published_at`.

## Endpoints

| Endpoint | Use | Cache (max-age / s-maxage) |
| --- | --- | --- |
| `GET /home` | homepage (above) | 30 s / 60 s |
| `GET /stories/{slug\|uid}` | story page | 60 s / 300 s |
| `GET /stories?category=&tag=&topic=&province=&district=&local_level=&author=&type=&language=&flags=&per_page=&cursor=` | any list, cursor-paginated (`meta.next_cursor`) | 60 / 300 |
| `GET /latest?category=&limit=` | latest | 60 / 300 |
| `GET /just-in?minutes=60&limit=` | "Just in" (poll) | 15 / 30 |
| `GET /trending?limit=` | most viewed, last 6 h | 60 / 300 |
| `GET /most-read?period=day\|week\|month` | most read | 60 / 300 |
| `GET /related/{uid}` | related stories | 60 / 300 |
| `POST /stories/{uid}/view` | view beacon — send once after a story renders | not cached, 204 |
| `GET /categories/{slug}` | category page: `data.category` (+parent, children) + `data.stories` | 60 / 300 |
| `GET /locations/{province\|district\|local-level}/{slug}` | region pages (module `regions`) | 60 / 300 |
| `GET /authors/{username}` | author page (verified badge, bio, avatar) | 60 / 300 |
| `GET /topics/{slug}` | topic page | 60 / 300 |
| `GET /search?q=&…filters&page=` | search (Nepali or Romanised), `highlight` per result | 60 / 300 |
| `GET /search/suggest?q=` | search-box suggestions | 60 / 300 |
| `GET /menus/{key}` | `header`, `main` (old site), `more` (थप), `footer-*` | 300 / 3600 |
| `GET /pages/{slug}` | about, our-team, contact, advertise, careers, privacy, terms, editorial-policy, corrections-policy, grievance, send-a-tip | 300 / 3600 |
| `GET /team` | Our Team | 300 / 3600 |
| `GET /settings` | `{site, contact, social, legal, radio, weather, newsletter}` | 300 / 3600 |
| `GET /breaking` | ticker | 15 / 30 |
| `GET /redirects/resolve?path=` | old URL → `{to, status}` or 404 | 300 / 3600 |
| `GET /preview/{token}` | draft preview (Next.js draft mode), `no-store` | — |
| `GET /sitemaps/index.xml`, `news.xml` (48 h), `categories.xml`, `locations.xml`, `authors.xml`, `archive/{YYYY}-{MM}.xml` | sitemaps (proxy them from the site root) | 600 / 1800 |
| `GET /rss/latest.xml`, `/rss/{category\|district\|author}/{slug}.xml` | RSS 2.0 | 600 / 1800 |

**Story page**: `blocks`, `body_html`, `media[]` (with `srcset`), `featured_image`, `authors`
(with `verified`, `url`), `locations`, `published_at` / `first_published_at` / `updated_at`
(BS + AD), `reading_time`, `corrections[]`, `breadcrumbs[]`, and `structured_data`
— two schema.org objects (`NewsArticle`, `BreadcrumbList`) to print as JSON-LD.

**`?lite=1`** (any list, story or home): small cards `{uid, slug, url, headline (one
language), category, published_at, image (one 320 px URL)}`; the story drops blocks, media,
taxonomy and structured data. Use it on 2G / data-saver.

**Paths** in `url` fields follow `WEB_STORY_PATH=/news/{slug}`, `WEB_CATEGORY_PATH=/category/{slug}`,
`WEB_LOCATION_PATH=/{type}/{slug}`, `WEB_AUTHOR_PATH=/author/{username}`, `WEB_PAGE_PATH=/{slug}` —
set them to the site's routes.

## Caching and freshness

- Every GET sends `Cache-Control: public, max-age, s-maxage, stale-while-revalidate` and an
  `ETag`; send `If-None-Match` to get `304`.
- The API's own Redis caches (tags `stories`, `public`, `site:*`) are flushed the moment a
  story is published, updated or unpublished, or site content changes.
- **On-demand revalidation**: on publish / update / unpublish and site changes the API
  POSTs (queue `high`, 5 tries, back-off 5/15/30/60 s) to `NEXT_REVALIDATE_URL`:

  ```json
  {"paths": ["/", "/news/{slug}", "/category/national"], "tags": ["stories", "home", "story:{uid}", "category:national", "district:kailali", "author:{username}"], "sent_at": "1764230400"}
  ```

  Headers: `X-Paschim-Timestamp` (unix seconds) and
  `X-Paschim-Signature: sha256=` + HMAC-SHA256(`NEXT_REVALIDATE_SECRET`, `"{timestamp}.{raw body}"`).
  Verify in the route handler (reject if the timestamp is older than 5 minutes):

  ```ts
  const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(`${ts}.${rawBody}`).digest('hex');
  if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature))) return new Response(null, { status: 401 });
  paths.forEach(p => revalidatePath(p)); tags.forEach(t => revalidateTag(t));
  ```
- **CDN**: `CDN_PURGE_DRIVER=cloudflare` + `CLOUDFLARE_ZONE_ID` / `CLOUDFLARE_API_TOKEN` purges the
  site URLs and `/api/v1/public/{home,latest,just-in,breaking}`. A published story is live
  within 30 s even without the webhook (short TTLs).

## Old URLs

Next.js middleware: for an unknown path call `/redirects/resolve?path=` and redirect on
`{to, status}`. Covered: the `redirects` table (CMS-managed; `/team.php`, `/mero_palika.php`
seeded) and old article URLs `/news-details/{id}/{date}`, `/news-article/{id}/{category}`
(through `stories.legacy_id`, filled by the importer in Prompt 10). Old URLs that hit the
API domain directly are redirected by the `HandleLegacyRedirects` middleware.
