RootSmith Docs

Next.js SDK

Install @rootsmithio/next in a Next.js App Router site so RootSmith pages render on your domain and refresh the moment you publish.

The SDK renders published RootSmith pages in your Next.js app, adds them to your sitemap, and receives a signed refresh when you publish.

To let your coding agent do this for you, open Publishing → Set up SDK and choose Use your agent. It shows how to connect your agent and a prompt with your site filled in. You add the connection secret yourself.

Requirements

  • Next.js 15 or 16 with the App Router, and React 19.
  • A server runtime. For output: "export", use static sites instead.
  • The site deployed at the primary domain saved for the site in RootSmith, over HTTPS.

1. Install the package

npm install @rootsmithio/next

2. Add environment variables

Open Sites → Publishing in RootSmith, choose Next.js with a server under How is your site built?, select Set up SDK, and choose Do it yourself to copy these values. An agent can get the site ID from the get_sdk_setup tool.

.env.local
ROOTSMITH_SITE_ID=00000000-0000-0000-0000-000000000000
ROOTSMITH_CONNECTION_SECRET=
VariableValue
ROOTSMITH_SITE_IDThe site ID from Publishing.
ROOTSMITH_CONNECTION_SECRETThe connection secret from Publishing.

Keep the secret on the server

Only a person can copy the connection secret from RootSmith. Add it to .env.local and to your host's server environment. Never commit it, never prefix it with NEXT_PUBLIC_, and never paste it into a chat with an agent.

Add both variables to your host, such as Vercel, for production.

3. Create the client

lib/rootsmith.ts
import { createRootSmith } from "@rootsmithio/next"

export const rootSmith = createRootSmith({
  siteId: process.env.ROOTSMITH_SITE_ID!,
})

4. Render pages

Add a catch-all route that asks RootSmith for the requested path:

app/[...path]/page.tsx
import "@rootsmithio/next/styles.css"
import { notFound } from "next/navigation"
import { pageMetadata } from "@rootsmithio/next"
import { RootSmithPage } from "@rootsmithio/next/markdown"
import { rootSmith } from "@/lib/rootsmith"

type Props = { params: Promise<{ path: string[] }> }

export async function generateStaticParams() {
  return []
}

async function get(params: Props["params"]) {
  const { path } = await params
  const page = await rootSmith.getPage(`/${path.join("/")}`)
  if (!page) notFound()
  return page
}

export async function generateMetadata({ params }: Props) {
  return pageMetadata(await get(params))
}

export default async function Page({ params }: Props) {
  return <RootSmithPage page={await get(params)} />
}

The empty generateStaticParams renders each page on its first visit, then serves it from the Next.js cache.

Adapt the paths to the project:

  • With a src folder, use src/app/... and src/lib/....
  • Without the @/ import alias, use a relative import.
  • If the app already has a root catch-all route, add one route for each page type's URL prefix instead, such as app/blog/[...path]/page.tsx. Pass the full path to getPage, such as `/blog/${path.join("/")}`.
  • Wrap RootSmithPage in your site's layout or article shell as needed.

Each page includes Article structured data (JSON-LD) with the title, description, dates, and your site as the author and publisher. It shows the publish date, and the update date when the page changed on a later day. Headings get id anchors, and images after the first load lazily.

5. Add the refresh handler

app/api/rootsmith/route.ts
import { createRootSmithHandler } from "@rootsmithio/next"

export const POST = createRootSmithHandler()

RootSmith calls this route to verify the connection and to refresh a page after you publish. It must be public. If your app uses auth middleware, a proxy.ts or middleware.ts matcher, basic auth, or deployment protection, let POST /api/rootsmith through. The handler checks its own signature.

6. List pages in your sitemap

app/sitemap.ts
import type { MetadataRoute } from "next"
import { rootSmith } from "@/lib/rootsmith"

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const pages = await rootSmith.listAllPages()
  return pages.map((page) => ({ url: page.url, lastModified: page.updatedAt }))
}

If the site already has a sitemap, add these entries to it.

7. Build an index page

Published pages live under a page type's URL prefix, such as /blog/, and never at the prefix itself, so your own route owns /blog. Pass the prefix to listAllPages and sort the posts with the newest first:

app/blog/page.tsx
import Link from "next/link"
import { rootSmith } from "@/lib/rootsmith"

export default async function BlogIndex() {
  const posts = await rootSmith.listAllPages({
    prefix: "/blog",
    sort: "newest",
  })
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>
          <Link href={post.path}>{post.title}</Link>
          <p>{post.description}</p>
        </li>
      ))}
    </ul>
  )
}

The index refreshes when you publish, like page reads. Page type prefixes are in Sites → Page types, or in get_site for an agent. To split a long index into numbered pages, see Pagination.

8. Deploy and connect

  1. Deploy the site with both environment variables set.
  2. In Publishing → Set up SDK, enter /api/rootsmith as the Delivery endpoint and select Save and verify.
  3. The status changes to Connected.

An agent does step 2 with update_publishing_settings, then verify_publishing_connection. See Set up with an agent.

Add optional page parts

Pass the links that lead to the page. RootSmithPage adds the page title as the last item and adds matching BreadcrumbList data. Link only to pages that exist, such as your index page.

<RootSmithPage
  page={page}
  breadcrumbs={[
    { name: "Home", href: "/" },
    { name: "Blog", href: "/blog" },
  ]}
/>

Table of contents

TableOfContents lists the page's H2 headings and links to their anchors. It renders nothing when a page has fewer than two. For your own design, pageHeadings(page.markdown) returns the same { id, title } list.

