---
name: harborly-content-hub
description: Integrate Harborly-hosted content (blog articles, changelog, topbar announcement bar, privacy policy, terms of service, custom legal pages) into a website through Harborly's anonymous read-only Content Hub HTTP API. Use when the user asks to connect their Harborly product content, topbar announcements, or legal documents to their website, landing page, or docs site — for example "wire Harborly content and the topbar into my site". Optional `locale` selects a published translation; omit it for the product default language. Includes a complete Next.js App Router reference implementation, caching rules, an optional signed webhook receiver for fast cache invalidation, and a verification checklist.
version: 1.3.0
---

# Harborly Content Hub

Harborly is a per-product workspace. A product can publish **articles**, a **public changelog**, **topbar announcements**, and **legal documents** (privacy policy, terms of service, custom legal pages). The product's website reads all of them over an anonymous, read-only HTTP API — no redeploy is needed when content changes in Harborly.

The same endpoints serve every language the product has enabled — articles, changelog, announcements, and legal documents alike. Pass `locale` to read one language. Omit it and the API uses the product's default content language, so an existing single-language integration keeps working with no query changes. Legal documents are per-language too: each legal identity keeps one published copy per language, and legal details return `alternates` with the published languages.

This skill tells you (the coding agent) how to wire that API into a website and how to verify the result.

## When to use this skill

- The user asks to embed their Harborly articles (blog), changelog, topbar announcement bar, or legal pages (privacy policy, terms, custom legal documents) into their website.
- The user asks to "connect Harborly to my site", "publish my Harborly articles on my website", or similar.
- The user asks to serve that content in more than one language (localized routes, hreflang, or a language switcher).

**Not** this skill: writing drafts, translating, or publishing content — that is covered by the separate authoring skill at `/skills/content-authoring/v1/SKILL.md` and Harborly MCP tools. The Content Hub API described here is read-only.

## Prerequisites

Before writing code, collect from the user:

1. **`publicSlug`** — the product's public identifier, set by the user in the Harborly settings page. Ask for it if it was not provided; do not guess it.
2. **Enabled toggles** in the same settings page:
   - **Site content API** — gates articles and announcements. If it is off, article and announcement endpoints return `404`.
   - **Public changelog** — gates the changelog endpoints. If it is off, changelog endpoints return `404`.
   - Legal documents need no toggle: published legal pages are readable as soon as the product has a `publicSlug`.
3. **Content languages** — which locales are enabled, and which one is the default. Both are on the Harborly settings page. Ask the user; do not infer them from the browser, from `Accept-Language`, or by calling a Harborly management API (this integration stays anonymous). The catalog the public API accepts is fixed: `zh-CN`, `zh-TW`, `en`, `ja`, `ko`, `de`, `fr`, `es`, `pt-BR`, `it`, `ru`. Matching is case-insensitive; responses use these canonical tags. There are no aliases (`zh` is not `zh-CN`, `en-US` is not `en`).
4. **API origin** — default `https://harborly.dev`. If the user runs a different deployment, use their origin. Do not send requests to any other Harborly host you discover in configuration; this skill targets the public content origin only.

If a request returns `404` during development, check the toggle, the slug, and — on a detail URL — whether that locale is enabled and has a published translation. For a legal URL, check whether that document is published in the resolved locale; no toggle applies. A `400` means the `locale` tag or the article `cursor` is invalid; fix the request. Do not treat `400` as empty content.

## Identity and privacy boundary

- The API is **anonymous and read-only**. It serves only published snapshots — drafts, unpublished and deleted content never appear in responses.
- **No Harborly token is needed, and none may be sent.** Do not ask the user for a Harborly access token for this integration, and never attach an `Authorization` header to these requests.
- **No CORS.** The API is not reachable from browser JavaScript. Fetch it **server-side only** — React Server Components, ISR, server actions, or a server-side route handler that your client code calls. Never call these URLs from a `"use client"` component or from browser code.
- Responses are public by design: anything returned may end up in caches and search engines. That is expected for published content.

## HTTP contract

Base URL for all endpoints:

```
{origin}/api/workspace/content/sites/{publicSlug}
```

Conventions for every endpoint:

