1011 lines
50 KiB
Markdown
1011 lines
50 KiB
Markdown
# JSON-LD lib (`packages/libs/src/json-ld`)
|
||
|
||
Builds the schema.org JSON-LD that introduces the business and every indexable page to Google, focused on ecommerce: the business and the website on the home page, a product or a product with variants on its page, with its offer, sale price, rating, and reviews, the store-wide return and shipping policies on their own pages, the breadcrumb trail, and a physical store. Server only: JSON-LD is part of the server render and the same for every visitor, and island's `JsonLd` primitive writes it into the page. Framework-agnostic; no dependency. schema-dts makes every property optional, so it accepts a product with no price, `IRT`, and Jalali dates; next-seo's serializer escapes only `</script>`, which `</script >` gets past; react-schemaorg turns `&` into `&` inside values.
|
||
|
||
Sources: the vocabulary at schema.org/docs/schemas.html; what Google reads, requires, and shows at developers.google.com/search/docs/appearance/structured-data.
|
||
|
||
Contents: What each page gets · What the markup may say · Structure · Types · API · Values · Rendering · Not in this lib · Adding a type · Implementation · Usage · Testing and monitoring · Acceptance checklist
|
||
|
||
## What each page gets
|
||
|
||
| Page | Nodes | What Google does with them |
|
||
|---|---|---|
|
||
| Home, in every locale | `buildOrganization` (an `OnlineStore`) and `buildWebSite` | The logo, contact details, and identifiers in the knowledge panel; the site name beside every result |
|
||
| Product | `buildProduct`, or `buildProductGroup` when the page sells variants; `buildBreadcrumbList` | Merchant listings and product snippets: price, sale price, availability, rating, and the product's own shipping and returns; the trail on desktop results |
|
||
| Category, brand, and other listings | `buildBreadcrumbList` | The trail on desktop results |
|
||
| Returns policy | `buildOrganization` with `returnPolicy` | The store's return window and fees on its product results |
|
||
| Shipping policy | `buildOrganization` with `shipping` | The store's delivery cost and time on its product results |
|
||
| Store branch | `buildStore` and `buildBreadcrumbList` | The branch's address, opening hours, and phone |
|
||
| Search results, cart, checkout, account, compare, and every not-found, no-access, or error state | Nothing | Nothing: these pages are `noindex`, or blocked in `robots.ts` |
|
||
|
||
- One graph per page: the page passes its nodes to `buildGraph` and renders the result with one `<JsonLd>`.
|
||
- The platform's `app/json-ld/` holds one builder per page type that maps a `*Payload`, such as `buildProductPageJsonLd(product)`. The home and policy pages build theirs from the business facts in the app's `configs/seo.ts` (Usage).
|
||
|
||
## What the markup may say
|
||
|
||
Google shows rich results only from markup it trusts, and a manual action for misleading markup makes it ignore the site's markup. So:
|
||
|
||
- Only what the page shows. The name, price, sale price, availability, rating, review count, reviews, and policies match the server HTML of the same URL, in both templates. They come from the same `*Payload` in the same request, so they match by construction. Never add a value the page doesn't show; identifiers (`sku`, `gtin`, `mpn`) and the brand may stay invisible.
|
||
- The same for every visitor. Build it only from what the server render reads, never from the viewer: no member price, personal price, cart, or recommendation. A page whose price depends on the viewer, such as a B2B price list after login, has no `offer`; its product can still carry its rating.
|
||
- The page's main thing. A product page marks up its product, never the products in its rails, which have their own pages.
|
||
- No self-serving ratings. `rating` and `reviews` go on products only, never on the organization or a store: Google ignores what a business shows about itself.
|
||
- One name for the business. `buildOrganization` and `buildWebSite` take the same `name` and `alternateName`, and every locale's home page renders the same `buildWebSite`, because Google keeps one site name per domain.
|
||
- Nothing Google stopped showing: no `FAQPage` (FAQ rich results ended on May 7, 2026), no `SearchAction` (the sitelinks search box ended on November 21, 2024), and no `HowTo` (ended in September 2023).
|
||
|
||
## Structure
|
||
|
||
```
|
||
packages/libs/src/json-ld/
|
||
├── json-ld.ts # configureJsonLd, buildGraph, serializeJsonLd
|
||
├── organization.ts # buildOrganization (an OnlineStore), buildWebSite
|
||
├── product.ts # buildProduct, buildProductGroup
|
||
├── offer.ts # Offer with its struck-through price, and AggregateOffer; used by product.ts
|
||
├── policies.ts # return policy and shipping: store-wide for organization.ts, per product for offer.ts
|
||
├── breadcrumb.ts # buildBreadcrumbList
|
||
├── store.ts # buildStore: a physical branch
|
||
├── values.ts # absolute URLs, enumeration URLs, @id values, plain text; not exported
|
||
├── types.ts # every builder's input, and the nodes and graph they return
|
||
├── constants.ts # JSON_LD_CONTEXT, SCHEMA_ORG_URL, JSON_LD_LIMITS
|
||
└── server.ts # the module's only entry; import 'server-only'
|
||
```
|
||
|
||
- The module is server-only, like a feature's `caches/`: it has only `server.ts`, exposed as the `@project/libs/json-ld/server` subpath and re-exported by the project's `server.ts`. A client component that imports it fails the build, so JSON-LD stays in the server render and its builders stay out of client bundles.
|
||
- `server.ts` exports `configureJsonLd`, `buildGraph`, `serializeJsonLd`, `buildOrganization`, `buildWebSite`, `buildProduct`, `buildProductGroup`, `buildBreadcrumbList`, `buildStore`, `JSON_LD_LIMITS`, and the types.
|
||
- It reads no env and imports no React or Next.js. island's `JsonLd` primitive renders its graph, and the platform's `app/json-ld/` calls its builders.
|
||
|
||
## Types
|
||
|
||
Inputs are plain values: what the page shows, in the shape a payload gives it. The builders write the schema.org shape. Enumeration members are schema.org names (`'InStock'`), which the lib writes as full URLs (`https://schema.org/InStock`). Google's required values are required in the types, so a missing one fails type-check before it fails in Search Console.
|
||
|
||
```ts
|
||
import type { JSON_LD_CONTEXT } from './constants';
|
||
|
||
// An absolute URL, or a root-relative path ('/product/123') that resolves against siteUrl.
|
||
export type Url = string;
|
||
|
||
export type JsonLdOptions = {
|
||
siteUrl: string; // the site's origin from the app's env; the same value as metadataBase
|
||
};
|
||
|
||
// What the builders return. Callers pass nodes to buildGraph and never read them.
|
||
export type JsonLdValue = string | number | boolean | JsonLdNode | readonly JsonLdValue[] | null | undefined;
|
||
export type JsonLdNode = { readonly [property: string]: JsonLdValue };
|
||
export type JsonLdGraph = { readonly '@context': typeof JSON_LD_CONTEXT; readonly '@graph': readonly JsonLdNode[] };
|
||
|
||
// schema.org enumeration members, written as https://schema.org/<member>.
|
||
// Only the members Google reads; schema.org has more.
|
||
export type ItemAvailability =
|
||
| 'InStock' | 'LimitedAvailability' | 'OutOfStock' | 'SoldOut' | 'BackOrder'
|
||
| 'PreOrder' | 'PreSale' | 'InStoreOnly' | 'OnlineOnly' | 'Discontinued';
|
||
export type OfferItemCondition = 'NewCondition' | 'UsedCondition' | 'RefurbishedCondition';
|
||
export type ReturnMethod = 'ReturnByMail' | 'ReturnInStore' | 'ReturnAtKiosk';
|
||
export type ReturnFees = 'FreeReturn' | 'ReturnFeesCustomerResponsibility' | 'ReturnShippingFees';
|
||
export type DayOfWeek = 'Saturday' | 'Sunday' | 'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday';
|
||
// The properties a group's variants differ in, written as https://schema.org/<property>.
|
||
export type VariesBy = 'color' | 'size' | 'material' | 'pattern';
|
||
|
||
export type MoneyInput = { value: number; currency: string }; // currency: ISO 4217
|
||
export type DaysInput = { min: number; max: number }; // whole days
|
||
|
||
export type PostalAddressInput = {
|
||
country: string; // ISO 3166-1 alpha-2, e.g. 'IR'
|
||
region?: string;
|
||
locality?: string;
|
||
street?: string;
|
||
postalCode?: string;
|
||
};
|
||
|
||
export type ShippingConditionInput = {
|
||
country: string; // where it ships, ISO 3166-1 alpha-2
|
||
rate: MoneyInput; // value 0 is free
|
||
transitDays?: DaysInput; // from the dispatch to the door
|
||
};
|
||
|
||
// Store-wide shipping. When several conditions match an order, Google uses the cheapest.
|
||
export type ShippingServiceInput = {
|
||
handlingDays?: DaysInput; // from the order to the dispatch
|
||
conditions: readonly (ShippingConditionInput & { orderValueFrom?: number })[]; // orderValueFrom: in rate.currency
|
||
};
|
||
|
||
// A product's own shipping, when it differs from the store's. Google needs both times here.
|
||
export type ShippingInput = Required<ShippingConditionInput> & { handlingDays: DaysInput };
|
||
|
||
type ReturnWindow = {
|
||
country: string | readonly string[]; // where the policy applies
|
||
returnCountry: string; // where the items go back to
|
||
method?: ReturnMethod;
|
||
fees?: ReturnFees;
|
||
shippingFee?: MoneyInput; // only with fees 'ReturnShippingFees'
|
||
};
|
||
|
||
export type ReturnPolicyInput =
|
||
| (ReturnWindow & { category: 'MerchantReturnFiniteReturnWindow'; days: number })
|
||
| (ReturnWindow & { category: 'MerchantReturnUnlimitedWindow' })
|
||
| { category: 'MerchantReturnNotPermitted'; country: string | readonly string[] };
|
||
|
||
export type OfferInput = {
|
||
price: number; // the price the page shows, greater than 0: on a marketplace, the buy box's
|
||
priceCurrency: string; // ISO 4217
|
||
availability: ItemAvailability;
|
||
itemCondition?: OfferItemCondition; // omit for new items
|
||
listPrice?: number; // the struck-through price the page shows beside a discount
|
||
saleStarts?: string; // the sale's window: ISO 8601 date-time with offset, e.g. '2026-10-31T23:59:59+03:30'
|
||
saleEnds?: string;
|
||
shipping?: readonly ShippingInput[]; // only when they differ from the store's policies
|
||
returnPolicy?: ReturnPolicyInput;
|
||
};
|
||
|
||
// A page that shows a price range from several sellers and no single price. Product snippets only:
|
||
// merchant listings need one Offer. Never for variants.
|
||
export type OfferRangeInput = { lowPrice: number; highPrice: number; offerCount: number; priceCurrency: string };
|
||
|
||
export type RatingInput = {
|
||
value: number; // the average the page shows
|
||
count: number; // how many ratings it averages
|
||
best?: number; // default 5
|
||
worst?: number; // default 1
|
||
};
|
||
|
||
export type ReviewInput = {
|
||
author: string; // the name the page shows, under 100 characters
|
||
rating: number;
|
||
best?: number; // default 5
|
||
body?: string;
|
||
datePublished?: string; // ISO 8601
|
||
};
|
||
|
||
export type ProductInput = {
|
||
url: Url; // the page's canonical URL
|
||
name: string;
|
||
image: readonly Url[]; // the gallery, main image first
|
||
description?: string; // plain text the page shows
|
||
sku?: string;
|
||
gtin?: string; // 8, 12, 13 or 14 digits
|
||
mpn?: string;
|
||
brand?: string;
|
||
category?: string; // the shop's category path, e.g. 'Electronics > Mobile phones'
|
||
color?: string;
|
||
size?: string;
|
||
material?: string;
|
||
pattern?: string;
|
||
offer?: OfferInput | OfferRangeInput;
|
||
rating?: RatingInput;
|
||
reviews?: readonly ReviewInput[]; // every review the server HTML shows, or none
|
||
};
|
||
|
||
// A variant: its own name ('Wool coat, green, small'), images, unique sku, attributes, and offer.
|
||
// url is the page with the variant selected, such as '/product/12?color=green&size=s'.
|
||
export type VariantInput = Omit<ProductInput, 'rating' | 'reviews'> & { sku: string };
|
||
|
||
// The variants of one product, on one page that preselects a variant from its URL.
|
||
export type ProductGroupInput = {
|
||
url: Url; // the page's canonical URL, with no variant selected
|
||
groupId: string; // the parent SKU
|
||
name: string;
|
||
variesBy: readonly VariesBy[];
|
||
variants: readonly VariantInput[];
|
||
image?: readonly Url[];
|
||
description?: string;
|
||
brand?: string;
|
||
rating?: RatingInput; // ratings and reviews that cover every variant
|
||
reviews?: readonly ReviewInput[];
|
||
};
|
||
|
||
export type BreadcrumbInput = { name: string; url: Url };
|
||
|
||
export type ContactPointInput = {
|
||
contactType: string; // e.g. 'customer service'
|
||
telephone?: string; // with the country code, e.g. '+98-21-12345678'
|
||
email?: string;
|
||
areaServed?: string | readonly string[];
|
||
availableLanguage?: readonly string[];
|
||
};
|
||
|
||
export type OrganizationInput = {
|
||
name: string; // the site name, as in WebSiteInput
|
||
logo: Url; // at least 112x112 px, crawlable, readable on white
|
||
url?: Url; // default '/'
|
||
alternateName?: string | readonly string[];
|
||
legalName?: string;
|
||
description?: string;
|
||
sameAs?: readonly Url[]; // official profiles on other sites
|
||
telephone?: string;
|
||
email?: string;
|
||
address?: PostalAddressInput;
|
||
contactPoints?: readonly ContactPointInput[];
|
||
iso6523Code?: string; // e.g. '0060:123456789' (DUNS); Google prefers it to vatId and taxId
|
||
vatId?: string;
|
||
taxId?: string;
|
||
foundingDate?: string; // ISO 8601
|
||
returnPolicy?: ReturnPolicyInput; // only on the page that shows the policy
|
||
shipping?: readonly ShippingServiceInput[]; // only on the page that shows the rates
|
||
};
|
||
|
||
export type WebSiteInput = {
|
||
name: string; // one per domain: the same in every locale
|
||
alternateName?: string | readonly string[]; // most preferred first
|
||
inLanguage?: string; // BCP 47, e.g. 'fa-IR'
|
||
};
|
||
|
||
export type OpeningHoursInput = { days: readonly DayOfWeek[]; opens: string; closes: string }; // 'HH:MM', local time
|
||
|
||
export type StoreInput = {
|
||
type?: `${string}Store`; // the most specific subtype, e.g. 'ElectronicsStore'; default 'Store'
|
||
url: Url; // the branch's page
|
||
name: string;
|
||
address: PostalAddressInput;
|
||
image?: readonly Url[];
|
||
telephone?: string;
|
||
geo?: { latitude: number; longitude: number }; // at least 5 decimal places
|
||
openingHours?: readonly OpeningHoursInput[];
|
||
priceRange?: string;
|
||
};
|
||
```
|
||
|
||
## API
|
||
|
||
- `configureJsonLd({ siteUrl })` runs once, in `bootstrap.server.ts`, with the site's origin from the app's env (`NEXT_PUBLIC_SITE_URL`, the value that also sets `metadataBase`). It keeps only the origin and throws on an invalid URL, so a bad value stops the app at startup. A builder called before it throws "json-ld is not configured. bootstrap.server.ts must call configureJsonLd first."
|
||
- Every `build*` function is pure: it takes one input and returns one node, or `null` when a value Google requires is missing or invalid. It never throws on data, because a page renders the same with or without its markup:
|
||
- `buildProduct` returns `null` without a name, an image, and at least one of a valid offer, rating, or review: Google shows no product without one of them.
|
||
- `buildProductGroup` returns `null` without a name, a valid variant, or one of a priced variant, a rating, or a review. A variant needs a name and an image; a variant without its own images gets the group's from the caller.
|
||
- `buildBreadcrumbList` returns `null` for a trail of fewer than two items, which Google ignores.
|
||
- Inside a node, the lib drops an offer whose price isn't greater than 0, a rating with no count or a value outside its scale, a review without an author or a valid rating, a GTIN with a wrong length or check digit, and a URL that isn't `http` or `https`.
|
||
- `buildGraph(...nodes)` drops `null` nodes and empty values (`undefined`, `null`, `NaN`, blank strings, empty arrays, and objects left with only their `@type`) and returns `{ '@context': 'https://schema.org', '@graph': [...] }`, or `null` when no node is left.
|
||
- `serializeJsonLd(graph)` returns the JSON text with `<`, `>`, `&`, U+2028, and U+2029 written as `\u` escapes, so no value can end the script element or open an HTML comment, and `JSON.parse` returns the same values. Only island's `JsonLd` calls it.
|
||
- URLs: every URL input takes a root-relative path (`/product/123`) or an absolute URL. A path resolves against `siteUrl`; an absolute URL, such as an image on the CDN, keeps its origin. Non-ASCII paths come out percent-encoded, as Google recommends.
|
||
- `@id`: the organization is `<siteUrl>/#organization`, the website `<siteUrl>/#website`, a product or group `<url>#product`, and a store `<url>#store`. The website points at the organization as its `publisher` through that `@id`, and every page and locale gives the organization the same one.
|
||
|
||
## Values
|
||
|
||
JSON-LD is read by machines in every locale, so its values keep their machine form whatever the page's language:
|
||
|
||
- Text: plain text the page shows, in the page's language, never HTML or entities. Use the payload's plain fields, such as a summary, not the HTML description. The lib collapses whitespace and cuts descriptions at `JSON_LD_LIMITS.descriptionLength` characters. It never cuts a review, which must match the page.
|
||
- Numbers: JavaScript numbers, never formatted strings. No thousands separators, currency signs, or Persian digits: `'۱۲٬۹۰۰٬۰۰۰ تومان'` is what the page shows, and `129000000` with `'IRR'` is the value. The page formats with `Intl`; JSON-LD keeps the raw number.
|
||
- Prices: greater than 0, in the currency's main unit, with `priceCurrency` as an ISO 4217 code. Toman has no ISO 4217 code, and Search Console flags `IRT`, so a site that shows toman writes rials: the price times 10, with `'IRR'`. Google shows a toman price labelled `IRR` as rials, at a tenth of the real price. The currency code and the multiplier are constants in one place, because the rial redenomination may bring a new ISO code. One URL has one currency: a site that sells in two currencies serves them on different URLs, never by cookie or location. On a marketplace, the offer is the buy box: the seller and price the page shows first.
|
||
- Dates: ISO 8601 in the Gregorian calendar, as the API sends them (`2026-10-31`, or `2026-10-31T23:59:59+03:30`). Never a Jalali date, a date formatted for display, or a date without zero padding (`2026-10-9`). A date-time always carries its offset, Iran's being `+03:30`, because Google reads one without it in Googlebot's time zone. A sale's `saleStarts` comes before its `saleEnds`.
|
||
- Codes: countries in ISO 3166-1 alpha-2 (`'IR'`), languages in BCP 47 (`'fa-IR'`), and telephones with the country code (`'+98-21-12345678'`). Days of the week and every enumeration member stay in English.
|
||
- Identifiers: `gtin` in its numeric form, never a GS1 Digital Link URL; the lib fixes Persian and Arabic digits, spaces, and dashes. `sku` has no spaces, and every variant has its own. `mpn` is the manufacturer's part number.
|
||
- Images: absolute URLs that Googlebot can crawl and index, the main image first. Never a URL that `robots.txt` blocks or that needs a cookie.
|
||
- URLs: canonical. A page's `url` is the path that `generateMetadata` gives `alternates.canonical`, both from the platform's navigation paths.
|
||
|
||
## Rendering
|
||
|
||
- Where: in the page entry (`page.tsx`), once, before the mobile or desktop template, in the first flush, so it's near the top of the HTML. Google prefers product markup in the initial HTML and reads only the first 2 MB of a page. What streams arrives at the end of the document, in a hidden `<div>` that client JavaScript moves into place. An indexable page has nothing above it that streams, no `loading.tsx` included, so its page entry is always in the first flush ([b2c-b2b.md](b2c-b2b.md#rendering)). Never in a layout, where every page under it would repeat it; in a template, which the page has in two versions; in a part inside `<Suspense>`; or in a client component, which can't import the lib.
|
||
- Inside an element: the root layout renders page content inside an element such as `<main>`, so no JSON-LD is a direct child of `<head>` or `<body>`. When the root fails to hydrate, React renders the document again in the browser but keeps the scripts that sit directly under `<head>` and `<body>`, and Google then reads two copies.
|
||
- A native `<script>`, never `next/script`: `next/script` adds the element only after hydration, so Google would read it as JavaScript-generated markup.
|
||
- From what: only data the page already awaits for its first paint, through the same caches. JSON-LD never waits for a read of its own. Reviews that stream in a part stay out; the product's rating summary is enough for its stars.
|
||
- Which pages: indexable pages whose main read is `ok`. Not-found, no-access, and error states, and every `noindex` route, render none, because Google ignores markup there.
|
||
- The element is a data block: browsers never run `<script type="application/ld+json">`, so it needs no CSP nonce and adds no JavaScript.
|
||
- Size: Next.js sends every JSON-LD byte twice in the HTML: in the element, and again, escaped, in the RSC payload that hydrates the page, so a graph costs more than twice its size. Keep it to what Google reads. The builders cap images at `JSON_LD_LIMITS.images` and descriptions at `JSON_LD_LIMITS.descriptionLength` characters.
|
||
|
||
## Not in this lib
|
||
|
||
| Not here | Why |
|
||
|---|---|
|
||
| `WebPage` and its subtypes, `SiteNavigationElement`, `WPHeader`, and `WPFooter` | No Google feature reads them; they only add bytes |
|
||
| `ItemList` on listing pages | Google reads it only for its structured data carousels, a beta limited to a few regions such as the EEA. A site that serves one adds it as Adding a type describes |
|
||
| `FAQPage`, `SearchAction`, and `HowTo` | Google no longer shows them (What the markup may say) |
|
||
| Member prices and loyalty programs | A member price is the viewer's data, which renders in the browser ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)), and Google shows loyalty benefits in only eight countries |
|
||
| `seller` on an offer | Google reads no seller; on a marketplace, the offer is the buy box |
|
||
| Pros and cons (`positiveNotes`, `negativeNotes`) | Google shows them only for editorial review pages, never a shop's product page, and not in Persian |
|
||
| `hasCertification`, `subjectOf` (3D models), `hasAdultConsideration` | EU energy labels, glTF models, and adult products; add the property when the shop sells them |
|
||
| Merchant Center feeds | A product feed is a back-end export, not page markup |
|
||
| Microdata and RDFa | JSON-LD only, so markup never touches the templates |
|
||
| JSON-LD added in the browser, by client code or a tag manager | It arrives after rendering, if at all, and can differ from the server HTML |
|
||
| Other types, such as `BlogPosting` for a shop blog, `VideoObject` for product videos, and `Event` | Add a builder when a page needs one (next section) |
|
||
|
||
## Adding a type
|
||
|
||
1. Read the type on schema.org and its feature page in Google's structured data docs. Write only the properties Google reads, and keep its required properties required in the input type.
|
||
2. Add the input type to `types.ts` and a `build<Type>` function in its own file that returns `null` when a required value is missing. Export both by name from `server.ts`.
|
||
3. Add its cases to the lib's tests, and check one rendered page in the Rich Results Test.
|
||
|
||
## Implementation
|
||
|
||
`server.ts` starts with `import 'server-only';` and re-exports by name the functions and `JSON_LD_LIMITS` that Structure lists, and the types `JsonLdGraph`, `JsonLdNode`, `JsonLdOptions`, the enumerations, and every `*Input`.
|
||
|
||
`constants.ts`
|
||
|
||
```ts
|
||
export const JSON_LD_CONTEXT = 'https://schema.org';
|
||
|
||
// Enumeration members and variesBy properties are written as full URLs: SCHEMA_ORG_URL + name.
|
||
export const SCHEMA_ORG_URL = 'https://schema.org/';
|
||
|
||
// Every byte reaches the visitor twice: in the script element and in the page's RSC payload.
|
||
export const JSON_LD_LIMITS = {
|
||
images: 5,
|
||
descriptionLength: 1000,
|
||
authorNameLength: 99, // Google ignores a review whose author name is 100 characters or longer
|
||
} as const;
|
||
```
|
||
|
||
`json-ld.ts`
|
||
|
||
```ts
|
||
import { JSON_LD_CONTEXT } from './constants';
|
||
import type { JsonLdGraph, JsonLdNode, JsonLdOptions } from './types';
|
||
|
||
let options: JsonLdOptions | undefined;
|
||
|
||
export function configureJsonLd(next: JsonLdOptions): void {
|
||
// Only the origin: paths resolve against it. An invalid URL throws at startup.
|
||
options = { siteUrl: new URL(next.siteUrl).origin };
|
||
}
|
||
|
||
export function getJsonLdOptions(): JsonLdOptions {
|
||
if (!options) {
|
||
throw new Error('json-ld is not configured. bootstrap.server.ts must call configureJsonLd first.');
|
||
}
|
||
return options;
|
||
}
|
||
|
||
export function buildGraph(...nodes: (JsonLdNode | null | undefined)[]): JsonLdGraph | null {
|
||
const graph = nodes.map((node) => compact(node) as JsonLdNode | undefined).filter((node) => node !== undefined);
|
||
return graph.length > 0 ? { '@context': JSON_LD_CONTEXT, '@graph': graph } : null;
|
||
}
|
||
|
||
// JSON.stringify keeps "<" as it is, so a product named "</script>..." would end the element.
|
||
const UNSAFE_IN_HTML = /[<>&\u2028\u2029]/g;
|
||
|
||
export function serializeJsonLd(graph: JsonLdGraph): string {
|
||
return JSON.stringify(graph).replace(UNSAFE_IN_HTML, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
||
}
|
||
|
||
// Drops what says nothing: undefined, null, NaN, blank strings, empty arrays,
|
||
// and objects left with nothing but their @type.
|
||
function compact(value: unknown): unknown {
|
||
if (Array.isArray(value)) {
|
||
const items = value.map(compact).filter((item) => item !== undefined);
|
||
return items.length > 0 ? items : undefined;
|
||
}
|
||
if (value !== null && typeof value === 'object') {
|
||
const entries = Object.entries(value)
|
||
.map(([key, item]) => [key, compact(item)] as const)
|
||
.filter(([, item]) => item !== undefined);
|
||
return entries.some(([key]) => key !== '@type') ? Object.fromEntries(entries) : undefined;
|
||
}
|
||
if (typeof value === 'string') return value.trim() || undefined;
|
||
if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
|
||
return value ?? undefined;
|
||
}
|
||
```
|
||
|
||
`values.ts`
|
||
|
||
```ts
|
||
import { SCHEMA_ORG_URL } from './constants';
|
||
import { getJsonLdOptions } from './json-ld';
|
||
import type { JsonLdNode, MoneyInput, PostalAddressInput, Url } from './types';
|
||
|
||
// '/product/12' becomes 'https://www.example.com/product/12'; absolute URLs keep their origin.
|
||
// A value that isn't an http(s) URL is dropped, never thrown: bad data never breaks the page.
|
||
export function absoluteUrl(url: Url | undefined): string | undefined {
|
||
const value = url?.trim();
|
||
if (!value) return undefined; // a blank URL would resolve to the home page
|
||
const { siteUrl } = getJsonLdOptions(); // outside the try: a missing configureJsonLd must throw
|
||
try {
|
||
const parsed = new URL(value, siteUrl);
|
||
return parsed.protocol === 'https:' || parsed.protocol === 'http:' ? parsed.href : undefined;
|
||
} catch {
|
||
return undefined;
|
||
}
|
||
}
|
||
|
||
// 'InStock' becomes 'https://schema.org/InStock'.
|
||
export function schemaUrl(name: string): string {
|
||
return `${SCHEMA_ORG_URL}${name}`;
|
||
}
|
||
|
||
// A stable @id, so nodes in one graph can point at each other: 'https://www.example.com/#organization'.
|
||
export function nodeId(url: Url, name: string): string | undefined {
|
||
const absolute = absoluteUrl(url);
|
||
return absolute && `${absolute}#${name}`;
|
||
}
|
||
|
||
// One line of plain text, cut at maxLength characters.
|
||
export function plainText(value: string | undefined, maxLength = Number.POSITIVE_INFINITY): string | undefined {
|
||
const text = value?.replace(/\s+/g, ' ').trim();
|
||
if (!text) return undefined;
|
||
const chars = Array.from(text);
|
||
return chars.length <= maxLength ? text : `${chars.slice(0, maxLength - 1).join('').trimEnd()}…`;
|
||
}
|
||
|
||
// A GTIN as Google reads it: 8, 12, 13 or 14 Latin digits with a valid GS1 check digit.
|
||
// Persian and Arabic digits, spaces and dashes are fixed; anything else is dropped.
|
||
export function gtin(value: string | undefined): string | undefined {
|
||
const digits = value
|
||
?.replace(/[۰-۹]/g, (digit) => String(digit.charCodeAt(0) - 0x06f0))
|
||
.replace(/[٠-٩]/g, (digit) => String(digit.charCodeAt(0) - 0x0660))
|
||
.replace(/[\s-]/g, '');
|
||
if (!digits || !/^(\d{8}|\d{12,14})$/.test(digits)) return undefined;
|
||
// From the right, the check digit has weight 1, the next digit 3, then 1, 3, and so on.
|
||
const sum = Array.from(digits)
|
||
.reverse()
|
||
.reduce((total, digit, index) => total + Number(digit) * (index % 2 === 0 ? 1 : 3), 0);
|
||
return sum % 10 === 0 ? digits : undefined;
|
||
}
|
||
|
||
export function money({ value, currency }: MoneyInput): JsonLdNode {
|
||
return { '@type': 'MonetaryAmount', value, currency };
|
||
}
|
||
|
||
export function postalAddress(address: PostalAddressInput): JsonLdNode {
|
||
return {
|
||
'@type': 'PostalAddress',
|
||
addressCountry: address.country,
|
||
addressRegion: address.region,
|
||
addressLocality: address.locality,
|
||
streetAddress: address.street,
|
||
postalCode: address.postalCode,
|
||
};
|
||
}
|
||
|
||
export function isNode(node: JsonLdNode | null | undefined): node is JsonLdNode {
|
||
return node !== null && node !== undefined;
|
||
}
|
||
```
|
||
|
||
`policies.ts`
|
||
|
||
```ts
|
||
import type { DaysInput, JsonLdNode, ReturnPolicyInput, ShippingInput, ShippingServiceInput } from './types';
|
||
import { money, schemaUrl } from './values';
|
||
|
||
export function returnPolicy(input: ReturnPolicyInput): JsonLdNode {
|
||
if (input.category === 'MerchantReturnNotPermitted') {
|
||
return {
|
||
'@type': 'MerchantReturnPolicy',
|
||
applicableCountry: input.country,
|
||
returnPolicyCategory: schemaUrl(input.category),
|
||
};
|
||
}
|
||
return {
|
||
'@type': 'MerchantReturnPolicy',
|
||
applicableCountry: input.country,
|
||
returnPolicyCategory: schemaUrl(input.category),
|
||
returnPolicyCountry: input.returnCountry,
|
||
merchantReturnDays: input.category === 'MerchantReturnFiniteReturnWindow' ? input.days : undefined,
|
||
returnMethod: input.method && schemaUrl(input.method),
|
||
returnFees: input.fees && schemaUrl(input.fees),
|
||
returnShippingFeesAmount: input.fees === 'ReturnShippingFees' && input.shippingFee ? money(input.shippingFee) : undefined,
|
||
};
|
||
}
|
||
|
||
// The store-wide shipping, on the organization.
|
||
export function shippingService(input: ShippingServiceInput): JsonLdNode {
|
||
return {
|
||
'@type': 'ShippingService',
|
||
handlingTime: input.handlingDays && servicePeriod(input.handlingDays),
|
||
shippingConditions: input.conditions.map((condition) => ({
|
||
'@type': 'ShippingConditions',
|
||
shippingDestination: { '@type': 'DefinedRegion', addressCountry: condition.country },
|
||
orderValue:
|
||
condition.orderValueFrom === undefined
|
||
? undefined
|
||
: { '@type': 'MonetaryAmount', minValue: condition.orderValueFrom, currency: condition.rate.currency },
|
||
shippingRate: money(condition.rate),
|
||
transitTime: condition.transitDays && servicePeriod(condition.transitDays),
|
||
})),
|
||
};
|
||
}
|
||
|
||
// A product's own shipping, on its offer, when it differs from the store's.
|
||
export function shippingDetails(input: ShippingInput): JsonLdNode {
|
||
return {
|
||
'@type': 'OfferShippingDetails',
|
||
shippingDestination: { '@type': 'DefinedRegion', addressCountry: input.country },
|
||
shippingRate: money(input.rate),
|
||
deliveryTime: {
|
||
'@type': 'ShippingDeliveryTime',
|
||
handlingTime: days(input.handlingDays),
|
||
transitTime: days(input.transitDays),
|
||
},
|
||
};
|
||
}
|
||
|
||
function servicePeriod(range: DaysInput): JsonLdNode {
|
||
return { '@type': 'ServicePeriod', duration: days(range) };
|
||
}
|
||
|
||
function days({ min, max }: DaysInput): JsonLdNode {
|
||
return { '@type': 'QuantitativeValue', minValue: min, maxValue: max, unitCode: 'DAY' };
|
||
}
|
||
```
|
||
|
||
`offer.ts`
|
||
|
||
```ts
|
||
import { returnPolicy, shippingDetails } from './policies';
|
||
import type { JsonLdNode, OfferInput, OfferRangeInput, Url } from './types';
|
||
import { absoluteUrl, schemaUrl } from './values';
|
||
|
||
// null when the price can't be shown: missing, zero, negative, or not a number.
|
||
export function offerNode(input: OfferInput | OfferRangeInput, url: Url): JsonLdNode | null {
|
||
if ('lowPrice' in input) {
|
||
if (!(input.lowPrice > 0) || !(input.highPrice >= input.lowPrice)) return null;
|
||
return {
|
||
'@type': 'AggregateOffer',
|
||
lowPrice: input.lowPrice,
|
||
highPrice: input.highPrice,
|
||
offerCount: input.offerCount,
|
||
priceCurrency: input.priceCurrency,
|
||
};
|
||
}
|
||
if (!(input.price > 0)) return null;
|
||
return {
|
||
'@type': 'Offer',
|
||
url: absoluteUrl(url),
|
||
price: input.price,
|
||
priceCurrency: input.priceCurrency,
|
||
availability: schemaUrl(input.availability),
|
||
itemCondition: input.itemCondition && schemaUrl(input.itemCondition),
|
||
// Product snippets read priceValidUntil, a date; merchant listings read validFrom and validThrough.
|
||
validFrom: input.saleStarts,
|
||
validThrough: input.saleEnds,
|
||
priceValidUntil: input.saleEnds?.slice(0, 10),
|
||
// The price before the discount, which the page shows struck through.
|
||
priceSpecification:
|
||
input.listPrice !== undefined && input.listPrice > input.price
|
||
? {
|
||
'@type': 'UnitPriceSpecification',
|
||
priceType: schemaUrl('StrikethroughPrice'),
|
||
price: input.listPrice,
|
||
priceCurrency: input.priceCurrency,
|
||
}
|
||
: undefined,
|
||
shippingDetails: input.shipping?.map(shippingDetails),
|
||
hasMerchantReturnPolicy: input.returnPolicy && returnPolicy(input.returnPolicy),
|
||
};
|
||
}
|
||
```
|
||
|
||
`product.ts`
|
||
|
||
```ts
|
||
import { JSON_LD_LIMITS } from './constants';
|
||
import { offerNode } from './offer';
|
||
import type { JsonLdNode, ProductGroupInput, ProductInput, RatingInput, ReviewInput, VariantInput } from './types';
|
||
import { absoluteUrl, gtin, isNode, nodeId, plainText, schemaUrl } from './values';
|
||
|
||
// null when Google can't show the product: no name, no image, or none of a price, a rating, and a review.
|
||
export function buildProduct(input: ProductInput): JsonLdNode | null {
|
||
const product = productNode(input);
|
||
if (!product) return null;
|
||
const offers = input.offer ? offerNode(input.offer, input.url) : null;
|
||
const aggregateRating = input.rating ? ratingNode(input.rating) : null;
|
||
const review = reviewNodes(input.reviews);
|
||
if (!offers && !aggregateRating && review.length === 0) return null;
|
||
return { '@type': 'Product', '@id': nodeId(input.url, 'product'), ...product, offers, aggregateRating, review };
|
||
}
|
||
|
||
// Variants that share one page. Each variant has its own URL (the page with it selected) and offer.
|
||
export function buildProductGroup(input: ProductGroupInput): JsonLdNode | null {
|
||
const name = plainText(input.name);
|
||
const variants = input.variants.map(variantNode).filter(isNode);
|
||
const aggregateRating = input.rating ? ratingNode(input.rating) : null;
|
||
const review = reviewNodes(input.reviews);
|
||
const hasPrice = variants.some((variant) => variant.offers);
|
||
if (!name || variants.length === 0 || (!hasPrice && !aggregateRating && review.length === 0)) return null;
|
||
return {
|
||
'@type': 'ProductGroup',
|
||
'@id': nodeId(input.url, 'product'),
|
||
url: absoluteUrl(input.url),
|
||
name,
|
||
productGroupID: input.groupId,
|
||
variesBy: input.variesBy.map(schemaUrl),
|
||
image: images(input.image),
|
||
description: plainText(input.description, JSON_LD_LIMITS.descriptionLength),
|
||
brand: input.brand && { '@type': 'Brand', name: plainText(input.brand) },
|
||
aggregateRating,
|
||
review,
|
||
hasVariant: variants,
|
||
};
|
||
}
|
||
|
||
function productNode(input: Omit<ProductInput, 'rating' | 'reviews'>): JsonLdNode | null {
|
||
const name = plainText(input.name);
|
||
const image = images(input.image);
|
||
if (!name || image.length === 0) return null;
|
||
return {
|
||
'@type': 'Product',
|
||
name,
|
||
image,
|
||
description: plainText(input.description, JSON_LD_LIMITS.descriptionLength),
|
||
sku: input.sku,
|
||
gtin: gtin(input.gtin),
|
||
mpn: input.mpn,
|
||
brand: input.brand && { '@type': 'Brand', name: plainText(input.brand) },
|
||
category: input.category,
|
||
color: input.color,
|
||
size: input.size,
|
||
material: input.material,
|
||
pattern: input.pattern,
|
||
};
|
||
}
|
||
|
||
function variantNode(input: VariantInput): JsonLdNode | null {
|
||
const variant = productNode(input);
|
||
if (!variant) return null;
|
||
return { ...variant, offers: input.offer ? offerNode(input.offer, input.url) : null };
|
||
}
|
||
|
||
function images(urls: readonly string[] | undefined): string[] {
|
||
return (urls ?? [])
|
||
.map(absoluteUrl)
|
||
.filter((url): url is string => url !== undefined)
|
||
.slice(0, JSON_LD_LIMITS.images);
|
||
}
|
||
|
||
function ratingNode({ value, count, best = 5, worst = 1 }: RatingInput): JsonLdNode | null {
|
||
if (!(count > 0) || !(value >= worst && value <= best)) return null;
|
||
return {
|
||
'@type': 'AggregateRating',
|
||
ratingValue: value,
|
||
ratingCount: count,
|
||
bestRating: best === 5 ? undefined : best,
|
||
worstRating: worst === 1 ? undefined : worst,
|
||
};
|
||
}
|
||
|
||
function reviewNodes(reviews: readonly ReviewInput[] | undefined): JsonLdNode[] {
|
||
return (reviews ?? []).map(reviewNode).filter(isNode);
|
||
}
|
||
|
||
function reviewNode({ author, rating, best = 5, body, datePublished }: ReviewInput): JsonLdNode | null {
|
||
const name = plainText(author);
|
||
if (!name || name.length > JSON_LD_LIMITS.authorNameLength || !(rating >= 1 && rating <= best)) return null;
|
||
return {
|
||
'@type': 'Review',
|
||
author: { '@type': 'Person', name },
|
||
reviewRating: { '@type': 'Rating', ratingValue: rating, bestRating: best === 5 ? undefined : best },
|
||
reviewBody: plainText(body),
|
||
datePublished,
|
||
};
|
||
}
|
||
```
|
||
|
||
`organization.ts`
|
||
|
||
```ts
|
||
import { returnPolicy, shippingService } from './policies';
|
||
import type { ContactPointInput, JsonLdNode, OrganizationInput, WebSiteInput } from './types';
|
||
import { absoluteUrl, nodeId, plainText, postalAddress } from './values';
|
||
|
||
// The business, for the home page. OnlineStore is the Organization subtype Google recommends for a shop.
|
||
export function buildOrganization(input: OrganizationInput): JsonLdNode | null {
|
||
const name = plainText(input.name);
|
||
const logo = absoluteUrl(input.logo);
|
||
if (!name || !logo) return null;
|
||
return {
|
||
'@type': 'OnlineStore',
|
||
'@id': nodeId('/', 'organization'),
|
||
url: absoluteUrl(input.url ?? '/'),
|
||
name,
|
||
alternateName: input.alternateName,
|
||
legalName: plainText(input.legalName),
|
||
description: plainText(input.description),
|
||
logo,
|
||
sameAs: input.sameAs?.map(absoluteUrl),
|
||
telephone: input.telephone,
|
||
email: input.email,
|
||
address: input.address && postalAddress(input.address),
|
||
contactPoint: input.contactPoints?.map(contactPoint),
|
||
iso6523Code: input.iso6523Code,
|
||
vatID: input.vatId,
|
||
taxID: input.taxId,
|
||
foundingDate: input.foundingDate,
|
||
hasMerchantReturnPolicy: input.returnPolicy && returnPolicy(input.returnPolicy),
|
||
hasShippingService: input.shipping?.map(shippingService),
|
||
};
|
||
}
|
||
|
||
// The site name Google shows beside each result, for the home page.
|
||
export function buildWebSite(input: WebSiteInput): JsonLdNode | null {
|
||
const name = plainText(input.name);
|
||
if (!name) return null;
|
||
return {
|
||
'@type': 'WebSite',
|
||
'@id': nodeId('/', 'website'),
|
||
url: absoluteUrl('/'),
|
||
name,
|
||
alternateName: input.alternateName,
|
||
inLanguage: input.inLanguage,
|
||
publisher: { '@id': nodeId('/', 'organization') },
|
||
};
|
||
}
|
||
|
||
function contactPoint(input: ContactPointInput): JsonLdNode {
|
||
return {
|
||
'@type': 'ContactPoint',
|
||
contactType: input.contactType,
|
||
telephone: input.telephone,
|
||
email: input.email,
|
||
areaServed: input.areaServed,
|
||
availableLanguage: input.availableLanguage,
|
||
};
|
||
}
|
||
```
|
||
|
||
`breadcrumb.ts`
|
||
|
||
```ts
|
||
import type { BreadcrumbInput, JsonLdNode } from './types';
|
||
import { absoluteUrl, plainText } from './values';
|
||
|
||
// The trail the page shows. Google needs at least two items.
|
||
export function buildBreadcrumbList(items: readonly BreadcrumbInput[]): JsonLdNode | null {
|
||
const trail = items
|
||
.map((item) => ({ name: plainText(item.name), url: absoluteUrl(item.url) }))
|
||
.filter((item) => item.name && item.url);
|
||
if (trail.length < 2) return null;
|
||
return {
|
||
'@type': 'BreadcrumbList',
|
||
itemListElement: trail.map((item, index) => ({
|
||
'@type': 'ListItem',
|
||
position: index + 1,
|
||
name: item.name,
|
||
item: item.url,
|
||
})),
|
||
};
|
||
}
|
||
```
|
||
|
||
`store.ts`
|
||
|
||
```ts
|
||
import type { JsonLdNode, OpeningHoursInput, StoreInput } from './types';
|
||
import { absoluteUrl, nodeId, plainText, postalAddress, schemaUrl } from './values';
|
||
|
||
// A physical branch, on its own page. Never with ratings: Google ignores reviews a business shows about itself.
|
||
export function buildStore(input: StoreInput): JsonLdNode | null {
|
||
const name = plainText(input.name);
|
||
if (!name) return null;
|
||
return {
|
||
'@type': input.type ?? 'Store',
|
||
'@id': nodeId(input.url, 'store'),
|
||
url: absoluteUrl(input.url),
|
||
name,
|
||
address: postalAddress(input.address),
|
||
image: input.image?.map(absoluteUrl),
|
||
telephone: input.telephone,
|
||
geo: input.geo && { '@type': 'GeoCoordinates', latitude: input.geo.latitude, longitude: input.geo.longitude },
|
||
openingHoursSpecification: input.openingHours?.map(openingHours),
|
||
priceRange: input.priceRange,
|
||
};
|
||
}
|
||
|
||
function openingHours(input: OpeningHoursInput): JsonLdNode {
|
||
return {
|
||
'@type': 'OpeningHoursSpecification',
|
||
dayOfWeek: input.days.map(schemaUrl),
|
||
opens: input.opens,
|
||
closes: input.closes,
|
||
};
|
||
}
|
||
```
|
||
|
||
## Usage
|
||
|
||
`apps/<app>/src/env/env.client.ts` declares the site's origin. Like every env value, it's required and has no default ([lib-env.md](lib-env.md#the-apps-env)). The root layout's `metadataBase` uses the same value.
|
||
|
||
```ts
|
||
// in schema
|
||
NEXT_PUBLIC_SITE_URL: v.pipe(v.string(), v.url()),
|
||
|
||
// in runtimeEnv
|
||
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
|
||
```
|
||
|
||
`bootstrap.server.ts`
|
||
|
||
```ts
|
||
import { configureJsonLd } from '@project/libs/json-ld/server';
|
||
|
||
configureJsonLd({ siteUrl: clientEnv.NEXT_PUBLIC_SITE_URL });
|
||
```
|
||
|
||
The libs `package.json` exposes the module as `"./json-ld/server": "./src/json-ld/server.ts"`, and the project's `server.ts` re-exports it by name ([project-structure.md](project-structure.md#exports-and-tree-shaking)).
|
||
|
||
### island's `JsonLd` primitive
|
||
|
||
`packages/island/src/primitives/json-ld/`: a non-visual primitive with no styles, so no `variants.ts`, and server-only, so `server.ts` and no `index.ts`. island's `package.json` exposes it as `"./primitives/json-ld/server": "./src/primitives/json-ld/server.ts"`, and island's `server.ts` re-exports it.
|
||
|
||
`types.ts`
|
||
|
||
```ts
|
||
import type { JsonLdGraph } from '@project/libs/json-ld/server';
|
||
|
||
export type JsonLdProps = {
|
||
data: JsonLdGraph | null; // from buildGraph; null renders nothing
|
||
};
|
||
```
|
||
|
||
`JsonLd.tsx`
|
||
|
||
```tsx
|
||
import { serializeJsonLd } from '@project/libs/json-ld/server';
|
||
import type { JsonLdProps } from './types';
|
||
|
||
export function JsonLd({ data }: JsonLdProps) {
|
||
if (!data) return null;
|
||
// serializeJsonLd escapes <, > and &, so no value can end the element.
|
||
return <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: serializeJsonLd(data) }} />;
|
||
}
|
||
```
|
||
|
||
`server.ts`
|
||
|
||
```ts
|
||
import 'server-only';
|
||
|
||
export { JsonLd } from './JsonLd';
|
||
export type { JsonLdProps } from './types';
|
||
```
|
||
|
||
### The business's pages
|
||
|
||
`apps/<app>/src/configs/seo.ts` holds the business facts beside the metadata defaults. They're the same in every environment, so they're constants, not env. The returns and shipping pages show the same facts in their text; change both together.
|
||
|
||
```ts
|
||
import type {
|
||
OrganizationInput,
|
||
ReturnPolicyInput,
|
||
ShippingServiceInput,
|
||
WebSiteInput,
|
||
} from '@project/libs/json-ld/server';
|
||
|
||
export const SEO_WEBSITE = {
|
||
name: 'Example',
|
||
alternateName: ['اگزمپل', 'example.com'],
|
||
inLanguage: 'fa-IR',
|
||
} satisfies WebSiteInput;
|
||
|
||
export const SEO_ORGANIZATION = {
|
||
name: SEO_WEBSITE.name,
|
||
alternateName: SEO_WEBSITE.alternateName,
|
||
logo: '/pwa/icon-512.png', // at least 112x112 px and readable on white
|
||
sameAs: ['https://www.instagram.com/example', 'https://www.linkedin.com/company/example'],
|
||
telephone: '+98-21-12345678',
|
||
email: 'support@example.com',
|
||
address: { country: 'IR', locality: 'Tehran', street: 'No. 1, Example St.', postalCode: '1234567890' },
|
||
} satisfies OrganizationInput;
|
||
|
||
export const SEO_RETURN_POLICY = {
|
||
category: 'MerchantReturnFiniteReturnWindow',
|
||
days: 7,
|
||
country: 'IR',
|
||
returnCountry: 'IR',
|
||
method: 'ReturnByMail',
|
||
fees: 'FreeReturn',
|
||
} satisfies ReturnPolicyInput;
|
||
|
||
export const SEO_SHIPPING = [
|
||
{
|
||
handlingDays: { min: 0, max: 1 },
|
||
conditions: [
|
||
{ country: 'IR', rate: { value: 500_000, currency: 'IRR' }, transitDays: { min: 1, max: 4 } },
|
||
{ country: 'IR', rate: { value: 0, currency: 'IRR' }, orderValueFrom: 10_000_000, transitDays: { min: 1, max: 4 } },
|
||
],
|
||
},
|
||
] satisfies ShippingServiceInput[];
|
||
```
|
||
|
||
`apps/<app>/src/app/(shop)/page.tsx`, the home page. `getDevice`, `getHomePage`, and the templates are the page's own, as in [page-example.md](page-example.md).
|
||
|
||
```tsx
|
||
import { JsonLd } from '@project/island/primitives/json-ld/server';
|
||
import { buildGraph, buildOrganization, buildWebSite } from '@project/libs/json-ld/server';
|
||
import { getDevice, getHomePage } from '@project/<platform>/server';
|
||
import { SEO_ORGANIZATION, SEO_WEBSITE } from '../../configs';
|
||
import { HomeDesktop } from './templates/home-desktop';
|
||
import { HomeMobile } from './templates/home-mobile';
|
||
|
||
export default async function HomePage() {
|
||
const [device, home] = await Promise.all([getDevice(), getHomePage()]);
|
||
return (
|
||
<>
|
||
<JsonLd data={buildGraph(buildOrganization(SEO_ORGANIZATION), buildWebSite(SEO_WEBSITE))} />
|
||
{device === 'mobile' ? <HomeMobile home={home} /> : <HomeDesktop home={home} />}
|
||
</>
|
||
);
|
||
}
|
||
```
|
||
|
||
The returns page renders `buildOrganization({ ...SEO_ORGANIZATION, returnPolicy: SEO_RETURN_POLICY })`, and the shipping page `buildOrganization({ ...SEO_ORGANIZATION, shipping: SEO_SHIPPING })`, the same way.
|
||
|
||
### Pages built from a payload
|
||
|
||
`platforms/<platform>/src/app/json-ld/` holds one server-only builder per page type. It sits in the platform's `app/` because it reads features' `*Payload` types and the navigation paths, and nothing in `features/` may import `app/`. Its entry is `server.ts`, with no `index.ts`, and the platform's `server.ts` re-exports it. `paths` stands for the typed route paths in `app/navigation/navigation.ts`; match their real names.
|
||
|
||
`constants.ts`
|
||
|
||
```ts
|
||
import type { ItemAvailability } from '@project/libs/json-ld/server';
|
||
import type { ProductStock } from '../../features/catalog';
|
||
|
||
// The catalog API sends toman. ISO 4217 has no toman, so prices go out in rials: toman × 10.
|
||
// A redenominated rial changes only these two.
|
||
export const PRICE_CURRENCY = 'IRR';
|
||
export const RIALS_PER_TOMAN = 10;
|
||
|
||
export const STOCK_AVAILABILITY: Record<ProductStock, ItemAvailability> = {
|
||
'in-stock': 'InStock',
|
||
'low-stock': 'LimitedAvailability',
|
||
'out-of-stock': 'OutOfStock',
|
||
'coming-soon': 'PreOrder',
|
||
discontinued: 'Discontinued',
|
||
};
|
||
```
|
||
|
||
`product-json-ld.ts`. The breadcrumb is the trail the page shows, from the same payload.
|
||
|
||
```ts
|
||
import { buildBreadcrumbList, buildGraph, buildProduct } from '@project/libs/json-ld/server';
|
||
import type { JsonLdGraph } from '@project/libs/json-ld/server';
|
||
import type { ProductPayload } from '../../features/catalog';
|
||
import { paths } from '../navigation';
|
||
import { PRICE_CURRENCY, RIALS_PER_TOMAN, STOCK_AVAILABILITY } from './constants';
|
||
|
||
export function buildProductPageJsonLd(product: ProductPayload): JsonLdGraph | null {
|
||
const url = paths.product(product.id);
|
||
const { price } = product;
|
||
return buildGraph(
|
||
buildProduct({
|
||
url,
|
||
name: product.name,
|
||
image: product.images.map((image) => image.url),
|
||
description: product.summary,
|
||
sku: product.sku,
|
||
gtin: product.barcode,
|
||
brand: product.brand?.name,
|
||
offer: price && {
|
||
price: price.selling * RIALS_PER_TOMAN,
|
||
listPrice: price.beforeDiscount && price.beforeDiscount * RIALS_PER_TOMAN,
|
||
saleEnds: price.discountEndsAt, // the countdown's endsAt too, so the markup and the page end together
|
||
priceCurrency: PRICE_CURRENCY,
|
||
availability: STOCK_AVAILABILITY[product.stock],
|
||
},
|
||
rating: product.rating && { value: product.rating.average, count: product.rating.count },
|
||
}),
|
||
buildBreadcrumbList(product.breadcrumb.map((crumb) => ({ name: crumb.name, url: crumb.path }))),
|
||
);
|
||
}
|
||
```
|
||
|
||
`server.ts`
|
||
|
||
```ts
|
||
import 'server-only';
|
||
|
||
export { buildProductPageJsonLd } from './product-json-ld';
|
||
```
|
||
|
||
`apps/<app>/src/app/(shop)/product/[id]/page.tsx` renders the graph in its page entry, before the template, for an `ok` read only, as [page-example.md](page-example.md) shows: `<JsonLd data={buildProductPageJsonLd(product.data)} />`.
|
||
|
||
## Testing and monitoring
|
||
|
||
- Unit tests: the acceptance checklist below for the lib. For each builder in the platform's `app/json-ld/`, a fixture payload and the exact graph it expects, plus the payloads without a price, a rating, or images, and with HTML or `</script>` in a name.
|
||
- Before a new or changed page type ships: run a rendered page from staging through the Rich Results Test in URL mode, and fix every error and the warnings the data allows. The Rich Results Test doesn't cover site names or `noindex` pages; check the home page's `WebSite` and `OnlineStore` with the Schema Markup Validator (validator.schema.org) and URL Inspection.
|
||
- After each release, with the web vitals: Search Console's Merchant listings and Product snippets reports (under Shopping), and its Breadcrumbs, Review snippets, and Unparsable structured data reports. A rise in invalid items means a broken builder or bad data; a drop in valid items means a page stopped rendering its markup. The Manual actions report must stay empty.
|
||
- Google documents no merchant listings for Iran, and Merchant Center serves neither Iran nor Persian, so an Iran-facing shop counts on product snippets (rating, price, availability) and treats merchant listings as a bonus. The markup is the same either way.
|
||
|
||
## Acceptance checklist
|
||
|
||
For building or changing the lib:
|
||
|
||
```
|
||
[ ] Each builder returns the expected node for a full input, with enumeration members as https://schema.org/<Member>
|
||
[ ] buildProduct returns null without a name, an image, or one of a valid offer, rating, and review; buildProductGroup without a name or a valid variant; buildBreadcrumbList for fewer than two items
|
||
[ ] An offer whose price is 0, negative, or NaN is dropped; a list price at or below the price adds no StrikethroughPrice
|
||
[ ] A rating with count 0 or a value outside its scale, and a review without an author, with a 100-character author name, or with a rating outside its scale, are dropped
|
||
[ ] Paths resolve against siteUrl; absolute URLs keep their origin; javascript:, data:, and unparsable URLs are dropped; non-ASCII paths come out percent-encoded
|
||
[ ] configureJsonLd keeps only the origin and throws on an invalid URL; a builder called before it throws the clear error
|
||
[ ] buildGraph drops null nodes, undefined, null, NaN, blank strings, empty arrays, and objects left with only @type; it keeps 0 and false; it returns null when no node is left
|
||
[ ] serializeJsonLd output has no <, >, &, U+2028, or U+2029 character, and JSON.parse of it equals the graph, also for a name containing "</script><!--"
|
||
[ ] Descriptions are cut at JSON_LD_LIMITS.descriptionLength characters and images at JSON_LD_LIMITS.images; review bodies are never cut
|
||
[ ] No input type lets a rating or a review reach an OnlineStore or a Store
|
||
[ ] Importing @project/libs/json-ld/server from a client component fails the build
|
||
[ ] The Rich Results Test finds no error on a rendered product page, a product-group page, and a listing page's breadcrumb; the Schema Markup Validator finds none on the home page
|
||
```
|