Skip to main content

API reference

The package has five entries. The core and /schema have no dependency and run in Node and in a browser. /react and /expo-router need React Native. /node runs in Node only.

@rootnative/seo — core (no dependency)​

import { defineSite, toHeadTags, toMetadata, pageLang, clipDescription, isoDuration, serializeJsonLd, resolveUrl } from '@rootnative/seo'
import type { PageMeta, PageMetadata, PageAlternate, SiteConfig, Site, HeadTag, JsonLd, OpenGraphType } from '@rootnative/seo'
  • defineSite(config: SiteConfig): Site — fills the defaults. Throws on an empty name or a relative url. Strips a trailing slash from url.
    • SiteConfig: name, url (absolute origin + base path), locale?, titleTemplate?: (title) => string (default "<title> | <name>", and the bare name when the title equals it), twitterSite? (@handle), descriptionLimit? (default 160).
  • toHeadTags(site, meta: PageMeta): HeadTag[] — tag records, not elements. Any head renderer can write them.
    • PageMeta: title, description?, url? (absolute or relative to the site), image?: string | null, imageSize?: { width, height }, imageAlt?, type?: 'website' | 'article' | 'profile' | 'video.movie' | 'product', locale?, noindex?, alternates?: PageAlternate[], twitterCard?: 'summary' | 'summary_large_image', jsonLd?: JsonLd[].
    • PageAlternate: { lang, url }. lang is a BCP 47 code (en, de-AT) or x-default; url is absolute or relative to the site. List every language version, this page included, in the same order on each version.
    • HeadTag: { tag: 'title', text } | { tag: 'meta', name, content } | { tag: 'meta', property, content } | { tag: 'link', rel, href, hreflang? } | { tag: 'script', type: 'application/ld+json', text }.
    • Rules: the tab title uses the template, og:title doesn't. No url → no canonical link and no og/twitter tags. og:image:width/height only with an image and an imageSize. Twitter card summary_large_image with an image, summary without, unless twitterCard forces one. noindex writes <meta name="robots" content="noindex">. alternates writes one <link rel="alternate" hreflang href> per entry after the canonical link, plus x-default with the URL of the first entry when the list has none, and only with a url. Each other tag is written once.
  • toMetadata(site, meta: PageMeta): PageMetadata — the same head as the Metadata object of an Expo Router generateMetadata export, which the static export reads from Expo SDK 58: export function generateMetadata(_request, params) { return toMetadata(site, metaFor(params)) }. Same rules as toHeadTags; the Expo serializer writes the same tags from it. No JSON-LD, because Metadata has no field for it: PageHead writes it into the body.
    • PageMetadata: title, description?, robots?, alternates?: { canonical, languages? } (languages maps the hreflang code to the URL, x-default included), openGraph?: { type, siteName, title, description?, url, locale?, images? }, twitter?: { card, site?, title, description?, images? }. A subset of the expo-server Metadata type.
  • pageLang(site, meta: PageMeta): string | undefined — the language of the page as the lang of <html>: the alternates entry that points at the page itself, else locale, else the site locale, as a BCP 47 tag (de_DE → de-DE). PageHead and RouteHead set it on <html> while the page is on, when it names another language than the one there; a template of your own sets it the same way.
  • clipDescription(text, limit = 160) — collapses whitespace, clips at a word boundary, adds one ….
  • isoDuration(minutes) — 150 → 'PT2H30M'. Returns null for 0, a negative, or a non-finite number.
  • serializeJsonLd(value) — JSON.stringify with every < as \\u003c, so </script> in a title can't end the tag.
  • resolveUrl(site, pathOrUrl) — joins a path under the site; an absolute URL passes through.
  • headTagsHtml(tags) — the tags as HTML, one per line, escaped, for a static template such as the index.html of a Vite build: template.replace('</head>', headTagsHtml(toHeadTags(site, meta)) + '</head>').

@rootnative/seo/schema — JSON-LD builders (no dependency)​

Each returns a JsonLd with @context: 'https://schema.org' and @type set. Every empty field (undefined, null, "", [], {}) is removed at every depth.

  • webSite({ name, url, searchUrlTemplate? }) — adds a SearchAction with query-input: 'required name=search_term_string' when the template is set.
  • breadcrumbList(trail: { name, url }[]) — ListItems with position from 1.
  • organization({ name, url, logo?, sameAs? })
  • article({ headline, url, image?, description?, datePublished?, dateModified?, author? }) — author is a string or { name, url? }, written as a Person. Sets mainEntityOfPage to url.
  • product({ name, url, image?, description?, brand?, sku?, offers?, aggregateRating? }) — brand becomes Brand; offers: { price, priceCurrency, availability?, url? } becomes Offer with availability as https://schema.org/<name>.
  • movie({ name, url, image?, description?, datePublished?, genre?, durationMinutes?, actors?, director?, rating? }) — duration through isoDuration; actors and director as Person.
  • person({ name, url, image?, description?, birthDate?, deathDate?, birthPlace?, jobTitle?, sameAs? }) — birthPlace as Place.
  • event({ name, url, startDate, endDate?, location?, image?, description? }) — location is a string or { name, address? }, as Place.
  • faqPage(questions: { question, answer }[]) — Question + Answer under mainEntity.
  • RatingInput: { ratingValue, ratingCount?, reviewCount?, bestRating? (5), worstRating? (1) }. A rating with no count is left out.