- JSON with camelCase keys.
- IDs are UUID strings.
- Timestamps are ISO 8601 strings with timezone, normalized to UTC by the server.
- Optional `locale` on every endpoint — articles, changelog, legal, and announcements. See [Locale](#locale).

### Locale

| Name | Type | Default | Notes |
| --- | --- | --- | --- |
| `locale` | string? | product default language | Canonical catalog tag. Case-insensitive. |

- **Omit `locale`** to read the product's current default language. A single-language site should omit it on every request.
- **Not in the catalog** (malformed, blank, an alias, or any other BCP 47 tag) → `400`. Do not retry.
- **In the catalog, but not enabled** for this product → list endpoints return `200` with an empty collection; detail endpoints return `404`.
- **Articles, changelog, and legal do not fall back.** No published copy for the resolved locale → the row is absent from the list, and the detail request is `404`.
- **Announcements resolve per item.** `Hidden` for the resolved locale is dropped and does not fall back. A `Translated` entry supplies that locale's `message` and `ctaText`. If the locale has no entry, the item uses the current default-language copy.
- **`locale` on the response is the language of the copy returned**, in canonical form. For an announcement that fell back, that is the default language, not the requested tag. Articles, changelog, and legal never fall back, so a returned document's `locale` is the resolved language.
- **Article `cursor` values are bound to the resolved locale**, the product, and `tag`. Send a cursor back only with that same locale and tag. Another locale, or an unknown cursor version, is `400`. Cursors issued before locale support are accepted only when the resolved locale is `zh-CN`. Changing language starts at the first page (no `cursor`).
- **Changelog pages use `skipCount`.** That offset is a different result set per locale. When the language changes, start again at `skipCount=0`.
- **Do not negotiate with `Accept-Language`.** Language comes only from this query or from the default. Cache keys must include `locale` when it is set; see [Caching and consistency](#caching-and-consistency).
- Asset URLs do not take `locale`.

### `GET /articles` — cursor pagination

Query parameters:

| Name | Type | Default | Notes |
| --- | --- | --- | --- |
| `limit` | int | `20` | Range 1–100. |
| `cursor` | string? | — | Opaque cursor from a previous response's `nextCursor`. Pass through unchanged; never decode or modify it. Bound to the resolved locale — see [Locale](#locale). |
| `tag` | string? | — | Filter by tag. |
| `locale` | string? | product default | See [Locale](#locale). |

Response `{ items: HarborlyArticleSummary[], nextCursor: string | null }`. Each summary includes `locale`. Page forward by passing `nextCursor` as the next request's `cursor` **with the same `locale`**; when it comes back `null`, there are no more pages. An empty site, or a locale with no published articles, returns `200` with `items: []`.

### `GET /articles/{slug}` — one article

Optional query: `locale`. See [Locale](#locale).

Response: `HarborlyArticle` (summary plus `bodyMarkdown`, `seoTitle`, `seoDescription`, `assets`, `alternates`). Notes:

- `bodyMarkdown` is Markdown; `asset:` references in it have already been rewritten to absolute asset URLs — render it as-is, no rewriting needed.
- `seoTitle` / `seoDescription` may be empty strings; fall back to `title` / `summary`.
- `canonicalUrl` may be an empty string (= not set by the author); fall back to your own site's article URL.
- `alternates` is `{ locale, slug }[]`. It includes this document. Only same-group variants that are published, not deleted, and in an enabled locale are listed; drafts are not. Build hreflang and the language switcher only from this array. The `slug` is the content slug — the public page URL is your own route, not the API path.

### Assets (`cover` and `assets`)

Asset URLs are absolute URLs on the Harborly origin. Raster images respond with a `302` redirect to a short-lived signed URL; SVGs are proxied directly. Asset responses are `Cache-Control: no-store` and visibility is re-checked on every request, so assets stop serving once an article is withdrawn.

Render images with plain `<img>` tags. Do not route them through image optimizers that fetch-and-cache server-side (e.g. `next/image`): the signed redirect URLs expire, and the optimizer's cache would outlive the visibility check.

### `GET /changelog` — offset pagination

Query parameters: `skipCount` (int, default `0`), `maxResultCount` (int, default `20`, range 1–100), and optional `locale` and `releaseTarget`. See [Locale](#locale).

Response `{ items: HarborlyChangelogSummary[], hasMore: boolean }`. Each summary includes `locale`. Note this is a **different pagination scheme** from articles: offset-based with `hasMore`, not cursor-based. Entries are grouped by release target first — a product can serve several parallel changelogs (e.g. one per plugin) — and ordered newest version first within each target. `releaseTarget` filters to one target's stable code (e.g. `plugin`); omit it to get all targets together. When `locale` changes, start again at `skipCount=0`.

### `GET /changelog/{documentId}` — one entry

Optional query: `locale`. See [Locale](#locale).

Response: `HarborlyChangelog` (summary plus `bodyMarkdown` and `alternates`). The path id is that language's own document id — the `id` on a list item, or `documentId` on an alternate. Notes:

- `alternates` is `{ locale, documentId }[]`. It includes this document, under the same publication rules as article `alternates`.
- Switch language with the alternate's `documentId`. Do not keep this path id and only change `locale`.
- The public page URL is your own route. The API document id is not that URL.
- Entries from deprecated changelog groups never appear — in the list, in details, or in `alternates`.

### `GET /announcements?placement=topbar` — effective announcements

Optional query: `locale`. See [Locale](#locale).

Response: a **bare JSON array** of `HarborlyAnnouncement` (not wrapped in an object). `placement` is `"topbar"` today. Each item's `locale` is the language of the copy returned; the item does not carry other languages.

Semantics, already applied server-side:

- Only the current publication of each announcement; deleted and unpublished ones are excluded.
- Only currently **effective** ones: `(startsAt === null || startsAt <= now) && (endsAt === null || now < endsAt)`.
- Sorted `priority` descending, then `publishedAt` descending, then `id` descending. **Show only the first item.**
- `dismissKey` is `"{id}:{publishedRevision}"`. It changes whenever an announcement is re-published after being taken down — use it in dismissal storage keys so a banner comes back for users who dismissed the previous incarnation.
- `ctaText` / `ctaUrl` are both set or both empty/null. `message` is plain text (1–500 chars).
- No announcements in effect → `200` with `[]`. Feature disabled or unknown slug → `404`. Render nothing in either case.

### `GET /legal` — published legal pages

Optional query: `locale`. See [Locale](#locale).

Response: `{ items: HarborlyLegalLink[] }` — the published legal documents in that language; each item carries its `locale`. No published pages → `200` with `items: []`.

### `GET /legal/privacy` — the privacy policy

Optional query: `locale`. See [Locale](#locale).

Response: `HarborlyLegal` — the currently published privacy policy in that language.

### `GET /legal/terms` — the terms of service

Optional query: `locale`. See [Locale](#locale).

Response: `HarborlyLegal` — the currently published terms of service in that language.

### `GET /legal/{slug}` — one legal document

`slug` is `"privacy"`, `"terms"`, or a custom document's slug: lowercase letters and digits separated by hyphens, at most 100 characters. `privacy` and `terms` here are equivalent to the two endpoints above. Optional query: `locale` — see [Locale](#locale). Response: `HarborlyLegal`.

Legal semantics:

- Same base URL as every other endpoint: `{origin}/api/workspace/content/sites/{publicSlug}`.
- Unpublished, withdrawn, or deleted document, unknown slug, unknown `publicSlug`, or no published translation for the resolved locale → `404`. Detail endpoints have no empty-state `200`.
- **Not gated by the toggles.** Legal endpoints ignore both **Site content API** and **Public changelog** — a published legal document is readable as soon as the product has a `publicSlug`.
- Legal takes `locale` like every other endpoint: omit it for the product default language; a locale with no published translation of that document is `404` (no fallback).
- The response carries its `locale` and `alternates: [{ locale, slug }]` — this document plus other published variants in enabled locales of the same legal group. Build legal hreflang and the language switcher only from this array; the `slug` is the content slug, not a page URL.
- The response is the version confirmed at publication. Later draft edits do not change what is served until the document is published again — per language: each language has its own title, body, effective date, and publication.
- Anonymous, no CORS, server-side only — same rules as every other endpoint.

### TypeScript types

```ts
/** AssetTheme enum, serialized as a number: 1 = neutral, 2 = light, 3 = dark. */
export type HarborlyAssetTheme = 1 | 2 | 3;

export interface HarborlyAsset {
  /** asset: reference as written in the article body; empty for the cover. */
  ref: string;
  /** Absolute Harborly URL. Raster images 302-redirect to a short-lived signed URL. */
  url: string;
  mediaType: string;
  width: number | null;
  height: number | null;
  theme: HarborlyAssetTheme;
  alt: string;
}

export interface HarborlyArticleSummary {
  id: string;
  slug: string;
  /** Canonical language of this copy, e.g. "en" or "zh-CN". */
  locale: string;
  title: string;
  summary: string;
  tags: string[];
  cover: HarborlyAsset | null;
  /** Empty string when the author did not set a canonical URL. */
  canonicalUrl: string;
  contentRevision: number;
  /** ISO 8601, UTC. */
  firstPublishedAt: string;
  /** ISO 8601, UTC. */
  updatedAt: string;
}

/** One published article variant. `slug` is the content slug, not a page URL. */
export interface HarborlyArticleAlternate {
  locale: string;
  slug: string;
}

export interface HarborlyArticle extends HarborlyArticleSummary {
  bodyMarkdown: string;
  seoTitle: string;
  seoDescription: string;
  /** bodyMarkdown already references these URLs; no rewriting needed. */
  assets: HarborlyAsset[];
  /** This document plus other published, enabled variants in the group. */
  alternates: HarborlyArticleAlternate[];
}

export interface HarborlyArticlePage {
  items: HarborlyArticleSummary[];
  /** Opaque cursor. null = no more pages. */
  nextCursor: string | null;
}

export interface HarborlyChangelogSummary {
  id: string;
  /** Canonical language of this copy. */
  locale: string;
  title: string;
  releaseVersion: string | null;
  /** Release target (parallel version line) this entry belongs to. */
  releaseTargetId: string;
  releaseTargetCode: string;
  releaseTargetName: string;
  summary: string | null;
  /** Date only, YYYY-MM-DD. */
  releaseDate: string;
  contentRevision: number;
  firstPublishedAt: string;
  updatedAt: string;
}

/** One published changelog variant. `documentId` is that language's document id. */
export interface HarborlyChangelogAlternate {
  locale: string;
  documentId: string;
}

export interface HarborlyChangelog extends HarborlyChangelogSummary {
  bodyMarkdown: string;
  /** This document plus other published, enabled variants in the group. */
  alternates: HarborlyChangelogAlternate[];
}

export interface HarborlyChangelogPage {
  items: HarborlyChangelogSummary[];
  hasMore: boolean;
}

/** Category enum, serialized as a number: 1 = promotion, 2 = notice, 3 = maintenance. */
export type HarborlyAnnouncementCategory = 1 | 2 | 3;

export interface HarborlyAnnouncement {
  id: string;
  /**
   * Language of `message` / `ctaText`. The default language when this item
   * had no entry for the requested locale and the default copy was returned.
   */
  locale: string;
  /** Plain text, 1–500 characters. Render as text, never as HTML. */
  message: string;
  category: HarborlyAnnouncementCategory;
  ctaText: string | null;
  ctaUrl: string | null;
  /** Only "topbar" exists today. */
  placement: string;
  /** Higher first. The API already applies the ordering. */
  priority: number;
  startsAt: string | null;
  endsAt: string | null;
  dismissible: boolean;
  publishedRevision: number;
  publishedAt: string;
  /** "{id}:{publishedRevision}". Always include this in dismissal storage keys. */
  dismissKey: string;
}

/** DocumentType enum, serialized as a number: 9 = privacy policy, 10 = terms of service, 11 = custom legal document. */
export type HarborlyLegalType = 9 | 10 | 11;

export interface HarborlyLegalLink {
  /** Canonical language of this copy. */
  locale: string;
  type: HarborlyLegalType;
  /** "privacy", "terms", or the custom slug. */
  slug: string;
  title: string;
  /** Date only, YYYY-MM-DD. */
  effectiveDate: string;
  /** ISO 8601, UTC. Time of the current publication. */
  updatedAt: string;
}

/** One published legal variant. `slug` is the content slug, not a page URL. */
export interface HarborlyLegalAlternate {
  locale: string;
  slug: string;
}

export interface HarborlyLegal extends HarborlyLegalLink {
  id: string;
  bodyMarkdown: string;
  contentRevision: number;
  /** This document plus other published, enabled variants in the group. */
  alternates: HarborlyLegalAlternate[];
}
```

### Status codes and error handling

| Status | Meaning | How to handle |
| --- | --- | --- |
| `200` | Success — possibly with empty `items` or `[]`. Also a list request for a catalog locale the product has not enabled. | Render normally; empty is not an error. |
| `304` | ETag match (raw HTTP clients only) | Use your cached copy. |
| `400` | `InvalidContentLocale`: `locale` is not a catalog tag. `InvalidInput`: an article `cursor` does not belong to the resolved locale, including an unknown cursor version | Do not retry. Fix the query. Not an empty-content result. |
| `404` | `ResourceNotFound`: unknown `publicSlug`, feature toggle off, entry missing or withdrawn, no article/changelog/legal translation for the resolved locale, an unpublished, unknown-slug, or untranslated-in-that-locale legal document, or a detail request for a catalog locale the product has not enabled | Treat as "no content": empty list, `notFound()` page, or no banner. |
| `429` | Rate limited | Retry after honoring `Retry-After` if present. |
| `5xx` / network failure | Harborly temporarily unavailable | Retry with backoff; keep serving your last good cached copy. |

Retry advice for `5xx`, `429`, and network failures: retry up to 3 times with exponential backoff (e.g. 500 ms, 1 s). Never retry other `4xx` responses. `404` is a valid answer, not a failure. Error responses are served with `Cache-Control: no-store`, so `404` states are not cached.

## Caching and consistency

### What Harborly sends

- **Articles and changelog**: `Cache-Control: public, max-age=60, stale-while-revalidate=300`, plus a strong `ETag` per response. Send `If-None-Match` with that ETag to get `304` when unchanged (relevant for raw HTTP integrations; framework caches handle this themselves).
- **Legal pages**: same headers as articles and changelog — `Cache-Control: public, max-age=60, stale-while-revalidate=300` plus a strong `ETag`; `If-None-Match`/`304` supported.
- **Announcements**: `Cache-Control: public, max-age=N` where `N = min(30, seconds until the next scheduled start/end boundary of a published announcement, at least 1)` — so a scheduled banner goes live within roughly `max-age`. There is deliberately **no** `stale-while-revalidate`, so stale announcements are not served past their TTL by Harborly-side caches. `ETag`/`304` supported.
- Error responses: `Cache-Control: no-store`.

### Locale and cache keys

`Cache-Control` and `ETag` are unchanged and describe a single response URL. Two locales are two URLs.

- When a page is localized, the locale is part of the site URL and of the Content Hub request. ISR, the `fetch` cache, and any CDN cache key must include it. Next.js caches `fetch` by URL, so `?locale=` is part of that key. A route such as `/[locale]/blog/...` does the same for the HTML.
- Do not select a language with `Accept-Language`, and do not `Vary` the page on it. Do not send that header to the Content Hub API.
- A request that omits `locale` is one cache entry: "the current default". If the product's default language later changes, copies already cached can remain for Harborly's `max-age` (and `stale-while-revalidate` on articles and changelog) plus the site's own TTL.

### Consistency window

Taking content down does not invalidate caches that already hold it. After unpublishing or deleting in Harborly, old copies can still be served:

- by Harborly-side HTTP caches for up to `max-age` (60 s; announcements ≤30 s) plus `stale-while-revalidate` (300 s, articles/changelog/legal pages);
- by **your site's own cache** (ISR/CDN/page cache) for its own TTL on top of that.

Announcement changes therefore propagate in ≈ API `max-age` (≤30 s) **+ your site's cache TTL**. Recommendations:

- **Announcements**: short revalidate (`30` s) or fully dynamic reads.
- **Articles / changelog**: ISR with `revalidate` between `60` and `300` s is fine.

If a stricter take-down SLA matters to the user, prefer dynamic (no-cache) reads for that content and say so explicitly. If waiting out this window is too slow, an optional webhook receiver invalidates your cache the moment Harborly publishes — see [Webhook receiver (optional, faster cache refresh)](#webhook-receiver-optional-faster-cache-refresh). Nothing changes when no webhook is configured.

If a background revalidation request fails, frameworks typically keep serving the last good page and retry — with ISR, a Harborly outage degrades to slightly stale content rather than errors. A page that has never rendered before (e.g. at build time) will surface the error instead; wrap build-time-only calls in `try`/`catch` when you want the build to survive an outage.

## Next.js App Router reference implementation

Install the Markdown renderer once:

```bash
pnpm add react-markdown remark-gfm
```

Environment variables (`.env.local`):

```bash
HARBORLY_PUBLIC_SLUG=your-public-slug            # ask the user for this
HARBORLY_API_ORIGIN=https://harborly.dev         # optional; this is the default
NEXT_PUBLIC_SITE_URL=https://your-site.example   # used for metadata and sitemap
HARBORLY_WEBHOOK_SECRET=whsec_...                # only for the webhook receiver; see that section
```

### `lib/harborly.ts`

```ts
// lib/harborly.ts
// Server-side client for Harborly's anonymous Content Hub API.
// Call these functions only from server code: the API has no CORS and must
// stay on the server. Never attach an Authorization header — the API is
// anonymous by design and tokens must not be sent.
//
// `locale` is optional. Omit it (single-language sites) and Harborly uses the
// product's default content language. Never send Accept-Language.

const API_ORIGIN = process.env.HARBORLY_API_ORIGIN ?? "https://harborly.dev";

/** Your product's public identifier, set in the Harborly settings page. */
export const PUBLIC_SLUG = process.env.HARBORLY_PUBLIC_SLUG ?? "";

const BASE_URL = `${API_ORIGIN}/api/workspace/content/sites/${encodeURIComponent(PUBLIC_SLUG)}`;

// --- Types: see the "TypeScript types" section above; copy them here. ---

const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));

async function fetchWithRetry(url: string, init: RequestInit): Promise<Response> {
  let lastError: unknown = new Error("Harborly content API request failed");
  for (let attempt = 0; attempt < 3; attempt++) {
    try {
      const response = await fetch(url, init);
      // 404 is a valid answer (disabled, missing, or no translation).
      // 400 is a bad locale or cursor — return it so the caller fails the request.
      // Other 4xx are client errors — do not retry them.
      if (response.status < 500 && response.status !== 429) return response;
      lastError = new Error(`Harborly content API returned ${response.status}`);
    } catch (error) {
      lastError = error; // network failure — retry
    }
    if (attempt < 2) await sleep(500 * 2 ** attempt);
  }
  throw lastError;
}

/**
 * GET a JSON document. Returns null on 404 (unknown publicSlug, disabled
 * feature, withdrawn, missing, or no translation). Throws immediately on 400.
 * Throws after retries on 5xx and network failures; with ISR the last good
 * page keeps serving meanwhile.
 */
/**
 * Fetch-cache tags, one per content type. Deliberately without locale: a tag
 * match refreshes every language at once, which is what a publish event wants.
 * The webhook receiver (see the Webhook section) revalidates these by
 * `resource.type`. Legal has no webhook events — the tag exists only so the
 * naming stays uniform.
 */
export const TAGS = {
  articles: "harborly:articles",
  changelog: "harborly:changelog",
  announcements: "harborly:announcements",
  legal: "harborly:legal",
} as const;

async function getJson<T>(path: string, revalidate: number, tags: string[]): Promise<T | null> {
  const response = await fetchWithRetry(`${BASE_URL}${path}`, {
    next: { revalidate, tags },
    headers: { accept: "application/json" },
  });
  if (response.status === 404) return null;
  if (!response.ok) throw new Error(`Harborly content API ${path} failed: ${response.status}`);
  return (await response.json()) as T;
}

/**
 * Articles use cursor pagination: pass `nextCursor` from the previous page
 * until it comes back null. `limit` is 1–100, default 20.
 * The cursor is bound to `locale` (and `tag`). Do not reuse it across languages.
 */
export function getArticles(limit = 20, cursor?: string, tag?: string, locale?: string) {
  const query = new URLSearchParams({ limit: String(limit) });
  if (cursor) query.set("cursor", cursor);
  if (tag) query.set("tag", tag);
  if (locale) query.set("locale", locale);
  return getJson<HarborlyArticlePage>(`/articles?${query}`, 120, [TAGS.articles]);
}

/**
 * One published article by slug. null = unknown slug, withdrawn, disabled,
 * or no published translation for `locale`. Omit `locale` for the default language.
 */
export function getArticle(slug: string, locale?: string) {
  const suffix = locale ? `?locale=${encodeURIComponent(locale)}` : "";
  return getJson<HarborlyArticle>(`/articles/${encodeURIComponent(slug)}${suffix}`, 120, [TAGS.articles]);
}

/**
 * Changelog uses offset pagination: `skipCount` (default 0) and
 * `maxResultCount` (1–100, default 20). Keep paging while `hasMore` is true.
 * When `locale` changes, start again at `skipCount` 0.
 * `releaseTarget` filters to one release target's stable code (see
 * `releaseTargetCode` on a summary); omit it for all targets.
 */
export function getChangelog(
  skipCount = 0,
  maxResultCount = 20,
  locale?: string,
  releaseTarget?: string,
) {
  const query = new URLSearchParams({
    skipCount: String(skipCount),
    maxResultCount: String(maxResultCount),
  });
  if (locale) query.set("locale", locale);
  if (releaseTarget) query.set("releaseTarget", releaseTarget);
  return getJson<HarborlyChangelogPage>(`/changelog?${query}`, 120, [TAGS.changelog]);
}

/**
 * One changelog entry by that language's document id (UUID from a list item
 * or from `alternates[].documentId`). Omit `locale` for the default language.
 * To show another language, pass that alternate's `documentId`.
 */
export function getChangelogEntry(documentId: string, locale?: string) {
  const suffix = locale ? `?locale=${encodeURIComponent(locale)}` : "";
  return getJson<HarborlyChangelog>(`/changelog/${encodeURIComponent(documentId)}${suffix}`, 120, [TAGS.changelog]);
}

/**
 * Currently effective announcements for a placement, best first — show only
 * the first. 404 (feature disabled) and "none in effect" (200 []) both become
 * an empty array; render nothing in either case. 30s revalidate so taking a
 * banner down reaches the site quickly.
 */
export async function getAnnouncements(
  placement = "topbar",
  locale?: string,
): Promise<HarborlyAnnouncement[]> {
  const query = new URLSearchParams({ placement });
  if (locale) query.set("locale", locale);
  const result = await getJson<HarborlyAnnouncement[]>(`/announcements?${query}`, 30, [TAGS.announcements]);
  return result ?? [];
}

/**
 * Published legal pages for a locale (default language when omitted). Not
 * gated by the site content or changelog toggles. Empty items when nothing
 * legal is published in that language; null on unknown publicSlug.
 */
export function getLegalList(locale?: string) {
  const suffix = locale ? `?locale=${encodeURIComponent(locale)}` : "";
  return getJson<{ items: HarborlyLegalLink[] }>(`/legal${suffix}`, 300, [TAGS.legal]);
}

/**
 * One published legal page by slug: "privacy", "terms", or a custom slug.
 * null = not published, withdrawn, unknown slug, or no published
 * translation for `locale`.
 */
export function getLegal(slug: string, locale?: string) {
  const suffix = locale ? `?locale=${encodeURIComponent(locale)}` : "";
  return getJson<HarborlyLegal>(`/legal/${encodeURIComponent(slug)}${suffix}`, 300, [TAGS.legal]);
}
```

### `app/blog/page.tsx`

```tsx
// app/blog/page.tsx
import Link from "next/link";
import { notFound } from "next/navigation";
import { getArticles } from "@/lib/harborly";

export const metadata = {
  title: "Blog",
  description: "Articles about our product.",
};

// Reading searchParams makes this route render on demand; the fetch cache in
// lib/harborly.ts (revalidate: 120) is what keeps responses fast.
export default async function BlogPage({
  searchParams,
}: {
  searchParams: Promise<{ cursor?: string }>;
}) {
  const { cursor } = await searchParams;
  const page = await getArticles(20, cursor);
  if (!page) notFound(); // delivery disabled or unknown publicSlug

  return (
    <main>
      <h1>Blog</h1>
      <ul>
        {page.items.map((article) => (
          <li key={article.id}>
            {article.cover && (
              // Plain <img> on purpose: Harborly asset URLs redirect to
              // short-lived signed URLs that image optimizers must not cache.
              <img
                src={article.cover.url}
                alt={article.cover.alt}
                width={article.cover.width ?? undefined}
                height={article.cover.height ?? undefined}
                loading="lazy"
              />
            )}
            <Link href={`/blog/${article.slug}`}>{article.title}</Link>
            <p>
              <time dateTime={article.firstPublishedAt}>
                {article.firstPublishedAt.slice(0, 10)}
              </time>{" "}
              {article.summary}
            </p>
          </li>
        ))}
      </ul>
      {page.nextCursor && (
        <Link href={`/blog?cursor=${encodeURIComponent(page.nextCursor)}`}>
          Older articles
        </Link>
      )}
    </main>
  );
}
```

### `app/blog/[slug]/page.tsx`

```tsx
// app/blog/[slug]/page.tsx
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { getArticle, getArticles } from "@/lib/harborly";

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000";

type Props = { params: Promise<{ slug: string }> };

// Optional: pre-render the 100 newest articles at build time. Slugs published
// later fall back to on-demand rendering (dynamicParams defaults to true).
export async function generateStaticParams() {
  try {
    const page = await getArticles(100);
    return (page?.items ?? []).map((article) => ({ slug: article.slug }));
  } catch {
    return []; // API unreachable at build time — render on demand instead
  }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const article = await getArticle(slug);
  if (!article) return {};

  const title = article.seoTitle || article.title;
  const description = article.seoDescription || article.summary;
  // The author's canonical URL wins; otherwise fall back to this site's URL.
  const canonical = article.canonicalUrl || `${SITE_URL}/blog/${article.slug}`;

  return {
    title,
    description,
    alternates: { canonical },
    openGraph: {
      title,
      description,
      url: canonical,
      type: "article",
      images: article.cover ? [{ url: article.cover.url }] : undefined,
    },
  };
}

export default async function ArticlePage({ params }: Props) {
  const { slug } = await params;
  const article = await getArticle(slug);
  if (!article) notFound();

  return (
    <article>
      <h1>{article.title}</h1>
      <p>
        <time dateTime={article.firstPublishedAt}>
          {article.firstPublishedAt.slice(0, 10)}
        </time>
      </p>
      {article.cover && (
        // Plain <img>: asset URLs redirect to short-lived signed URLs; see
        // lib/harborly.ts. The next/no-img-element lint warning is expected.
        <img src={article.cover.url} alt={article.cover.alt} />
      )}
      {/* react-markdown renders Markdown as React nodes. Do not add
          rehype-raw or dangerouslySetInnerHTML — raw HTML stays disabled. */}
      <ReactMarkdown remarkPlugins={[remarkGfm]}>{article.bodyMarkdown}</ReactMarkdown>
      <p>
        <Link href="/blog">← All articles</Link>
      </p>
    </article>
  );
}
```

Markdown rendering: `react-markdown` + `remark-gfm` only. Do **not** enable raw HTML (`rehype-raw`, `dangerouslySetInnerHTML`) — article bodies do not need it and rendering HTML from a remote source is unnecessary risk. Map `article.assets` to `<img>`/`<video>` elements if you want richer handling; the URLs in `bodyMarkdown` already work as plain Markdown images.

### `app/changelog/page.tsx`

```tsx
// app/changelog/page.tsx
import Link from "next/link";
import { notFound } from "next/navigation";
import { getChangelog } from "@/lib/harborly";

export const metadata = {
  title: "Changelog",
  description: "What changed, release by release.",
};

const PAGE_SIZE = 20;

// Offset pagination: the page number maps to skipCount/maxResultCount.
// Note: entries published between two page loads can shift offsets slightly;
// acceptable for a changelog.
export default async function ChangelogPage({
  searchParams,
}: {
  searchParams: Promise<{ page?: string }>;
}) {
  const { page } = await searchParams;
  const pageNumber = Math.max(1, Number.parseInt(page ?? "1", 10) || 1);
  const list = await getChangelog((pageNumber - 1) * PAGE_SIZE, PAGE_SIZE);
  if (!list) notFound(); // public changelog disabled or unknown publicSlug

  return (
    <main>
      <h1>Changelog</h1>
      {list.items.map((entry) => (
        <section key={entry.id}>
          <h2>{entry.title}</h2>
          <p>
            {entry.releaseVersion && <span>{entry.releaseVersion} — </span>}
            <time dateTime={entry.releaseDate}>{entry.releaseDate}</time>
          </p>
          {entry.summary && <p>{entry.summary}</p>}
        </section>
      ))}
      <nav>
        {pageNumber > 1 && <Link href={`/changelog?page=${pageNumber - 1}`}>Newer</Link>}
        {list.hasMore && <Link href={`/changelog?page=${pageNumber + 1}`}>Older</Link>}
      </nav>
    </main>
  );
}
```

If you want full entry bodies on their own pages, add `app/changelog/[documentId]/page.tsx` following the same pattern as the article detail page, using `getChangelogEntry(documentId)` and `HarborlyChangelog.bodyMarkdown`.

### `app/legal/[slug]/page.tsx`

```tsx
// app/legal/[slug]/page.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { getLegal } from "@/lib/harborly";

type Props = { params: Promise<{ slug: string }> };

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const legal = await getLegal(slug);
  return legal ? { title: legal.title } : {};
}

export default async function LegalPage({ params }: Props) {
  const { slug } = await params;
  const legal = await getLegal(slug);
  if (!legal) notFound(); // not published, withdrawn, or unknown slug

  return (
    <main>
      <h1>{legal.title}</h1>
      <p>
        Effective{" "}
        <time dateTime={legal.effectiveDate}>{legal.effectiveDate}</time>
      </p>
      {/* Same Markdown rules as articles: GFM, no raw HTML. */}
      <ReactMarkdown remarkPlugins={[remarkGfm]}>{legal.bodyMarkdown}</ReactMarkdown>
    </main>
  );
}
```

Notes:

- **Footer links** come from `getLegalList()`: render one link per item (`/legal/${page.slug}` → `page.title`). When nothing legal is published — empty `items`, or the call fails — render **no** legal links.
- If the site already has `/privacy` and `/terms` routes it wants to keep, keep them: call `getLegal("privacy")` / `getLegal("terms")` inside those routes and render the returned `HarborlyLegal` the same way. No redirect, no new route needed.

### `app/sitemap.ts`

```ts
// app/sitemap.ts
import type { MetadataRoute } from "next";
import { getArticles, getChangelog, getLegalList } from "@/lib/harborly";

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000";

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const entries: MetadataRoute.Sitemap = [
    { url: `${SITE_URL}/blog` },
    { url: `${SITE_URL}/changelog` },
  ];

  // .catch(() => null): a Harborly outage must not fail sitemap generation.
  // This covers the first page only (100 articles / 100 changelog entries);
  // for larger sets, page through the cursors or generate a sitemap index.
  const [articles, changelog, legal] = await Promise.all([
    getArticles(100).catch(() => null),
    getChangelog(0, 100).catch(() => null),
    getLegalList().catch(() => null),
  ]);

  for (const article of articles?.items ?? []) {
    entries.push({
      url: `${SITE_URL}/blog/${article.slug}`,
      lastModified: new Date(article.updatedAt),
    });
  }
  // Only list per-entry changelog URLs if you added app/changelog/[documentId]/page.tsx;
  // otherwise delete this loop so the sitemap never points at 404 pages.
  for (const entry of changelog?.items ?? []) {
    entries.push({
      url: `${SITE_URL}/changelog/${entry.id}`,
      lastModified: new Date(entry.updatedAt),
    });
  }

  // Published legal pages: privacy, terms, and any custom documents. Items
  // exist only while published, so the list never points at 404 pages.
  for (const page of legal?.items ?? []) {
    entries.push({
      url: `${SITE_URL}/legal/${page.slug}`,
      lastModified: new Date(page.updatedAt),
    });
  }

  return entries;
}
```

### `components/announcement-bar.tsx` (server) and `components/announcement-bar-view.tsx` (client)

```tsx
// components/announcement-bar.tsx — server component, fetches the data.
import type { HarborlyAnnouncement } from "@/lib/harborly";
import { PUBLIC_SLUG, getAnnouncements } from "@/lib/harborly";
import { AnnouncementBarView } from "@/components/announcement-bar-view";

/**
 * Renders nothing when there is no effective announcement — no placeholder
 * ends up in the HTML. Data refreshes with the fetch's 30s revalidate, so
 * publishing or removing a banner reaches the site within about half a
 * minute plus any page cache.
 *
 * Pass the route locale on a localized site. Omit it for the default language.
 * `announcement.locale` can differ from the requested locale when the item has
 * no entry for it and the default-language copy is served. A Hidden translation
 * is simply absent.
 */
export async function AnnouncementBar({ locale }: { locale?: string }) {
  let announcements: HarborlyAnnouncement[];
  try {
    announcements = await getAnnouncements("topbar", locale);
  } catch {
    return null; // API down — never break the whole layout for a banner
  }

  const announcement = announcements[0]; // the API already sorts best-first
  if (!announcement) return null;

  // Key includes the publicSlug (multi-site safety) and the dismissKey, so
  // re-publishing after unpublishing produces a new key and the banner
  // reappears for users who dismissed the previous incarnation.
  const storageKey = `harborly:dismissed:${PUBLIC_SLUG}:${announcement.dismissKey}`;

  return <AnnouncementBarView announcement={announcement} storageKey={storageKey} />;
}
```

```tsx
// components/announcement-bar-view.tsx — client component, owns dismissal.
"use client";

import { useEffect, useState } from "react";
import type { HarborlyAnnouncement } from "@/lib/harborly";

export function AnnouncementBarView({
  announcement,
  storageKey,
}: {
  announcement: HarborlyAnnouncement;
  storageKey: string;
}) {
  const [dismissed, setDismissed] = useState(false);

  useEffect(() => {
    if (!announcement.dismissible) return;
    try {
      setDismissed(window.localStorage.getItem(storageKey) === "1");
    } catch {
      // localStorage unavailable (e.g. privacy mode) — just show the banner.
    }
  }, [announcement.dismissible, storageKey]);

  if (dismissed) return null;

  function dismiss() {
    setDismissed(true);
    try {
      window.localStorage.setItem(storageKey, "1");
    } catch {
      // Ignore write failures; the banner simply reappears on the next load.
    }
  }

  const cta =
    announcement.ctaText && announcement.ctaUrl
      ? { text: announcement.ctaText, url: announcement.ctaUrl }
      : null;

  return (
    <aside
      style={{ display: "flex", alignItems: "center", gap: "0.75rem", padding: "0.5rem 1rem" }}
    >
      {/* Plain text on purpose — never render announcement.message as HTML. */}
      <p style={{ margin: 0 }}>{announcement.message}</p>
      {cta && (
        <a href={cta.url} target="_blank" rel="noopener noreferrer">
          {cta.text}
        </a>
      )}
      {announcement.dismissible && (
        <button type="button" onClick={dismiss} aria-label="Dismiss announcement">
          ×
        </button>
      )}
    </aside>
  );
}
```

Behavior notes:

- The banner shows before hydration and hides after the `useEffect` if previously dismissed — a brief flash for users who dismissed it is the accepted trade-off here. Replace with an inline pre-hydration script only if the user asks.
- `dismissible: false` banners render no close button and skip the storage check.
- Adapt the inline styles to the site's design system; the structure and behavior are what matter.

### Mounting in `app/layout.tsx`

```tsx
// app/layout.tsx (excerpt)
import { AnnouncementBar } from "@/components/announcement-bar";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  // `lang` is the product's default content language.
  return (
    <html lang="en">
      <body>
        <AnnouncementBar />
        {/* your existing header / nav */}
        {children}
      </body>
    </html>
  );
}
```

`AnnouncementBar` is an async server component, so it can be rendered directly from the (server) layout. It renders `null` — literally nothing in the HTML — whenever Harborly returns no effective announcement or is unreachable. Set `<html lang>` to the product's default content language. On a localized site, set it to the route locale (see below).

## Webhook receiver (optional, faster cache refresh)

Everything above works with **no webhook configured**: updates land within the [consistency window](#consistency-window) — Harborly's cache plus your site's TTL. The webhook does not change that contract; it is an accelerator. When Harborly publishes, updates, or takes down content, it POSTs a signed event to an endpoint you register, and your site invalidates the affected cache immediately instead of waiting out the TTL. If the user does not want a webhook, skip this section entirely — no code, no secret, no behavior change.

Configure it in Harborly Web under **Content Hub → Webhook**: register your HTTPS endpoint URL, and Harborly shows the signing secret **once**, at creation (and again only when you explicitly rotate it). Copy it into `HARBORLY_WEBHOOK_SECRET` immediately; it cannot be viewed again afterwards. The page also has a **send test event** action that delivers a `test.ping` event so you can verify the wiring end to end.

### Event contract

Headers on every delivery:

| Header | Meaning |
| --- | --- |
| `Harborly-Event-Id` | UUID of the event. Stable across retries and manual resends — dedupe on it. |
| `Harborly-Event-Type` | `article`, `changelog`, or `announcement`, plus `.published`, `.updated`, or `.unpublished` (e.g. `article.published`); or the probe type `test.ping`. |
| `Harborly-Timestamp` | Unix seconds of this delivery attempt. Recomputed per retry. |
| `Harborly-Signature` | `v1=` followed by the lowercase-hex HMAC-SHA256 signature. |

- Signature: `HMAC-SHA256(key = the full secret string including its `whsec_` prefix (UTF-8), message = "{Harborly-Timestamp}.{rawBody}")`. Verify against the **raw** body bytes — read `await req.text()` first; never re-serialize parsed JSON before verifying.
- Payload: camelCase JSON with `id`, `type`, `occurredAt`, `projectId`, `publicSlug`, and `resource: { type, id, slug, locale, publishedRevision, translationGroupId }`. It carries **no content** — no Markdown, no drafts, only identifiers. `slug` is null for non-articles; `locale` is null for announcements; `publishedRevision` is null on `unpublished`.
- Localized content sends **one event per language document**, each with its `locale`. Announcements send one event per announcement (locale null).
- Only 2xx counts as delivered. 3xx is a failure (Harborly does not follow redirects); timeouts and non-2xx responses are retried with backoff (1m, 5m, 15m, 1h, 2h, 4h, 8h — up to 8 attempts within 24h). Delivery is **at-least-once**, so your receiver must be idempotent on `Harborly-Event-Id`.
- A scheduled announcement starting or ending on its own time window does **not** emit an event — keep the short announcement `revalidate` even with a webhook configured.

### Next.js App Router receiver: `app/api/harborly/webhook/route.ts`

The reference client above already tags every fetch with a content-type tag (`TAGS` in `lib/harborly.ts`), so the receiver only needs to `revalidateTag` the one matching `resource.type` — lists and detail pages across all locales refresh on their next request.

```ts
// app/api/harborly/webhook/route.ts
import { createHmac, timingSafeEqual } from "node:crypto";
import { revalidateTag } from "next/cache";
import { TAGS } from "@/lib/harborly";

// resource.type → the fetch-cache tag from lib/harborly.ts.
const TAG_FOR_TYPE: Record<string, string> = {
  article: TAGS.articles,
  changelog: TAGS.changelog,
  announcement: TAGS.announcements,
};

interface HarborlyWebhookResource {
  type: string;
  id: string;
  slug: string | null;
  locale: string | null;
  publishedRevision: number | null;
  translationGroupId: string | null;
}

interface HarborlyWebhookPayload {
  id: string;
  type: string;
  occurredAt: string;
  projectId: string;
  publicSlug: string;
  resource: HarborlyWebhookResource;
}

const SECRET = process.env.HARBORLY_WEBHOOK_SECRET ?? "";
// Harborly retries for up to 24h and manual resends reuse the event id —
// keep seen ids at least that long.
const SEEN_TTL_MS = 24 * 60 * 60 * 1000;
// Reject replays: the timestamp must be within 5 minutes of now.
const TIMESTAMP_TOLERANCE_SECONDS = 300;

/**
 * In-memory idempotency guard — a placeholder. Fine for a single long-lived
 * server; a restart loses it, and serverless or multi-instance deployments
 * share no memory. For production, replace it with a persistent store
 * (Redis, KV, a database table) keyed by the event id.
 */
const seenEventIds = new Map<string, number>();

function pruneSeen(now: number): void {
  for (const [id, seenAt] of seenEventIds) {
    if (now - seenAt > SEEN_TTL_MS) seenEventIds.delete(id);
  }
}

function respond(status: number): Response {
  return new Response(null, { status });
}

export async function POST(req: Request): Promise<Response> {
  if (!SECRET) return respond(503); // not configured — Harborly will retry

  // 1. Raw body first: the signature covers the exact bytes that were sent.
  const rawBody = await req.text();

  const eventId = req.headers.get("Harborly-Event-Id");
  const timestamp = req.headers.get("Harborly-Timestamp");
  const signature = req.headers.get("Harborly-Signature");
  if (!eventId || !timestamp || !signature) return respond(401);

  // 2. Replay window: unix seconds, within 5 minutes of now.
  const age = Math.floor(Date.now() / 1000) - Number.parseInt(timestamp, 10);
  if (!Number.isFinite(age) || Math.abs(age) > TIMESTAMP_TOLERANCE_SECONDS) {
    return respond(401);
  }

  // 3. Constant-time compare of HMAC-SHA256 over "{timestamp}.{rawBody}".
  const expected = createHmac("sha256", SECRET)
    .update(`${timestamp}.${rawBody}`)
    .digest("hex");
  const received = signature.replace(/^v1=/, "");
  const a = Buffer.from(expected, "hex");
  const b = Buffer.from(received, "hex");
  if (a.length !== b.length || !timingSafeEqual(a, b)) return respond(401);

  // 4. Idempotency: retries and manual resends reuse the event id.
  const now = Date.now();
  pruneSeen(now);
  if (seenEventIds.has(eventId)) return respond(200); // already handled
  seenEventIds.set(eventId, now);

  // 5. Verified — now parse, then act. Keep this fast (Harborly times the
  //    request out after 10 s): no fetching, no rendering, only invalidation.
  let payload: HarborlyWebhookPayload;
  try {
    payload = JSON.parse(rawBody) as HarborlyWebhookPayload;
  } catch {
    return respond(400); // signed but malformed — 4xx marks the delivery failed
  }

  // Probe event from Harborly Web's "send test event": nothing to refresh.
  if (payload.type === "test.ping") return respond(200);

  const tag = TAG_FOR_TYPE[payload.resource?.type ?? ""];
  if (tag) {
    // Log line is here so you can watch invalidations (and duplicates being
    // skipped) during the webhook checks in the acceptance checklist.
    console.log(`harborly webhook: revalidating ${tag} (${eventId})`);
    revalidateTag(tag);
  }
  // Unknown resource types still answer 200 — an unhandled event must not
  // turn into failed deliveries and pointless retries.

  return respond(200);
}
```

Notes:

- Add `HARBORLY_WEBHOOK_SECRET` to `.env.local` and your production environment. Never hardcode it. While it is unset the route answers `503`, so nothing is accepted unsigned and Harborly keeps retrying instead of marking deliveries failed.
- `revalidateTag` covers the `fetch` cache and ISR. If you also keep whole pages in a page-level cache that tags do not reach, call `revalidatePath` for the affected routes alongside it.
- Verify first, parse second, act last. Harborly times out after 10 s and does not read your response body — the handler should do nothing but check and invalidate.
- Other stacks follow the same shape: read the raw body, check the timestamp window, HMAC-verify with a constant-time compare, dedupe on the event id, then invalidate your cache per `resource.type`.

## Localized routes

Single-language sites skip this section and keep calling the client without `locale`. The routes above stay valid.

A multilingual site takes `locale` from its own dynamic segment, for example `app/[locale]/...`, and passes that string through. Use a canonical catalog tag the product has enabled (`en`, `zh-CN`, not `en-US` or `zh`). The API slug and the changelog document id are not page URLs — build every public URL, including hreflang, from the site's route.

Enabled locales come from the user (Prerequisites). Do not advertise the whole catalog.

Legal documents are localized too. The legal endpoints take `locale`, and a legal detail returns `alternates: [{ locale, slug }]` under the same publication rules as articles — build legal hreflang and the switcher from it, and render `404` for a locale with no published legal translation (no fallback). If the site serves legal pages under one shared URL instead, omit `locale` there and give them no hreflang variants.

Index pages have no `alternates` array. Link the enabled locales the user confirmed, each to the first page. Article, changelog, and legal **detail** pages build hreflang and the switcher only from `alternates`, which already includes the current language and excludes missing translations. Reject a route segment that is not one of those enabled locales with `notFound()` before calling the API. Keep the cover image, openGraph, and Markdown rules from the single-language article page.

```tsx
// app/[locale]/blog/page.tsx
import Link from "next/link";
import { notFound } from "next/navigation";
import { getArticles } from "@/lib/harborly";

// Enabled locales confirmed with the user. Not the full catalog.
const LOCALES = ["en", "zh-CN"] as const;

type Props = {
  params: Promise<{ locale: string }>;
  searchParams: Promise<{ cursor?: string }>;
};

export default async function BlogPage({ params, searchParams }: Props) {
  const { locale } = await params;
  const { cursor } = await searchParams;
  // `undefined` is the tag argument. The cursor belongs to this locale only.
  const page = await getArticles(20, cursor, undefined, locale);
  if (!page) notFound();

  return (
    <main>
      <h1>Blog</h1>
      <nav aria-label="Languages">
        {LOCALES.map((code) => (
          // No cursor: the other language starts on its first page.
          <Link key={code} href={`/${code}/blog`} hrefLang={code}>
            {code}
          </Link>
        ))}
      </nav>
      <ul>
        {page.items.map((article) => (
          <li key={article.id}>
            <Link href={`/${locale}/blog/${article.slug}`}>{article.title}</Link>
          </li>
        ))}
      </ul>
      {page.nextCursor && (
        <Link href={`/${locale}/blog?cursor=${encodeURIComponent(page.nextCursor)}`}>
          Older articles
        </Link>
      )}
    </main>
  );
}
```

```tsx
// app/[locale]/blog/[slug]/page.tsx
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { getArticle, getArticles } from "@/lib/harborly";

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000";
const LOCALES = ["en", "zh-CN"] as const;

type Props = { params: Promise<{ locale: string; slug: string }> };

export async function generateStaticParams() {
  try {
    const pages = await Promise.all(
      LOCALES.map((locale) => getArticles(100, undefined, undefined, locale)),
    );
    return pages.flatMap((page, index) =>
      (page?.items ?? []).map((article) => ({ locale: LOCALES[index], slug: article.slug })),
    );
  } catch {
    return [];
  }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { locale, slug } = await params;
  const article = await getArticle(slug, locale);
  if (!article) return {};

  // API alternates ≠ Next.js alternates. Build hreflang only for variants
  // the API returned. The href is this site's route, not the Content Hub URL.
  const languages: Record<string, string> = {};
  for (const alternate of article.alternates) {
    languages[alternate.locale] = `${SITE_URL}/${alternate.locale}/blog/${alternate.slug}`;
  }

  const canonical =
    article.canonicalUrl || `${SITE_URL}/${locale}/blog/${article.slug}`;

  return {
    title: article.seoTitle || article.title,
    description: article.seoDescription || article.summary,
    alternates: { canonical, languages },
  };
}

export default async function ArticlePage({ params }: Props) {
  const { locale, slug } = await params;
  const article = await getArticle(slug, locale);
  if (!article) notFound();

  return (
    <article>
      <nav aria-label="Languages">
        {article.alternates.map((alternate) => (
          <Link
            key={alternate.locale}
            href={`/${alternate.locale}/blog/${alternate.slug}`}
            hrefLang={alternate.locale}
            aria-current={alternate.locale === article.locale ? "page" : undefined}
          >
            {alternate.locale}
          </Link>
        ))}
      </nav>
      <h1>{article.title}</h1>
      <ReactMarkdown remarkPlugins={[remarkGfm]}>{article.bodyMarkdown}</ReactMarkdown>
    </article>
  );
}
```

Changelog detail follows the article page. The path id changes with the language: load `getChangelogEntry(documentId, locale)`, and point every alternate at that variant's own `documentId`.

```ts
// hreflang inside generateMetadata, after:
// const entry = await getChangelogEntry(documentId, locale)
const languages: Record<string, string> = {};
for (const alternate of entry.alternates) {
  languages[alternate.locale] =
    `${SITE_URL}/${alternate.locale}/changelog/${alternate.documentId}`;
}
// return { alternates: { canonical: `${SITE_URL}/${locale}/changelog/${entry.id}`, languages } }
```

```tsx
// switcher — `entry` is that same HarborlyChangelog. The link target is the
// alternate document, not this page's id.
<nav aria-label="Languages">
  {entry.alternates.map((alternate) => (
    <Link
      key={alternate.documentId}
      href={`/${alternate.locale}/changelog/${alternate.documentId}`}
      hrefLang={alternate.locale}
    >
      {alternate.locale}
    </Link>
  ))}
</nav>
```

The changelog index uses `getChangelog(skipCount, pageSize, locale)` and, when linking to another language, links to `/{locale}/changelog` with no `page` query. Sitemap entries for localized routes are the site URLs you actually serve. Fetch each enabled locale and emit only rows that came back:

```ts
for (const locale of LOCALES) {
  const articles = await getArticles(100, undefined, undefined, locale).catch(() => null);
  for (const article of articles?.items ?? []) {
    entries.push({ url: `${SITE_URL}/${locale}/blog/${article.slug}` });
  }
}
```

Do the same for legal: fetch `getLegalList(locale)` per enabled locale and emit `/{locale}/legal/{slug}` for each returned item.

Pass the segment into the banner from the localized layout, and set the document language there:

```tsx
// app/[locale]/layout.tsx
// If a parent layout already renders <html>, set lang on that element instead
// of emitting a second <html>.
import { AnnouncementBar } from "@/components/announcement-bar";

export default async function LocaleLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  return (
    <html lang={locale}>
      <body>
        <AnnouncementBar locale={locale} />
        {children}
      </body>
    </html>
  );
}
```

## Other frameworks

The HTTP contract is framework-agnostic. Whatever the stack, keep these points:

- Fetch **server-side only** (no browser calls — no CORS). PHP/WordPress: `wp_remote_get` + a transient cache; Astro: server fetch with a cache; Nuxt: `routeRules` ISR/swr; SvelteKit: server load with a cache.
- Pass `locale` from your own localized URL. Include it in every cache key. Do not negotiate with `Accept-Language`. Keep an article `cursor` on the locale that issued it.
- Respect the response `Cache-Control`/`ETag` if you implement your own cache; don't cache longer than `max-age`, and never cache error responses (`no-store`).
- Announcements: cache **≤30 s**. Articles/changelog: 60–300 s is fine.
- Legal pages: same cache budget as articles/changelog (60–300 s). They take `locale` like every other endpoint and never fall back; build hreflang only from the detail's `alternates`.
- Treat `404` as "no content", not an error; retry `5xx`/network failures with backoff.
- Render announcement `message` as plain text and Markdown via a non-HTML renderer (`markdown-it` with `html: false`, `marked` without raw HTML, or a `react-markdown`-equivalent).
- Use plain `<img>` for Harborly asset URLs (they redirect to short-lived signed URLs).

## Acceptance checklist

Work through every item and report results honestly. Replace `{publicSlug}` with the user's slug, `$SITE` with the deployed/running site URL.

### API checks (curl)

```bash
BASE=https://harborly.dev/api/workspace/content/sites/{publicSlug}

# Articles: expect 200 with Cache-Control "public, max-age=60, stale-while-revalidate=300" and an ETag header
curl -sS -D - -o /dev/null "$BASE/articles?limit=20"

# Conditional request: repeat with the ETag from above, wrapped in quotes — expect 304
curl -sS -D - -o /dev/null -H 'If-None-Match: "<etag-from-previous-response>"' "$BASE/articles?limit=20"

# Unknown slug: expect 404
curl -sS -o /dev/null -w '%{http_code}\n' https://harborly.dev/api/workspace/content/sites/no-such-site/articles

# Announcements: expect 200 with [] when nothing is in effect,
# or a JSON array of announcement objects when one is live
curl -sS "$BASE/announcements?placement=topbar"

# Changelog: 404 if the public changelog toggle is off; otherwise {"items":[...],"hasMore":...}
curl -sS -o /dev/null -w '%{http_code}\n' "$BASE/changelog?skipCount=0&maxResultCount=20"
curl -sS "$BASE/changelog?skipCount=0&maxResultCount=5"

# Changelog filtered by release target: {code} = one target's stable code,
# e.g. plugin (see releaseTargetCode on any returned summary)
curl -sS "$BASE/changelog?skipCount=0&maxResultCount=5&releaseTarget={code}"

# Legal pages: the list is 200 with {"items":[...]} — [] when nothing is published.
curl -sS "$BASE/legal"

# A published privacy policy is 200; an unpublished or unknown slug is 404.
curl -sS -o /dev/null -w '%{http_code}\n' "$BASE/legal/privacy"
curl -sS -o /dev/null -w '%{http_code}\n' "$BASE/legal/no-such-page"
```

Also confirm the toggles match reality: if an endpoint `404`s, ask the user to enable **Site content API** / **Public changelog** in Harborly settings rather than working around it in code. Legal endpoints do not depend on either toggle — a `404` there means the document is not published.

### Locale checks

`{locale-a}` and `{locale-b}` are two different locales the user confirmed are enabled. `{slug}` and `{documentId}` come from a previous `200`. `{cursor-from-locale-a}` is a `nextCursor` from locale A.

```bash
# Omit locale: default language. Each summary includes "locale".
curl -sS "$BASE/articles?limit=5"

# Enabled locale. Articles with no translation in it are absent — no fallback.
curl -sS "$BASE/articles?limit=5&locale={locale-a}"

# Not a catalog tag: expect 400. "zh" is not "zh-CN".
curl -sS -o /dev/null -w '%{http_code}\n' "$BASE/articles?locale=zh"

# Article detail: "locale" and alternates[{locale,slug}]. 404 if that locale has no published translation.
curl -sS "$BASE/articles/{slug}?locale={locale-a}"

# Changelog detail: alternates[{locale,documentId}]. The other language is that documentId, not this path with another locale.
curl -sS "$BASE/changelog/{documentId}?locale={locale-a}"

# Legal list and detail: items and details carry "locale"; the legal detail
# alternates[{locale,slug}]. A locale with no published legal translation is 404 — no fallback.
curl -sS "$BASE/legal?locale={locale-a}"
curl -sS "$BASE/legal/privacy?locale={locale-a}"

# Article cursor is bound to its resolved locale. Locale B plus locale A's cursor expects 400.
# Locale B with no cursor expects 200.
curl -sS -o /dev/null -w '%{http_code}\n' "$BASE/articles?limit=20&locale={locale-b}&cursor={cursor-from-locale-a}"
curl -sS -o /dev/null -w '%{http_code}\n' "$BASE/articles?limit=20&locale={locale-b}"

# Announcements. item.locale is the copy returned.
# Hidden for this locale: the item is absent. No entry: default-language copy, and locale is the default.
curl -sS "$BASE/announcements?placement=topbar&locale={locale-a}"

# In-catalog locale the product has not enabled: list is 200 with an empty collection; a detail URL is 404.
```

A single-language site that never sends `locale` still receives the default language. That is the backward-compatible path; do not add `locale` there unless the user asked for more than one language.

### Boundary checks

- No Harborly token anywhere in this integration: no `Authorization` header sent to the content API, no Harborly PAT in env files or code.
- All content-API calls are server-side: the URLs never appear in client bundles. `grep -r "content/sites" .next/static/` (or your build output) must return nothing.

### Page checks

- **No announcement published**: viewing the site shows no banner and the HTML contains no placeholder markup for it.
- **Announcement published**: banner appears within ≈30 s + page cache; `message` shown as plain text (view source: no raw HTML injection).
- **Dismiss flow**: click ×, confirm the `localStorage` key `harborly:dismissed:{publicSlug}:{dismissKey}` is set to `"1"`, refresh — the banner stays hidden.
- **Republish flow**: unpublish the announcement in Harborly — the banner disappears within the consistency window; publish it again — it reappears even in the browser where it was dismissed (new `dismissKey`).
- **`dismissible: false`**: banner shows with no close button.
- **Article metadata**: on a detail page, view source — `<title>` equals `seoTitle` (or the article title when empty); meta description equals `seoDescription` (or summary); the canonical link is the author's `canonicalUrl` when set, otherwise the site's real article URL; `og:image` is the cover URL when a cover exists.
- **Markdown**: body renders headings, links, tables (GFM), and images; there is no `rehype-raw`/`dangerouslySetInnerHTML` in the article code (`grep -r "rehype-raw\|dangerouslySetInnerHTML" app/ components/` returns nothing).
- **Sitemap**: `curl -sS $SITE/sitemap.xml` lists `/blog`, `/changelog`, one entry per published article, and one entry per published legal page; per-entry changelog URLs appear only if the changelog detail route exists, and every listed URL returns `200`. Localized sites list their own `/{locale}/...` URLs instead, and only for variants the API returned.
- **hreflang**: on a localized article page, view source — one `hreflang` per `alternates` entry and no others. Each `href` is the site route (`/{locale}/blog/{slug}`), not a `harborly.dev` API URL. The language switcher links the same set. A changelog switcher lands on that alternate's `documentId`.
- **Article pagination**: from page 2, switching language opens the first page of the other language. The previous `cursor` is not in the URL.
- **Announcement locale**: a locale with no entry shows the default-language message, and the payload `locale` is that default. A locale the announcement marks Hidden shows no banner. The page does not vary on `Accept-Language`.
- **Legal pages**: a published document renders at your legal route with its `title`, the `effectiveDate`, and GFM Markdown; an unpublished, unknown, or untranslated-in-that-locale slug is a `404` page. The footer shows one link per published legal page and none when the list is empty. On a localized site, legal hreflang comes only from the detail's `alternates`.
- **Type check**: `pnpm exec tsc --noEmit` (or your framework's equivalent) passes.

### Webhook checks (optional — only when a webhook endpoint is configured)

`$HOOK` is the registered receiver (e.g. `$SITE/api/harborly/webhook`); `$SECRET` equals `HARBORLY_WEBHOOK_SECRET`. Sign locally with openssl — the key is the full secret string including its `whsec_` prefix, the message is `{timestamp}.{rawBody}`:

```bash
TS=$(date +%s)
BODY='{"id":"11111111-1111-7111-8111-111111111111","type":"test.ping","occurredAt":"2026-01-01T00:00:00+00:00","projectId":"22222222-2222-3222-8222-222222222222","publicSlug":"your-public-slug","resource":{"type":"test","id":"33333333-3333-8333-3333-333333333333","slug":null,"locale":null,"publishedRevision":null,"translationGroupId":null}}'
SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $NF}')

# Correctly signed probe: expect 200
curl -sS -o /dev/null -w '%{http_code}\n' -X POST "$HOOK" \
  -H 'Content-Type: application/json' \
  -H 'Harborly-Event-Id: 11111111-1111-7111-8111-111111111111' \
  -H 'Harborly-Event-Type: test.ping' \
  -H "Harborly-Timestamp: $TS" \
  -H "Harborly-Signature: v1=$SIG" \
  --data-raw "$BODY"
```

- **Signature errors return 401**: flip one character in `Harborly-Signature` (or modify the body without re-signing) — `$HOOK` answers `401`, and the delivery is retried by Harborly, not accepted.
- **Stale timestamps are rejected**: resend with `Harborly-Timestamp` set to `$(($(date +%s) - 601))` — `401`.
- **Duplicate events are processed once**: resend the identical signed request (same `Harborly-Event-Id`) — the answer is `200` again, but the handler's log line shows the invalidation ran only once.
- **Test event shows 200**: trigger **send test event** in Harborly Web (Content Hub → Webhook); the endpoint's delivery record turns `200` within seconds.
- **Fast refresh**: publish an article update in Harborly, reload the blog page seconds later — the change is visible without waiting out the 120 s fetch `revalidate` plus the API cache.
- **Nothing breaks without it**: with no webhook configured (or the endpoint disabled), the whole checklist above still passes within the documented consistency window.