import { RootSmithPage, TableOfContents } from "@rootsmithio/next/markdown"

<TableOfContents page={page} />
<RootSmithPage page={page} />

RelatedPages is a server component. It lists the newest pages under the same URL prefix, without the current page. It shows three under the heading "More articles"; pass limit and title to change them.

import { RelatedPages } from "@rootsmithio/next/markdown"

;<RelatedPages rootSmith={rootSmith} page={page} />

RSS feed

The feed lists the 20 newest pages under a prefix.

app/blog/feed.xml/route.ts
import { createRootSmithFeed } from "@rootsmithio/next"
import { rootSmith } from "@/lib/rootsmith"

export const GET = createRootSmithFeed({
  rootSmith,
  prefix: "/blog",
  title: "Acme blog",
})

On a static export, also add export const dynamic = "force-static". To let readers and crawlers find the feed, add alternates: { types: { "application/rss+xml": "/blog/feed.xml" } } to your index page's metadata.

Your own article layout

If you render MarkdownContent in your own layout instead of RootSmithPage, add <ArticleJsonLd page={page} breadcrumbs={...} /> to keep the structured data.

Large image previews

pageMetadata doesn't set robots, because a page's robots replaces the one in your layout, including a noindex. To let Google show large image previews, set it once in your root layout:

app/layout.tsx
export const metadata = {
  robots: { index: true, follow: true, "max-image-preview": "large" },
}

How refresh and caching work

  • SDK reads use the Next.js data cache with the rootsmith tag for one hour. Each next build reads current content, including in generateStaticParams, even when your host restores .next/cache.
  • When you publish, RootSmith sends a signed refresh. The handler expires the rootsmith tag, so the next request renders the new version.
  • If a refresh is lost, the page corrects itself within an hour.
  • If the refresh fails, RootSmith restores the previous version and tells you.
  • When a page is merged into another, getPage sends a permanent (308) redirect to the page that replaced it.
  • getPage returns null for an unknown path and for paths that can't be content, such as /favicon.ico or a path with a trailing slash.

Customize

  • Styles: @rootsmithio/next/styles.css matches the RootSmith preview. Override its rootsmith-* classes, or leave out the import and style the page yourself.
  • Elements: pass React Markdown components to RootSmithPage to replace elements such as links, headings, or code blocks.
  • Images: images load only from your site's origin by default. Pass imageOrigins={["https://cdn.example.com"]} to allow other hosts.
  • CDN caches: pass a refresh function to purge your own cache. Call revalidateTag(rootSmithTag, { expire: 0 }) in it too, and finish before it returns.
app/api/rootsmith/route.ts
import { revalidateTag } from "next/cache"
import { createRootSmithHandler, rootSmithTag } from "@rootsmithio/next"

export const POST = createRootSmithHandler({
  refresh: async (path) => {
    revalidateTag(rootSmithTag, { expire: 0 })
    await purgeMyCdn(path)
  },
})

Markdown supports headings, lists, links, URL images, quotes, fenced code, tables, and task lists. Raw HTML is skipped, unsafe URL schemes are removed, and no MDX or JavaScript runs.

Reference

@rootsmithio/next

ExportDescription
createRootSmith({ siteId, apiUrl?, fetcher? })Returns the client below. apiUrl defaults to https://api.rootsmith.io.
client.getPage(path)The published page at path, or null. Redirects merged pages with a 308.
client.listPages({ prefix?, sort?, page?, limit? })One page of the list and the total that match. Sorted by path, or newest first with sort: "newest". 25 per page, or limit up to 100. See Pagination.
client.listAllPages({ prefix?, sort? })Every published page that matches.
pageMetadata(page)Next.js Metadata with the title, description, canonical URL, and Open Graph article fields, including the site name.
createRootSmithHandler({ siteId?, secret?, refresh? })The POST route handler. Reads ROOTSMITH_SITE_ID and ROOTSMITH_CONNECTION_SECRET when a request arrives. Answers 503 until both are set.
createRootSmithFeed({ rootSmith, prefix, title, description? })A GET route handler with an RSS feed of the 20 newest pages under prefix.
rootSmithTagThe cache tag, "rootsmith".
PublishedPageThe page type below.

The client throws for other HTTP failures and invalid responses.

@rootsmithio/next/markdown

ExportDescription
RootSmithPage({ page, breadcrumbs?, components?, imageOrigins? })The title, description, dates, and body in an <article> with the version marker and Article structured data. With breadcrumbs, it shows them and adds BreadcrumbList data.
MarkdownContent({ markdown, baseUrl?, imageOrigins?, components? })The body only, with heading anchors. Shows no images without baseUrl or imageOrigins. Doesn't add the version marker or structured data.
ArticleJsonLd({ page, breadcrumbs? })The structured data alone, for your own layout.
TableOfContents({ page, title? })Links to the page's H2 headings. Renders nothing with fewer than two.
pageHeadings(markdown)The H2 headings as { id, title }, with the same ids as the rendered page.
RelatedPages({ rootSmith, page, limit?, title? })A server component that lists the newest other pages under the same prefix.

PublishedPage

interface PublishedPage {
  id: string
  siteId: string
  pageTypeId: string
  revision: number
  title: string
  path: string
  description: string
  markdown: string
  url: string
  siteName: string
  publishedAt: string
  updatedAt: string
}

siteName is the brand name from the Brand Profile, or the site's name when the profile has none. updatedAt is when the published version was saved, and never earlier than publishedAt.

On this page