@rootnative/seo/react — peers: react >=19.3.0 <20.0.0, react-native >=0.88.0 <0.89.0​

  • <SeoProvider site={site}> — gives every PageHead and RouteHead below it the site, and tracks which route a PageHead claims.
  • useSite(site?) — the site for the tree. A site argument wins. Throws with no provider and no argument.
  • <Heading level={1..6} as={Component}> — renders the given text component (default RN Text) with accessibilityRole="header" and aria-level. On the web react-native-web writes <h1>..<h6>. Generic: <Heading<TypographyProps> level={2} as={Typography} variant="titleMedium">. The wrapped component's own as, role, accessibilityRole and aria-level props are omitted.
  • imageLabel(kind, subject?) — imageLabel('Poster', 'Dune') → 'Dune poster'. Set the result as both alt and accessibilityLabel on expo-image (its web alt comes from accessibilityLabel).
  • useBrowserThemeColor(color: string | undefined) — sets the browser toolbar colour after hydration, so it follows the mode the user picks in the app and not only the system scheme. Call it once near the root, inside the theme provider, with the background of the theme that renders. It sets the content of each theme-color tag in the head (the { light, dark } pair of shellTags included) and puts the old values back on unmount; with no tag it adds one. undefined changes nothing. Native and a server do nothing. Keep the static tags of shellTags: they give the first paint and a page with no JavaScript their colour.

@rootnative/seo/expo-router — optional peer: expo-router >=57.0.0​

  • <PageHead {...meta} site?> — PageMeta as props, plus an optional site that wins over the provider. Writes the head tags through expo-router/head, and the JSON-LD as <script type="application/ld+json"> in the page body while the screen is focused. After hydration it takes out each head tag in a slot it writes that react-helmet-async didn't write (no data-rh): the generateMetadata tags of an SDK 58 static page, or a fallback in app/+html.tsx. It doesn't put them back. On native it renders null and reads no site, so a native tree or test needs no SeoProvider. On the web a missing site throws, and the static export fails. From Expo SDK 58 the static export writes none of its head tags: export generateMetadata with toMetadata too.
  • <RouteHead defaults={(pathname) => PageMeta | undefined} site?> — for the root layout, after the navigator. Writes the head of the current route when no focused screen on it renders a PageHead; a PageHead wins the whole page, not one tag at a time. undefined writes nothing. Native renders null. Put it after the navigator: the screen renders first and claims the route, and the static export runs no effect. Before the navigator, the export holds both heads, and the component warns in development. From Expo SDK 58 it writes no head tag into a static page, and a layout can't export generateMetadata: a route that needs a static head exports its own.
  • renderHeadTag(tag, index) — one HeadTag as the element expo-router/head expects. A JSON-LD script is written as a string child, not dangerouslySetInnerHTML (react-helmet-async drops the latter).
  • shellTags(options): ReactElement[] — for app/+html.tsx: charset, viewport (default width=device-width, initial-scale=1, shrink-to-fit=no), themeColor, favicon, appleTouchIcon, manifest, preconnect: { href, crossOrigin? }[]. themeColor is a string or { light, dark }; the object form writes one theme-color tag per prefers-color-scheme, which follows the system scheme, not a mode picked in the app; useBrowserThemeColor from /react follows that mode. favicon takes an .ico, .png or .svg URL; with web.favicon in app.json the Expo export adds a link to its own favicon.ico, and Chrome picks that file over an SVG, so remove web.favicon or put a favicon.ico in public/ to show the SVG. basePath (pass process.env.EXPO_BASE_URL) prefixes every relative href. No router dependency: works in a Vite template through renderToStaticMarkup. On SDK 57 Expo Router writes the PageHead tags before the shell, so the charset can land after byte 1024: the host must send Content-Type: text/html; charset=utf-8. On SDK 58 the shell must also render headNodes and bodyNodes from useServerDocumentContext(); put headNodes after shellTags, and the charset stays first.

