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).
└── 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 };
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.
- 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`.
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.
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.
`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
`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).
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.
`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)} />`.
- 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