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 emptynameor a relativeurl. Strips a trailing slash fromurl.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 }.langis a BCP 47 code (en,de-AT) orx-default;urlis 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:titledoesn't. Nourl→ no canonical link and no og/twitter tags.og:image:width/heightonly with an image and animageSize. Twitter cardsummary_large_imagewith an image,summarywithout, unlesstwitterCardforces one.noindexwrites<meta name="robots" content="noindex">.alternateswrites one<link rel="alternate" hreflang href>per entry after the canonical link, plusx-defaultwith the URL of the first entry when the list has none, and only with aurl. Each other tag is written once.
toMetadata(site, meta: PageMeta): PageMetadata— the same head as theMetadataobject of an Expo RoutergenerateMetadataexport, which the static export reads from Expo SDK 58:export function generateMetadata(_request, params) { return toMetadata(site, metaFor(params)) }. Same rules astoHeadTags; the Expo serializer writes the same tags from it. No JSON-LD, becauseMetadatahas no field for it:PageHeadwrites it into the body.PageMetadata:title,description?,robots?,alternates?: { canonical, languages? }(languagesmaps thehreflangcode to the URL,x-defaultincluded),openGraph?: { type, siteName, title, description?, url, locale?, images? },twitter?: { card, site?, title, description?, images? }. A subset of theexpo-serverMetadatatype.
pageLang(site, meta: PageMeta): string | undefined— the language of the page as thelangof<html>: thealternatesentry that points at the page itself, elselocale, else the site locale, as a BCP 47 tag (de_DE→de-DE).PageHeadandRouteHeadset 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'. Returnsnullfor0, a negative, or a non-finite number.serializeJsonLd(value)—JSON.stringifywith 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 theindex.htmlof 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 aSearchActionwithquery-input: 'required name=search_term_string'when the template is set.breadcrumbList(trail: { name, url }[])—ListItems withpositionfrom 1.organization({ name, url, logo?, sameAs? })article({ headline, url, image?, description?, datePublished?, dateModified?, author? })—authoris a string or{ name, url? }, written as aPerson. SetsmainEntityOfPagetourl.product({ name, url, image?, description?, brand?, sku?, offers?, aggregateRating? })—brandbecomesBrand;offers: { price, priceCurrency, availability?, url? }becomesOfferwithavailabilityashttps://schema.org/<name>.movie({ name, url, image?, description?, datePublished?, genre?, durationMinutes?, actors?, director?, rating? })—durationthroughisoDuration;actorsanddirectorasPerson.person({ name, url, image?, description?, birthDate?, deathDate?, birthPlace?, jobTitle?, sameAs? })—birthPlaceasPlace.event({ name, url, startDate, endDate?, location?, image?, description? })—locationis a string or{ name, address? }, asPlace.faqPage(questions: { question, answer }[])—Question+AnswerundermainEntity.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 everyPageHeadandRouteHeadbelow it the site, and tracks which route aPageHeadclaims.useSite(site?)— the site for the tree. Asiteargument wins. Throws with no provider and no argument.<Heading level={1..6} as={Component}>— renders the given text component (default RNText) withaccessibilityRole="header"andaria-level. On the web react-native-web writes<h1>..<h6>. Generic:<Heading<TypographyProps> level={2} as={Typography} variant="titleMedium">. The wrapped component's ownas,role,accessibilityRoleandaria-levelprops are omitted.imageLabel(kind, subject?)—imageLabel('Poster', 'Dune')→'Dune poster'. Set the result as bothaltandaccessibilityLabelonexpo-image(its webaltcomes fromaccessibilityLabel).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 thecontentof eachtheme-colortag in the head (the{ light, dark }pair ofshellTagsincluded) and puts the old values back on unmount; with no tag it adds one.undefinedchanges nothing. Native and a server do nothing. Keep the static tags ofshellTags: 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?>—PageMetaas props, plus an optionalsitethat wins over the provider. Writes the head tags throughexpo-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 (nodata-rh): thegenerateMetadatatags of an SDK 58 static page, or a fallback inapp/+html.tsx. It doesn't put them back. On native it rendersnulland reads no site, so a native tree or test needs noSeoProvider. 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: exportgenerateMetadatawithtoMetadatatoo.<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 aPageHead; aPageHeadwins the whole page, not one tag at a time.undefinedwrites nothing. Native rendersnull. 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 exportgenerateMetadata: a route that needs a static head exports its own.renderHeadTag(tag, index)— oneHeadTagas the elementexpo-router/headexpects. A JSON-LD script is written as a string child, notdangerouslySetInnerHTML(react-helmet-async drops the latter).shellTags(options): ReactElement[]— forapp/+html.tsx: charset, viewport (defaultwidth=device-width, initial-scale=1, shrink-to-fit=no),themeColor,favicon,appleTouchIcon,manifest,preconnect: { href, crossOrigin? }[].themeColoris a string or{ light, dark }; the object form writes onetheme-colortag perprefers-color-scheme, which follows the system scheme, not a mode picked in the app;useBrowserThemeColorfrom/reactfollows that mode.favicontakes an.ico,.pngor.svgURL; withweb.faviconinapp.jsonthe Expo export adds a link to its ownfavicon.ico, and Chrome picks that file over an SVG, so removeweb.faviconor put afavicon.icoinpublic/to show the SVG.basePath(passprocess.env.EXPO_BASE_URL) prefixes every relativehref. No router dependency: works in a Vite template throughrenderToStaticMarkup. On SDK 57 Expo Router writes thePageHeadtags before the shell, so the charset can land after byte 1024: the host must sendContent-Type: text/html; charset=utf-8. On SDK 58 the shell must also renderheadNodesandbodyNodesfromuseServerDocumentContext(); putheadNodesaftershellTags, and the charset stays first.
@rootnative/seo/dom — peers: react, react-native; no router
<PageHead {...meta} site? active?>— the samePageMetaprops as the Expo RouterPageHead, for an app with no Expo Router: React Navigation on react-native-web, a Vite build, an Electron renderer. Writes thetoHeadTagsrecords todocument.headin an effect and takes them out on unmount, so the two adapters write the same head. A tag of the same name, property orrelthat 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 thehreflanglinks 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 passesuseIsFocused(). Native rendersnull. An effect never runs on a server, so a static file gets its head fromheadTagsHtmlat 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>withsrc,alt,width,height,loading(defaultlazy),decoding="async"andobject-fitfromcontentFit(defaultcover); on nativeexpo-imagewithaltandaccessibilityLabel.srcSetlists more files of the image as{ source, width }, with the width in pixels: the web writessrcsetandsizes, so the browser picks a file by the shown width and the pixel density before any script runs, and native gives the files toexpo-imagein place ofsource, which picks one by the view size and the screen scale. PasssizeswithsrcSet, for example'160px'; without it the browser takes100vw.fetchPriority="high"on the hero image, the one the page is built around: the web writesfetchpriority, so the browser starts that download before layout, and native givesexpo-imagethe value aspriority.sourceis absolute, or a path under the site URL likePageMeta.image: the web gets the path under the host, native the absolute URL, and a relative one needs the site fromSeoProvideror thesiteprop.styleis a React Native image style that comes after thewidthandheightbox, so a size instylewins; set a side toundefinedto letflexoraspectRatiosize 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 runswriteSeoFiles, prints each page it leaves out with the reason and each page that got its ownlang, and exits with 1 on an error.--no-langleaves thelangof<html>as the shell wrote it.--sitemapreplaces the sitemap list inrobots.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 runsrenderServerExportfrom the current folder, prints the page count and each route that gets no page with the reason, and exits with 1 on an error.--paramsis a JSON file in the shape ofparams.renderServerExport({ outDir, params?, origin?, projectRoot?, timeoutMs? })— forweb.output: 'server'on Expo SDK 58, which writes no page file: the server renders each page at request time. Startsexpo serveonoutDir(theexpoofprojectRoot, default the current folder), or usesoriginwith the base path its routes are under. Requests each route ofserver/_expo/routes.jsonand writes the HTML to<outDir>/rendered, where every/nodefunction below reads it. The server export doesn't rungenerateStaticParams, so a dynamic route gets one page for each entry ofparams, by itspageinroutes.json:{ '/movies/[id]': [{ id: '42' }] }; a catch-all segment takes a list. A dynamic route with no entry is inskippedwithno-params. A not-found route is requested at a path with no match and written as+not-found.htmlwhen it answers 404, else skipped withnot-404. Removes the pages of an earlier run first. Resolves to{ pagesDir, pages: { file, route, status }[], skipped: { page, reason }[] }. Throws with noroutes.json, whenexpo servedoesn't answer intimeoutMs(default 60000), or when a request fails or answers 500 or more.writeSeoFiles({ outDir, siteUrl?, robots?, lang? })— reads every.htmlfile underoutDirand writessitemap.xmlandrobots.txtthere. A server export, which hasserver/_expo/routes.jsonandclient/, is read from<outDir>/renderedwhenrenderServerExportwrote 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/nodefunction 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 nonoindex. Left out, with areason: a special route (a+or_segment, or a root404.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 withhreflanglinks gets the same links asxhtml:linkentries.siteUrldefaults to the canonical link ofindex.html.robots: falsewrites norobots.txt; an object passes options towriteRobots. In a static export it also setslangon<html>of each page whose own language (itshreflanglink to itself, else itsog: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 (enstays onen_US), and a server export isn't changed.lang: falseskips the step. Resolves to{ siteUrl, sitemap, robots?, urls, skipped: { file, reason }[], langs: { file, lang }[] }. Each sitemap entry holdsloconly: Google ignoreschangefreqandpriority, and an export doesn't knowlastmod. 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 (localeis theog: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 afterrootnative-seo <outDir>. It runsauditExport, prints each problem with its file and rule, and exits with 1 when there is one. It writes nothing.--ignoreskips one rule; repeat it for more.auditExport({ outDir, siteUrl?, ignore? })— reads every.htmlfile underoutDirand returns{ pages, problems: { file, rule, message }[] }. The rules:title(one<title>with text),canonical(an absolute canonical link, ornoindex),h1(exactly one<h1>),main(exactly one<main>),lang(alangon<html>, and in a static export one that is the language of the page, from itshreflanglink to itself or itsog:locale),alt(every<img>has analtattribute),hreflang(on each indexable page withhreflanglinks: every code is a language code orx-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, nonoindex, and the same set; and thexhtml:linkentries of the sitemap, when it has them, are the links of the page), andsitemap(sitemap.xmlexists, every<loc>is the canonical link of a page, and every pagewriteSeoFileswould list is in it).siteUrldefaults to the canonical link ofindex.html; with neither, the second half of thesitemaprule is skipped. An emptyproblemslist 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 runsbrowseExport, prints each problem with its file and kind, and exits with 1 when there is one. It writes nothing. Chrome comes from--chrome, thenCHROME_PATH, then the usual names onPATHand the usual install paths.browseExport({ outDir, basePath?, chrome?, settleMs?, timeoutMs? })— servesoutDirand loads every.htmlfile in headless Chrome, driven over its debugging pipe with no package. Returns{ pages, problems: { file, route, kind, message }[], chrome }, wherekindisexception(uncaught),console(console.errororconsole.assert), orlog(a browser log entry, such as a request that failed). A hydration mismatch is aconsole.errorin 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 ofindex.htmlaren'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? })— servesoutDiron127.0.0.1as a static host serves an Expo Router export (a server export: a file fromclient/, then a page fromserver/, never the route manifest; a dynamic route gets its own file only, where the Expo server sends the template for every slug):/aboutisabout.htmlorabout/index.html, a route with no file gets+not-found.htmlor404.htmlwith status 404, and a request outsideoutDiris refused.basePathdefaults to the path of the canonical link ofindex.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 binarybrowseExportwould use, orundefined.
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 relativelocor alternateurlis joined undersiteUrl.alternatesbecome<xhtml:link rel="alternate" hreflang href>entries, and<urlset>declares thexhtmlnamespace only then. Every value is XML-escaped.priorityis clamped to 0..1.writeRobots({ outDir, sitemapUrl, disallow?, allow?, userAgent?, fileName? })/robotsTxt(...)—sitemapUrlis one URL or a list. With nodisallowthe file allows everything. The file carries a comment that says why an overlay route isn't disallowed: a crawler readsnoindexonly 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 icontypeis inferred from the file extension.