@rootnative/seo/dom — peers: react, react-native; no router​

  • <PageHead {...meta} site? active?> — the same PageMeta props as the Expo Router PageHead, for an app with no Expo Router: React Navigation on react-native-web, a Vite build, an Electron renderer. Writes the toHeadTags records to document.head in an effect and takes them out on unmount, so the two adapters write the same head. A tag of the same name, property or rel that was there before, from the template or from a screen below, is taken out while this head is on and put back when it goes, and the hreflang links go as one set, so no language of the head below stays: a screen mounted over another wins, and the one below gets its head back. active={false} takes the head out for a screen that stays mounted behind another; a React Navigation screen passes useIsFocused(). Native renders null. An effect never runs on a server, so a static file gets its head from headTagsHtml at build time.

@rootnative/seo/expo-image — optional peer: expo-image >=57.0.0​

  • <Picture source alt width height srcSet? sizes? contentFit? loading? fetchPriority? site? style? testID?> — an image a crawler sees. On the web a plain <img> with src, alt, width, height, loading (default lazy), decoding="async" and object-fit from contentFit (default cover); on native expo-image with alt and accessibilityLabel. srcSet lists more files of the image as { source, width }, with the width in pixels: the web writes srcset and sizes, so the browser picks a file by the shown width and the pixel density before any script runs, and native gives the files to expo-image in place of source, which picks one by the view size and the screen scale. Pass sizes with srcSet, for example '160px'; without it the browser takes 100vw. fetchPriority="high" on the hero image, the one the page is built around: the web writes fetchpriority, so the browser starts that download before layout, and native gives expo-image the value as priority. source is absolute, or a path under the site URL like PageMeta.image: the web gets the path under the host, native the absolute URL, and a relative one needs the site from SeoProvider or the site prop. style is a React Native image style that comes after the width and height box, so a size in style wins; set a side to undefined to let flex or aspectRatio size it. The web lays out the <img> as a react-native-web view, and flattens the style to CSS. alt="" marks a decorative image.

