Serve a site's pages from Next.js
Serve pages written in the site catalog (by an agent or by hand) as the routes of a Next.js app, or as parts of pages you write yourself, with static export. @surfaces-ui/next works out the routes and metadata and draws each page. Next.js does the routing, building and hosting. Every page is rendered to HTML on the server, so its words, headings, links and theme are in the file before any script runs.
Install it beside next (15 or later, App Router), which it takes as a peer dependency:
npm install @surfaces-ui/next @surfaces-ui/spec @surfaces-ui/componentsThe site is a list of pages, each on a route. A segment in brackets ([slug]) takes values the app supplies. Surfaces does not store content: here the essays are a list, but they could come from MDX files, a CMS or a database.
site.ts:
import type { SiteRoutes } from "@surfaces-ui/next";
import { A2UI_VERSION, siteCatalog } from "@surfaces-ui/spec";
/** The essays. In a real app they come from MDX files, a CMS or a database; Surfaces only asks for them. */
export const essays = [
{ slug: "reading-a-chart", title: "Reading a chart", summary: "What to look at first.", body: "Start with the **axis**, then the shape." },
{ slug: "one-number", title: "One number", summary: "When a headline figure is enough.", body: "A number needs a *comparison* beside it." },
];
export const essayBySlug = (slug: string) => essays.find((essay) => essay.slug === slug);
const page = (id: string, title: string, components: Record<string, unknown>[], data?: unknown) => ({
id,
title,
catalogId: siteCatalog.id,
a2ui: A2UI_VERSION,
components: components as never,
...(data === undefined ? {} : { data }),
});
/** Three routes: the home page, the list of essays, and a page for each essay. */
export const site: SiteRoutes = {
title: "Field notes",
theme: { preset: "Ink" },
pages: [
{
route: "/",
meta: { description: "Notes on reading data." },
page: page("home", "Field notes", [
{ id: "root", component: "Hero", title: "Field notes", lead: "Notes on reading data.", children: ["to-essays"] },
{ id: "to-essays", component: "Link", text: "Read the essays", url: "/essays" },
]),
},
{
route: "/essays",
page: page(
"essays",
"Essays",
[
{ id: "root", component: "Section", heading: "Essays", children: ["list"] },
{ id: "list", component: "Column", children: essays.map((essay) => `to-${essay.slug}`) },
...essays.map((essay) => ({ id: `to-${essay.slug}`, component: "Link", text: essay.title, url: `/essays/${essay.slug}` })),
],
),
},
{
route: "/essays/[slug]",
page: page("essay", "Essay", [
{ id: "root", component: "Column", children: ["title", "body", "back"] },
// The page is the whole document, so its title is a Hero: the one <h1>.
{ id: "title", component: "Hero", align: "start", title: { "@path": "/essay/title" }, lead: { "@path": "/essay/summary" } },
{ id: "body", component: "Markdown", text: { "@path": "/essay/body" } },
{ id: "back", component: "Link", text: "All essays", url: "/essays" },
]),
},
],
};One optional catch-all route serves every page. Its params, metadata and page all come from the site:
app/[[...route]]/page.tsx:
import { SitePage, siteMetadata, siteParams } from "@surfaces-ui/next";
import type { Metadata } from "next";
import { essayBySlug, essays, site } from "../../site";
type Props = { params: Promise<{ route?: string[] }> };
// Only the site's own addresses exist; anything else is a 404 at build time.
export const dynamicParams = false;
export function generateStaticParams() {
return siteParams(site, { "/essays/[slug]": () => essays.map((essay) => essay.slug) });
}
export function generateMetadata({ params }: Props): Promise<Metadata> {
return siteMetadata(site, params, {
describe: (route, { slug }) => {
const essay = route === "/essays/[slug]" && slug ? essayBySlug(slug) : undefined;
return essay ? { title: essay.title, description: essay.summary } : undefined;
},
});
}
export default function Page({ params }: Props) {
return <SitePage site={site} params={params} data={(_, { slug }) => (slug ? { essay: essayBySlug(slug) } : {})} />;
}Notes on it:
siteParamslists every address forgenerateStaticParams, with[]for the home page. A route that takes values when none were given is an error, so a static export never leaves a page out quietly.dynamicParams = falsemakes any other address a 404 at build time.SitePageis a server component. It finds the page, callsnotFound()for an address the site does not have, and checks the page against its catalog. A page the catalog refuses stops the build with what is wrong.dataruns on the server. What it returns is merged into the page's data, where the page binds to it ({ "@path": "/essay/title" }). The route's own values are also at/@route(/@route/slug). Only plain JSON reaches the browser.siteMetadatawrites the title (the site's title after a page's, the home page's alone), the description, the canonical path and a link preview.describegives a route that takes values its own title and description.- A link to a path on the site (
"/essays") moves through Next.js's router without loading the page again. A link elsewhere opens in a new tab, as it does in any surface. - Images come from the app. A
Medianames an image, andresolveImageonSitePageandsiteMetadataturns the name into an address on the server. With neither that norimageOrigins, a page loads no address an agent wrote (see the site catalog's rules). - The essay's title is a
Hero, not aText: a page that is the whole document has one<h1>, andHerodraws it.Text's heading variants start at<h2>, since inside a host's page the host owns the<h1>.
A part of a page
You don't have to give Surfaces whole routes. SurfaceSection draws one page document as a part of a Next.js page you write yourself: your own markup around it, as many sections as you like on one page, each rendered on the server. It takes data (plain JSON, merged into the page's data), theme, resolveImage and imageOrigins. Each section is themed in its own region, so the rest of the page keeps your look. A section the catalog refuses stops the build with what is wrong, as a route does.
app/about/page.tsx:
import { SurfaceSection } from "@surfaces-ui/next";
import { A2UI_VERSION, type PageDocument, siteCatalog } from "@surfaces-ui/spec";
import type { Metadata } from "next";
import { essays } from "../../site";
export const metadata: Metadata = { title: "About · Field notes" };
/** One part of this page is Surfaces components; the rest is the app's own markup. */
const latest: PageDocument = {
id: "latest",
title: "Latest essays",
catalogId: siteCatalog.id,
a2ui: A2UI_VERSION,
components: [
{ id: "root", component: "Section", heading: "Latest essays", level: 2, children: ["list"] },
{ id: "list", component: "Column", children: essays.map((essay) => `to-${essay.slug}`) },
...essays.map((essay) => ({ id: `to-${essay.slug}`, component: "Link", text: essay.title, url: `/essays/${essay.slug}` })),
],
};
export default function About() {
return (
<main>
<h1>About these notes</h1>
<p>Written by the app, styled by the app.</p>
<SurfaceSection page={latest} />
<p>And back to the app's own words.</p>
</main>
);
}The /about folder sits beside the catch-all route, and Next.js serves it first, as it does any fixed route. A site can be all routes, all sections, or a mix of the two.
Styles
The root layout loads the stylesheet. The layered form keeps Surfaces' rules below Tailwind's and your own:
app/layout.tsx:
import "@surfaces-ui/components/styles.layer.css";
import type { ReactNode } from "react";
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}turbopack.root is needed only in a pnpm workspace like this repository, where the packages are linked from outside the app's folder. In an app of your own, next.config needs only output: "export":
next.config.mjs:
import fs from "node:fs";
import path from "node:path";
/** The folder holding the workspace's lockfile, which the bundler must be allowed to read from. */
function workspaceRoot(dir) {
for (let at = dir; at !== path.dirname(at); at = path.dirname(at)) {
if (fs.existsSync(path.join(at, "pnpm-lock.yaml"))) return at;
}
return dir;
}
/** Static export: every route is written as HTML at build time, and nothing runs on a server. */
export default {
output: "export",
trailingSlash: true,
// Only needed inside a pnpm workspace, where packages are linked from outside the app's folder.
turbopack: { root: workspaceRoot(import.meta.dirname) },
};Each page is themed in its own region (scope="scoped", kept in memory), unless your layout already has a ThemeProvider, in which case that one is used. Data components (Chart, DataGrid and the rest) need a DataSourceProvider from a client component in your layout, as in Embed in a Next.js app. They draw once the page has loaded in the browser.
Relative imports in the app's own files are written without .js, as Next.js expects; Turbopack does not map .js onto a .ts file.
The test checks the routes and metadata every time. With SURFACES_TEST_NEXT=1 it also runs a real next build (Next.js 16.4, Turbopack, static export) and reads the HTML written for every page, the about page included. CI does that on every push and pull request, in a job of its own (nextjs). The exported site has also been opened in Chromium: the routes and the about page hydrated with no errors, and links moved between pages without reloading.
site.test.ts:
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { siteMetadata, siteParams, siteProblems } from "@surfaces-ui/next";
import { describe, expect, it } from "vitest";
import { essays, site } from "./site.js";
const here = import.meta.dirname;
describe("a Next.js site from Surfaces pages", () => {
it("has a route for every page and an address for every essay", async () => {
expect(siteProblems(site)).toEqual([]);
const params = await siteParams(site, { "/essays/[slug]": () => essays.map((e) => e.slug) });
expect(params).toEqual([{ route: [] }, { route: ["essays"] }, ...essays.map((e) => ({ route: ["essays", e.slug] }))]);
});
it("titles an essay from its own text", async () => {
const meta = await siteMetadata(site, Promise.resolve({ route: ["essays", "one-number"] }), {
describe: (_, { slug }) => ({ title: essays.find((e) => e.slug === slug)?.title }),
});
expect(meta.title).toBe("One number · Field notes");
});
// A real `next build` with static export takes about a minute, so it runs when asked: SURFACES_TEST_NEXT=1.
it.runIf(process.env.SURFACES_TEST_NEXT)(
"builds with Next.js as static HTML, each page drawn on the server",
() => {
// Inside apps/recipes, so the app finds `next` and the workspace's packages in node_modules.
const app = path.resolve(here, "../../.next-build");
fs.rmSync(app, { recursive: true, force: true });
fs.mkdirSync(app, { recursive: true });
for (const name of ["app", "site.ts", "next.config.mjs"]) fs.cpSync(path.join(here, name), path.join(app, name), { recursive: true });
execFileSync(path.resolve(here, "../../node_modules/.bin/next"), ["build"], { cwd: app, env: { ...process.env, NEXT_TELEMETRY_DISABLED: "1" }, stdio: "pipe" });
const read = (route: string) => fs.readFileSync(path.join(app, "out", route, "index.html"), "utf8");
const home = read("");
expect(home).toContain("<title>Field notes</title>");
expect(home).toMatch(/<h1[^>]*>Field notes<\/h1>/);
expect(home).toContain('href="/essays"');
for (const essay of essays) {
const html = read(`essays/${essay.slug}`);
expect(html).toContain(`<title>${essay.title} · Field notes</title>`);
expect(html).toMatch(new RegExp(`<h1[^>]*>${essay.title}</h1>`));
expect(html).toContain(`<link rel="canonical" href="/essays/${essay.slug}"/>`);
// The theme is in the first HTML, not added once scripts run.
expect(html).toContain("--sf-color-bg");
}
expect(read("essays/one-number")).toContain("<em>comparison</em>");
// A page the app writes itself, with Surfaces components as one part of it.
const about = read("about");
expect(about).toContain("<h1>About these notes</h1>");
expect(about).toMatch(/<h2[^>]*>Latest essays<\/h2>/);
expect(about).toContain('href="/essays/one-number"');
expect(about).toContain("back to the app");
},
300_000,
);
});Not built yet: layouts shared by pages (a header and a side navigation on every page), which wait for the site document in the sites plan.
Source and test: apps/recipes/src/nextjs-site