The checklist
Follow the steps in this order. Each step names the function that does it. The first two steps have no function, because they are router settings.
Install
- yarn
- npm
- pnpm
yarn add @rootnative/seo
npm install @rootnative/seo
pnpm add @rootnative/seo
The core entry has no dependency. The /react and /expo-router entries
need react and react-native, and /expo-router needs expo-router. The
/node entry runs in Node only.
1. Static output
Set web.output to static in app.json, and turn the developer sitemap
route off. Expo Router exports _sitemap.html otherwise, and a crawler
indexes it.
{
"expo": {
"web": { "output": "static" },
"extra": { "router": { "sitemap": false } }
}
}
A dynamic route needs generateStaticParams, or the export writes the
route template only. Return one params object per page, from the list the
app already has:
import { PageHead } from '@rootnative/seo/expo-router'
import { useLocalSearchParams } from 'expo-router'
import { findShowcase, showcaseEntries } from '../../src/showcase'
export function generateStaticParams() {
return showcaseEntries.map(({ slug }) => ({ slug }))
}
export default function ShowcaseScreen() {
const { slug } = useLocalSearchParams<{ slug: string }>()
const entry = findShowcase(slug)
if (!entry) return <PageHead title="Not found" noindex />
return (
<PageHead
title={entry.title}
description={entry.description}
url={`/showcase/${entry.slug}`}
/>
)
}
The export writes one file per entry and the template too, [slug].html,
rendered with no matching entry. Answer that case with noindex and no
url, as above: the template is then not a page a crawler indexes, and
rootnative-seo keeps it out of the sitemap. The audit can't tell the
template from a real page, so the example's check script asserts the
noindex on it by name.
The static output renders your app/+html.tsx. The single-page output used
Expo's own template, so a custom shell that worked before may lack
ScrollViewStyleReset from expo-router/html. Without it #root has no
height, a Stack screen that fills its parent fills nothing, and the page
shows the top bar over an empty area while the DOM holds every node. Keep
the reset in the shell, as the example in step 7 does.
Server output
web.output: 'server' adds a server for API routes. Up to Expo SDK 57 it
renders the same HTML at export time. From SDK 58 the server renders each
page at request time, and the export holds no page file. Every step in this
checklist is the same. Four things change:
-
The export writes the files the server sends as they are to
dist/client. On SDK 58, runrootnative-seo render distfirst: it startsexpo serve, requests each route ofdist/server/_expo/routes.json, and writes the HTML todist/rendered. On SDK 57 the pages are indist/serveralready. Then passdisttorootnative-seo, as for a static export: it reads the pages and writessitemap.xmlandrobots.txtintoclient/.auditandbrowseread the same layout. -
The server export doesn't run
generateStaticParams, sorenderdoes not know the entries of a dynamic route. Give them in a JSON file, by the route asroutes.jsonnames it. A dynamic route with no entry gets no page, andrendernames it.rootnative-seo render dist --params params.jsonparams.json{ "/movies/[id]": [{ "id": "42" }, { "id": "43" }] } -
The server sends the status itself. An unknown path gets
+not-found.htmlwith a 404, on any host. A dynamic route is the other way: the server sends the route template with a 200 for every slug, also for a slug that has no page. So thenoindexanswer for an unknown entry, as above, is the only signal a crawler gets there. -
The server matches each route from the root of its origin and ignores
experiments.baseUrl, which moves only the URLs of the files. Host a server output at the root of its origin, or remove the base path before the request reaches the server.
Check the status codes with npx expo serve before you deploy.
2. Links as Link
Use Link from expo-router for every navigation. It renders an <a href>
on the web. A Pressable with router.push renders a <div>, and a crawler
doesn't follow it. An external URL has the same trap: a Button with
Linking.openURL renders a <button>.
To make a component a link, put it inside <Link asChild>:
import { Button } from '@rootnative/components'
import { Link } from 'expo-router'
<Link href="https://github.com/rootnative" asChild>
<Button hrefAttrs={{ target: '_blank', rel: 'noopener' }}>GitHub</Button>
</Link>
On the web, Link opens an external URL in the same tab. hrefAttrs opens it
in a new tab. <Link target="_blank"> doesn't work under asChild. See
A button as a link.
3. The head on every page
Define the site once, give it to SeoProvider at the root, and render a
PageHead on each screen.
import { defineSite } from '@rootnative/seo'
export const site = defineSite({
name: 'Trek',
url: 'https://example.com/app',
locale: 'en_US',
twitterSite: '@trek',
})
import { SeoProvider } from '@rootnative/seo/react'
import { Stack } from 'expo-router'
import { site } from '../src/site'
export default function RootLayout() {
return (
<SeoProvider site={site}>
<Stack />
</SeoProvider>
)
}
import { PageHead } from '@rootnative/seo/expo-router'
import { movie } from '@rootnative/seo/schema'
export default function MovieScreen() {
const data = useMovie()
return (
<>
<PageHead
title={data.title}
description={data.overview}
url={`/movies/${data.id}`}
image={data.posterUrl}
imageSize={{ width: 1200, height: 630 }}
imageAlt={`${data.title} poster`}
type="video.movie"
jsonLd={[
movie({
name: data.title,
url: `https://example.com/app/movies/${data.id}`,
image: data.posterUrl,
durationMinutes: data.runtime,
}),
]}
/>
{/* the screen */}
</>
)
}
The rules the head follows:
- The tab title uses the site template. The default is
Title | Site. The Open Graph title does not, because the card shows the site name on its own line. - A page with no
urlgets no canonical link and no share card. That is the correct result for anoindexoverlay. - The description is clipped to 160 characters at a word boundary.
- The Twitter card is
summary_large_imagewith an image andsummarywithout one. PasstwitterCardto force one.
A page outside the provider, such as +not-found, passes site as a prop.
The prop wins over the provider.
Expo SDK 58: generateMetadata
From Expo SDK 58, the static export renders each page with the streaming
renderer. That renderer writes the head from the generateMetadata export of
the route. It writes no tag from PageHead. Export generateMetadata from
each route, and return toMetadata with the same meta that the screen gives
to PageHead:
import { toMetadata, type PageMeta } from '@rootnative/seo'
import { PageHead } from '@rootnative/seo/expo-router'
import { useLocalSearchParams } from 'expo-router'
import { findMovie } from '../../src/movies'
import { site } from '../../src/site'
function movieMeta(id: string): PageMeta {
const movie = findMovie(id)
if (!movie) return { title: 'Movie not found', noindex: true }
return {
title: movie.title,
description: movie.overview,
url: `/movies/${movie.id}`,
}
}
export function generateMetadata(_request: unknown, params: { id: string }) {
return toMetadata(site, movieMeta(params.id))
}
export default function MovieScreen() {
const { id } = useLocalSearchParams<{ id: string }>()
return <PageHead {...movieMeta(id)} />
}
toMetadatafollows the same rules asPageHead. The Expo serializer writes the same tags from its result.- In a static render the request is
undefined. The function gets the route params only, so it finds the data from the params. Expo removes the function from the client bundle. - Keep the
PageHead. It writes the JSON-LD into the page body, and it writes the head after a client navigation. After hydration it removes every server tag in a page slot (the description, the robots tag, the canonical link, thehreflanglinks,og:*andtwitter:*), so the head doesn't hold two sets. It removes the slots it leaves empty too: on a route the export did not write, anoindexhead takes the canonical link and the share card of the shell page out. The charset, the viewport, the icons and the manifest stay. - On SDK 57 the static export ignores
generateMetadataand writes thePageHeadtags. You can add the export before you move to SDK 58. - A static export doesn't call the
generateMetadataof+not-found: Expo skips internal routes, so that page has no head. Write the head into the file after the export, withheadTagsHtml(toHeadTags(site, meta))before</head>. A server export renders that head at request time. - A custom
app/+html.tsxmust render the nodes ofuseServerDocumentContext(). Without them the page has no metadata, no CSS and no JavaScript. See step 7.
The route a screen forgets
A screen with no PageHead is a page with no title. RouteHead closes
that gap: it takes a function from the pathname to a PageMeta and writes
that head for the current route, when no screen on the route renders a
PageHead. A PageHead wins the whole page, not one tag at a time, so a
noindex screen with no url gets no canonical link from the defaults.
import { RouteHead } from '@rootnative/seo/expo-router'
import { SeoProvider } from '@rootnative/seo/react'
import { Stack } from 'expo-router'
import { site } from '../src/site'
import { findPage } from '../src/pages'
function routeDefaults(pathname: string) {
const page = findPage(pathname)
if (!page) return undefined
return { title: page.title, description: page.summary, url: pathname }
}
export default function RootLayout() {
return (
<SeoProvider site={site}>
<Stack />
<RouteHead defaults={routeDefaults} />
</SeoProvider>
)
}
Put RouteHead after the navigator. The screen then renders first and
claims the route, and RouteHead reads the claim in the same render pass.
That order matters on the static export, which runs no effect. Before the
navigator, the export holds both heads, and the component warns in
development. Return undefined for a route that must write nothing.
On Expo SDK 58, RouteHead writes no tag into the static page. Expo Router
reads generateMetadata from the route file only, not from a layout. So a
route that RouteHead covers, and that a crawler must index, exports its own
generateMetadata:
import { toMetadata } from '@rootnative/seo'
import { site } from '../src/site'
export function generateMetadata() {
return toMetadata(site, { title: 'About', url: '/about' })
}
An app without Expo Router
React Navigation on react-native-web, a Vite build, or an Electron renderer
has no expo-router/head. PageHead from @rootnative/seo/dom takes the
same props and writes the same tags to document.head in an effect, and
takes them out on unmount. A screen mounted over another wins, and the one
below gets its head back when the top one unmounts. A screen that stays
mounted behind another passes active={false}; with React Navigation that
is useIsFocused().
import { PageHead } from '@rootnative/seo/dom'
import { useIsFocused } from '@react-navigation/native'
export function MovieScreen() {
const focused = useIsFocused()
return <PageHead title={data.title} url={`/movies/${data.id}`} active={focused} />
}
An effect runs after the first paint and never on a server, so such an app
has a static head only at build time. Render it into the template with
headTagsHtml from the core:
import { defineSite, headTagsHtml, toHeadTags } from '@rootnative/seo'
const head = headTagsHtml(toHeadTags(site, { title: 'Trek', url: '/' }))
const html = template.replace('</head>', `${head}</head>`)
Per-route noindex
An overlay route, a filter sheet, or a per-device screen is a page the
crawler can fetch but must not index. Give it noindex and no url. Do not
add it to robots.txt: a crawler reads the noindex tag only on a page it
may fetch.
<PageHead title="Filters" noindex />
A page in more than one language
A page that exists in more than one language names each version with an
hreflang link, so that a search engine shows the reader the version in
the reader's language. Write the list of versions once, and pass the same
list to the PageHead of each version:
export const aboutVersions = [
{ lang: 'en', url: '/about' },
{ lang: 'de', url: '/de/about' },
]
<PageHead
title="Über uns"
url="/de/about"
locale="de_DE"
alternates={aboutVersions}
/>
PageHead writes one <link rel="alternate" hreflang> for each entry, with
the URL under the site, and one more for x-default with the URL of the
first entry. To point x-default at a different page, such as a page where
the reader selects a language, put an x-default entry in the list. A page
with no url gets no hreflang link.
A search engine ignores a set that breaks one of these rules:
- Each version lists every version, and itself too.
- Each version lists the same set. A link that the other version does not return has no effect.
langis a language code, such asde, with an optional region, such asde-AT. The region code of the United Kingdom isGB, notUK.- Each version is a page that a crawler can index: it has a canonical link
and no
noindex.
rootnative-seo dist writes the same links into the sitemap as
xhtml:link entries, and sets lang on <html> of each version from its
hreflang link to itself, so the German version says lang="de".
PageHead sets the same lang after hydration. rootnative-seo audit
fails a set that breaks a rule, and a version whose lang is not its
language. A server export keeps the lang of the shell until hydration;
see the page language.
4. Robots and sitemap
Run rootnative-seo in the deploy step, after the export. It reads the
canonical link of every exported page and writes sitemap.xml and
robots.txt into the export folder. It also sets lang on <html> of each
page in another language than the shell; see
a page in more than one language.
{
"scripts": {
"export:web": "expo export --platform web",
"seo": "rootnative-seo dist"
}
}
A page goes in the sitemap with its canonical link, when that link is under
the site and the page has no noindex. So the sitemap lists the address each
page declares, and a route the export did not write is never listed. The
command prints each page it leaves out, with the reason:
[rootnative-seo] dist/sitemap.xml: 2 pages under https://example.com/app
[rootnative-seo] dist/robots.txt
[rootnative-seo] 3 pages stay out of the sitemap:
+not-found.html: a special route (+, _, or the host 404 page)
items/[id].html: a dynamic route template
search.html: noindex
The site URL comes from the canonical link of index.html. Pass
--site-url when the home page has none. The command fails when no page can
go in the sitemap, because an empty sitemap on a live host fails with no
other signal.
A crawler reads robots.txt at the origin root only. A site on a subpath
host writes the file from the root deploy, and lists every sitemap of the
origin in it: repeat --sitemap <url> once for each. Pass --no-robots when
another deploy owns the file.
writeSeoFiles from @rootnative/seo/node does the same in a script, and
readExport returns the pages for a URL list of your own.
Each sitemap entry holds <loc> only. Google ignores <changefreq> and
<priority>
(Google Search Central),
and an export doesn't know when a page last changed, so the command writes
no <lastmod> either. A deploy script that set these values can drop them
when it moves to rootnative-seo.
5. Headings and alt
A Text renders a <div>. In a Root Native UI app, pass level to
Typography: it renders <h1> to <h6> on the web and announces a header
on native. A display or headline variant with no level is a plain element
on the web, so decorative display text needs nothing.
import { Typography } from '@rootnative/components'
<Typography variant="titleMedium" level={2}>Cast</Typography>
Heading from @rootnative/seo/react does the same for an app without
@rootnative/components. Pass your own text component through as to keep
its type scale.
import { Heading } from '@rootnative/seo/react'
<Heading level={2}>Cast</Heading>
One <h1> per page. The AppBar title is level 1 by default, so put your
own headings at level 2 and below, or pass titleLevel={2} to the bar when a
heading above it is the page heading.
Landmarks and the page language
A crawler and a screen reader both read the landmarks: <main> for the
page content, <nav> for the navigation, <header> for the page bar, and
<footer> for the end matter. react-native-web renders them from role:
main, navigation, banner, and contentinfo. The package ships nothing
for this; the rule is one <main> per page, around the screen, with the
bar and the navigation outside it. Put it in the root layout once, around
the navigator:
<View role="main" style={{ flex: 1 }}>
<Stack />
</View>
In a Root Native UI app, AppBar is the banner, and NavigationBar,
NavigationRail, and the standard NavigationDrawer are navigation, on
their own. The standard SideSheet is complementary, an <aside>. A bar inside <main>, as on a demo page, is a plain header, not
a landmark. Pass role to change any of them.
Set the page language on <html> in app/+html.tsx: <html lang="en">.
A crawler reads it, and a screen reader picks its voice from it. A page in
another language gets its own lang from rootnative-seo dist and from
PageHead; see a page in more than one
language. rootnative-seo audit fails
a page with no <main>, more than one, no lang, or a lang that is not
the language of the page.
For an image a crawler must see, render Picture from
@rootnative/seo/expo-image. On the web it is a plain <img> with alt,
width and height in the export; on native it is expo-image. The
source is absolute or a path under the site URL, like image in
PageHead, and imageLabel builds the text:
import { Picture } from '@rootnative/seo/expo-image'
import { imageLabel } from '@rootnative/seo/react'
const label = imageLabel('Poster', movie.title) // 'Dune poster'
<Picture source={`/posters/${movie.id}.jpg`} alt={label} width={300} height={450} />
The export holds one <img>, and the server doesn't know the pixel density
of the screen or the width of the window. When the image server has more than
one size of the file, list them in srcSet, with the width of each file in
pixels, and give the shown width in sizes. The browser then picks the file
before any script runs. Without sizes the browser takes the full window
width, and picks a file too large for a small image. On native, expo-image
gets the same files and picks one by the view size and the screen scale:
<Picture
source={`/posters/w342/${movie.id}.jpg`}
srcSet={[
{ source: `/posters/w185/${movie.id}.jpg`, width: 185 },
{ source: `/posters/w342/${movie.id}.jpg`, width: 342 },
{ source: `/posters/w500/${movie.id}.jpg`, width: 500 },
]}
sizes="160px"
alt={label}
width={342}
height={513}
/>
Give the hero image, the one the page is built around, loading="eager" and
fetchPriority="high". The browser gives an image a low priority until it
has laid out the page, and that wait is part of the Largest Contentful Paint.
A backdrop at the top of a detail page is the usual case.
An image that stays on expo-image, for its cache or a transition, is not
in the export; set og:image and the JSON-LD image for it, and set both
alt and accessibilityLabel on it. The web alt attribute comes from
accessibilityLabel. rootnative-seo audit fails a page with an <img>
that has no alt; pass alt="" for a decorative image.
6. JSON-LD
The builders in @rootnative/seo/schema return an object with @context
and @type set, and leave every empty field out. They never write "",
null, or []. PageHead writes each one as a script and escapes <, so a
</script> in a title can't end the tag.
The scripts go into the page body, next to the screen, not into the head.
From Expo SDK 58 the static export writes no PageHead tag into the head,
and the Metadata of generateMetadata has no field for JSON-LD. A crawler
reads JSON-LD in the body too.
| Builder | Schema type |
|---|---|
webSite | WebSite, with a SearchAction when searchUrlTemplate is set |
breadcrumbList | BreadcrumbList |
organization | Organization |
article | Article |
product | Product, with Offer, Brand, and AggregateRating |
movie | Movie, with the duration as ISO 8601 |
person | Person |
event | Event |
faqPage | FAQPage |
A rating with no votes is left out. A duration of 0 is left out.
7. Bundle and preconnect
Give the HTML shell a preconnect for each origin the first paint needs: the
API, a CDN, a font host. shellTags writes them with the charset, the
viewport, the theme colour, the icons, and the manifest.
import { shellTags } from '@rootnative/seo/expo-router'
import { ScrollViewStyleReset } from 'expo-router/html'
import type { PropsWithChildren } from 'react'
export default function Root({ children }: PropsWithChildren) {
return (
<html lang="en">
<head>
{shellTags({
basePath: process.env.EXPO_BASE_URL,
themeColor: '#4C0519',
appleTouchIcon: '/apple-touch-icon.png',
manifest: '/manifest.webmanifest',
preconnect: [
{ href: 'https://api.example.com', crossOrigin: true },
{ href: 'https://cdn.example.com' },
],
})}
<ScrollViewStyleReset />
</head>
<body>{children}</body>
</html>
)
}
basePath prefixes every relative href, so the same shell works on a
subpath host. shellTags has no router dependency: the same function serves
a Vite index.html template through renderToStaticMarkup.
On SDK 57, Expo Router writes the PageHead tags at the start of <head>,
before the shell. On a page with a title, a description and the Open Graph
tags, the charset is then after byte 1024. The HTML spec requires it in the
first 1024 bytes, so the host must send the charset in the Content-Type
header. See the charset position.
From Expo SDK 58, the server renderer gives the shell the metadata, the CSS
and the JavaScript bundles as React nodes, through useServerDocumentContext.
A custom shell must render them, or the page has no head tags and does not
hydrate:
import { shellTags } from '@rootnative/seo/expo-router'
import {
ScrollViewStyleReset,
useServerDocumentContext,
} from 'expo-router/html'
import type { PropsWithChildren } from 'react'
export default function Root({ children }: PropsWithChildren) {
const { htmlAttributes, headNodes, bodyAttributes, bodyNodes } =
useServerDocumentContext()
return (
<html lang="en" {...htmlAttributes}>
<head>
{shellTags({ themeColor: '#4C0519' })}
<ScrollViewStyleReset />
{headNodes}
</head>
<body {...bodyAttributes}>
{children}
{bodyNodes}
</body>
</html>
)
}
Put headNodes after shellTags. The charset then stays in the first bytes
of the page.
A site with a light and a dark theme gives both colours:
shellTags({ themeColor: { light: '#f8f9ff', dark: '#0e141c' } })
This writes one theme-color tag for each prefers-color-scheme. A browser
uses the first tag whose media matches, so one tag with no media always wins
over a dark one. The tags follow the system scheme, not a mode that the user
picks in the app.
An app with a light, dark and system choice also calls
useBrowserThemeColor from @rootnative/seo/react. Call it in one place,
inside the theme provider, with the background of the theme that renders.
After hydration it sets each theme-color tag to that colour, and it does
nothing on native. With @rootnative/core:
import { useTheme } from '@rootnative/core'
import { useBrowserThemeColor } from '@rootnative/seo/react'
export function BrowserThemeColor() {
useBrowserThemeColor(useTheme().colors.background)
return null
}
Keep the static tags of shellTags. They give the first paint and a page
with no JavaScript their colour.
favicon takes the URL of an .ico, a .png or an .svg file. When
app.json sets web.favicon, the Expo export writes a second icon link, to
a favicon.ico with 16, 32 and 48 px images. Chrome picks that file over an
SVG favicon, in either order. To show the SVG, remove web.favicon from
app.json, or put your own favicon.ico in public/. With either change,
the export writes no second link.
8. The small tags
writeManifest writes a web app manifest with relative paths, so it works
under a subpath host. Pass themeColor to both shellTags and
writeManifest, and the same value to backgroundColor as the page
background. The manifest has one theme colour, so writeManifest takes a
string, also on a site with two themes.
Check the result
Read the export before you deploy. rootnative-seo audit dist reads every
exported page and fails on:
- a page with no
<title>, or an empty one; - a page with no canonical link and no
noindex, or a relative canonical link; - a page with no
<h1>, or more than one; - a page with no
<main>, or more than one, and a page with nolangon<html>, or with alangthat is not the language of the page, from itshreflanglink to itself or itsog:locale(a static export only); - an
<img>with noaltattribute; - an
hreflanglink with a code that is not a language, with a relative URL, or to a page withnoindexor with no file; a version that does not list itself or that lists a different set; and a sitemap whosexhtml:linkentries are not the links of the page; - a
sitemap.xmlentry that no page declares as its canonical link, or a page that must be in the sitemap and is not.
Run it after rootnative-seo dist, so the sitemap exists. It prints each
problem with its file and the rule, and writes nothing. A rule that does not
apply to your site is skipped with --ignore <rule>. From a script, call
auditExport({ outDir }) and read problems.
The audit reads the file. It can't see what happens when the script runs:
a hydration mismatch (React error #418), a component that reads the browser
during the hydrating render, or a bundle that fails to load. A crawler that
runs the script sees a page that renders twice, and Lighthouse counts the
error. rootnative-seo browse dist serves the export and loads every page
in headless Chrome, and fails on an uncaught exception, a console.error,
or a failed request. It needs Chrome or Chromium: CHROME_PATH, or the
usual install paths. The GitHub ubuntu-latest runner has Chrome. Run both
in CI, after the export:
expo export --platform web && rootnative-seo dist && rootnative-seo audit dist && rootnative-seo browse dist
The audit checks the shape of every page, not the content of one. The example app runs the audit and then asserts the title, the canonical link, the headings and the JSON-LD of two pages by value, which is the test that catches a head renderer change in Expo Router.
After the deploy, two checks run on the live host, and only they count.
Lighthouse on the deployed URLs is a gate in the deploy workflow: the
script
takes the URLs and fails below an SEO score of 100. Google Search Console
stays manual: verify the property once and submit <siteUrl>/sitemap.xml.
Both are described under the checks that count.
Then read the limits.