@rootnative/seo/node — Node only, no peer​

  • rootnative-seo <outDir> [--site-url <url>] [--sitemap <url>]... [--no-robots] [--no-lang] — the command for the deploy step, after the export. It runs writeSeoFiles, prints each page it leaves out with the reason and each page that got its own lang, and exits with 1 on an error. --no-lang leaves the lang of <html> as the shell wrote it. --sitemap replaces the sitemap list in robots.txt; repeat it for more than one.
  • rootnative-seo render <outDir> [--params <file>] [--origin <url>] — the first command for a server export on Expo SDK 58, before the others. It runs renderServerExport from the current folder, prints the page count and each route that gets no page with the reason, and exits with 1 on an error. --params is a JSON file in the shape of params.
  • renderServerExport({ outDir, params?, origin?, projectRoot?, timeoutMs? }) — for web.output: 'server' on Expo SDK 58, which writes no page file: the server renders each page at request time. Starts expo serve on outDir (the expo of projectRoot, default the current folder), or uses origin with the base path its routes are under. Requests each route of server/_expo/routes.json and writes the HTML to <outDir>/rendered, where every /node function below reads it. The server export doesn't run generateStaticParams, so a dynamic route gets one page for each entry of params, by its page in routes.json: { '/movies/[id]': [{ id: '42' }] }; a catch-all segment takes a list. A dynamic route with no entry is in skipped with no-params. A not-found route is requested at a path with no match and written as +not-found.html when it answers 404, else skipped with not-404. Removes the pages of an earlier run first. Resolves to { pagesDir, pages: { file, route, status }[], skipped: { page, reason }[] }. Throws with no routes.json, when expo serve doesn't answer in timeoutMs (default 60000), or when a request fails or answers 500 or more.
  • writeSeoFiles({ outDir, siteUrl?, robots?, lang? }) — reads every .html file under outDir and writes sitemap.xml and robots.txt there. A server export, which has server/_expo/routes.json and client/, is read from <outDir>/rendered when renderServerExport wrote it, else from <outDir>/server (Expo SDK 57 and earlier), and the two files go to <outDir>/client, the folder the server sends as files; every /node function below reads the same layout. A page goes in the sitemap with its canonical link, when the link is under the site and the page has no noindex. Left out, with a reason: a special route (a + or _ segment, or a root 404.html), a dynamic route template ([id].html), noindex, no canonical link, a canonical link outside the site, and a second page with the same link. A page with hreflang links gets the same links as xhtml:link entries. siteUrl defaults to the canonical link of index.html. robots: false writes no robots.txt; an object passes options to writeRobots. In a static export it also sets lang on <html> of each page whose own language (its hreflang link to itself, else its og:locale) isn't the language on the element, because Expo Router writes the <html> of the shell on every page; a page in the language of the shell keeps the shell value (en stays on en_US), and a server export isn't changed. lang: false skips the step. Resolves to { siteUrl, sitemap, robots?, urls, skipped: { file, reason }[], langs: { file, lang }[] }. Each sitemap entry holds loc only: Google ignores changefreq and priority, and an export doesn't know lastmod. Throws when no page can go in the sitemap, because an empty sitemap fails with no other signal.
  • readExport(outDir) — { file, route, canonical?, noindex, alternates: { lang, url }[], locale? }[] for every exported HTML file (locale is the og:locale), sorted by path. Use it to build a URL list of your own.
  • rootnative-seo audit <outDir> [--site-url <url>] [--ignore <rule>]... — the gate for CI, after the export and after rootnative-seo <outDir>. It runs auditExport, prints each problem with its file and rule, and exits with 1 when there is one. It writes nothing. --ignore skips one rule; repeat it for more.
  • auditExport({ outDir, siteUrl?, ignore? }) — reads every .html file under outDir and returns { pages, problems: { file, rule, message }[] }. The rules: title (one <title> with text), canonical (an absolute canonical link, or noindex), h1 (exactly one <h1>), main (exactly one <main>), lang (a lang on <html>, and in a static export one that is the language of the page, from its hreflang link to itself or its og:locale), alt (every <img> has an alt attribute), hreflang (on each indexable page with hreflang links: every code is a language code or x-default, not -UK; every link is absolute; one link per code; a link to the page itself; every linked page in the export has a file, no noindex, and the same set; and the xhtml:link entries of the sitemap, when it has them, are the links of the page), and sitemap (sitemap.xml exists, every <loc> is the canonical link of a page, and every page writeSeoFiles would list is in it). siteUrl defaults to the canonical link of index.html; with neither, the second half of the sitemap rule is skipped. An empty problems list is a pass. It throws only when the folder is missing or holds no HTML file.
  • rootnative-seo browse <outDir> [--chrome <path>] [--base-path <path>] [--settle <ms>] — the second gate for CI, after the export. It runs browseExport, prints each problem with its file and kind, and exits with 1 when there is one. It writes nothing. Chrome comes from --chrome, then CHROME_PATH, then the usual names on PATH and the usual install paths.
  • browseExport({ outDir, basePath?, chrome?, settleMs?, timeoutMs? }) — serves outDir and loads every .html file in headless Chrome, driven over its debugging pipe with no package. Returns { pages, problems: { file, route, kind, message }[], chrome }, where kind is exception (uncaught), console (console.error or console.assert), or log (a browser log entry, such as a request that failed). A hydration mismatch is a console.error in development and a reported error in production, so both reach the list. settleMs (default 750) is how long it listens after the load event, so hydration runs. Throws when no Chrome is found, the folder is missing, it holds no HTML file, or the scripts of index.html aren't under the base path. That last message names both paths, so a base-path mismatch is one line, not a failed request for each script on each page.
  • serveExport({ outDir, basePath?, port? }) — serves outDir on 127.0.0.1 as a static host serves an Expo Router export (a server export: a file from client/, then a page from server/, never the route manifest; a dynamic route gets its own file only, where the Expo server sends the template for every slug): /about is about.html or about/index.html, a route with no file gets +not-found.html or 404.html with status 404, and a request outside outDir is refused. basePath defaults to the path of the canonical link of index.html. Resolves to { origin, basePath, urlOf(route), close() }. Use it to run Lighthouse or a browser test on the export.
  • findChrome(path?) — the Chrome or Chromium binary browseExport would use, or undefined.

The three functions below write one file each. Each creates outDir, writes the file and resolves to its path. Each has a pure sibling that returns the text.

  • writeSitemap({ outDir, siteUrl, urls, fileName? }) / sitemapXml({ siteUrl, urls }) — urls: { loc, lastmod?, changefreq?, priority?, alternates? }[]. A relative loc or alternate url is joined under siteUrl. alternates become <xhtml:link rel="alternate" hreflang href> entries, and <urlset> declares the xhtml namespace only then. Every value is XML-escaped. priority is clamped to 0..1.
  • writeRobots({ outDir, sitemapUrl, disallow?, allow?, userAgent?, fileName? }) / robotsTxt(...) — sitemapUrl is one URL or a list. With no disallow the file allows everything. The file carries a comment that says why an overlay route isn't disallowed: a crawler reads noindex only on a page it may fetch.
  • writeManifest({ outDir, name, shortName?, description?, startUrl? ('./'), scope? ('./'), display? ('standalone'), themeColor?, backgroundColor?, lang?, icons?, fileName? }) / manifestJson(...) — relative paths, so it works under a subpath host. The icon type is inferred from the file extension.