Docs/Ecosystem/Static

Static

Export Fletch apps to static HTML, build typed Markdown collections, OG cards, and search indexes, or split-deploy a static site with a live Go backend.

github.com/fletchhq/static

staticpkg.go.devstatic/contentpkg.go.devstatic/content/highlightpkg.go.devstatic/ogpkg.go.dev

Updated 2026-12-06 fletch docs show static/static 17 min read

On this page

Static turns a Fletch app into a static site. It renders every page in process, writes the files plus the host's redirect and header rules, and checks the result before it replaces your last export. It also ships typed Markdown collections, Open Graph cards, a search index, feeds, hybrid prerendering, and split deploys that put Live pages on a CDN in front of a Fletch backend.

Introduction

Every page of a Fletch app is an http.Handler, so github.com/fletchhq/static does not need a second rendering path. The exporter sends each planned URL through your app's handler, captures the response, and writes it as a file. Same-origin links, assets, and CSS references are crawled, so a broken link fails the export instead of reaching production. The build path is pure Go with CGO_ENABLED=0 and no Node or npm.

The root package does not import github.com/fletchhq/fletch. It accepts any value with Handler() http.Handler and Router() *router.Router, which *fletch.App has. Full API docs live on pkg.go.dev.

The repository ships four Go modules, so your binary only links what you import:

Module Version Role
github.com/fletchhq/static v0.2.1 Exporter, five host targets, preview emulators, CSP hash pass, checks, Prerender, FromFS, split deploy, and the feed, search, seo, statictest, and deploy/* packages
github.com/fletchhq/static/content v0.1.1 Typed Markdown collections with frontmatter validation, GFM, callouts, code tabs, components, and hot reload. Never imports the root package.
github.com/fletchhq/static/content/highlight v0.1.1 A content.Highlighter on Chroma, a Crest lexer, and the fletch.page light/dark stylesheet
github.com/fletchhq/static/og v0.1.0 Pure-Go 1200x630 Open Graph card renderer and cached http.Handler

Installation & Scaffolding

Scaffold a marketing or docs site with no database:

fletch new docs-site --site
cd docs-site
go mod tidy
fletch dev

--site writes Markdown in content/docs/, Crest pages in modules/site/ and ui/layouts/, and bootstrap/static.go, which wires Static and registers its commands. fletch dev watches content/ and sends the browser a reload without a Go rebuild; the collection reads content/ from disk under FLETCH_DEV=1 and picks up the edit itself.

To add Static to an existing app:

go get github.com/fletchhq/static@v0.2.1
go get github.com/fletchhq/static/content@v0.1.1
go get github.com/fletchhq/static/content/highlight@v0.1.1
go get github.com/fletchhq/static/og@v0.1.0

Only the root module is required. Run fletch ax sync afterwards so fletch docs show static/static and the bundled agent skill are available offline.

Static Export & Commands

Build a *static.Site from your app and register its commands:

func Static(app *fletch.App, docs *site.Docs) *static.Site {
	return static.New(app,
		static.URL("https://example.com"),
		static.Paths("docs.show", docs.Params("slug")), // /docs/{slug...}
		static.Redirect("/docs", "/docs/getting-started", http.StatusFound),
		static.Exclude("/admin/*"),
	)
}

// bootstrap/app.go
app.Command(Static(app, docs).Commands()...) // export, preview, verify-backend, topology

Auto-discovery exports every public GET route with no path parameters. Routes with parameters need Paths; mounts need Page.

Option Purpose
URL(u) Public site URL for absolute links, canonical URLs, and the sitemap. --url wins, then URL, then APP_URL.
Paths(route, fn) Parameter sets for a route name or pattern. fn is a static.PathsFunc; Collection.Params("slug") fits it.
Page(path) / Exclude(globs...) Add a path with no route of its own, or leave paths out. A trailing /* matches everything below it.
Redirect(from, to, status) A redirect rule; from may end in /*, and a * at the end of to takes the matched rest.
NotFound(path) The page written as 404.html.
TrailingSlash(static.Never | static.Always) URL form and file layout. Default Never (pricing.html).
Base(path) Serve under a prefix such as /repo.
Assets(dir) / Public(dir) Pipeline asset directory (default public/dist) and the directory copied verbatim (default public).
CSPStrict() / Checks(fns...) / Search(opts...) See Strict CSP & SEO checks and Search.
Backend(url, opts...) / Rewrite(from, to) See Split Deploy.

In handlers

These helpers do nothing outside an export, so the same handler serves live traffic and the export:

  • static.Exporting(ctx) reports an export request, so a handler can skip analytics or session writes.
  • static.BasePath(ctx) returns the base path for URLs built inside inline scripts.
  • static.Drafts(ctx) reports --drafts.
  • static.Describe(ctx, static.LastMod(t), static.NoIndex(), static.Source("content/x.md:12"), static.Priority(0.8)) records page facts for the sitemap and for diagnostics.

Commands

./app export writes dist/. From the global CLI, fletch export [args...] builds the app as fletch build does and then runs bin/<app> export [args...].

fletch export --target cloudflare --url https://example.com --verify
Flag Purpose
--out <dir> Output directory (default dist)
--target <host> cloudflare (default), vercel, netlify, github-pages, or plain
--url <url> Public site URL (default static.URL, then APP_URL)
--base, --host Path prefix, and a Host group to export and send as the request Host
--drafts, --noindex Include drafts; write Disallow: / and X-Robots-Tag: noindex for preview deploys
--verify Render everything twice and report differences (S006)
--allow S007,... Codes whose errors do not fail the export
--json, --dry-run Print only the report; render and check without writing
--page-timeout Longest render for one page (default 30s)
--write-config, --vercel-json, --cname, --write-workflow Host-specific files; see Hosting Targets
--pagefind Also run the pagefind binary (must be on PATH) over the export
--serve, --port Preview the export after writing it (default port 4321)
--backend, --verify-backend, --require-build-match, --cross-site Split deploy; see Split Deploy

The export is written into a temporary directory and renamed over --out only when it succeeds, so a failed export leaves the previous one in place. Files and rule lists are sorted, so two exports of the same build are byte-identical. A copy of the report goes to .fletch/static/last-export.json, which the dev dashboard's Static panel reads.

From Go, (*Site).Export(ctx, static.ExportOptions{...}) returns the same *static.Report, and (*Site).Topology(opts) resolves the split-deploy plan without rendering anything.

./app preview [dir] serves an export on loopback the way the host does: Cloudflare and Netlify _redirects and _headers, Vercel's Build Output routes, GitHub Pages' file-only rules, and each host's 404.html behavior. The directory is a positional argument (default dist). static.Preview(fsys, static.PreviewOptions{Target: "cloudflare"}) returns the same (http.Handler, error) for tests. The emulators follow each host's documentation; keep one real smoke deploy per host.

Content Collections & Syntax Highlighting

content.New[T] loads a directory of Markdown files into typed entries. Frontmatter decodes into T, and each body compiles once at load into HTML plus component calls.

//go:embed content
var contentFS embed.FS

type DocMeta struct {
	content.Base `yaml:",inline"`
	Badge        string `yaml:"badge" validate:"omitempty,oneof=crest live nock quiver pubsub ax"`
}

docs, err := content.New[DocMeta]("docs", content.Auto(contentFS, "content/docs"),
	content.WithHighlighter(highlight.New()),
	content.WithCacheDir(".fletch/cache/static"),
	content.GitDates(),
)
  • Sources: content.Embed(fsys, dir), content.Dir(dir), or content.Auto(fsys, dir), which reads the disk when FLETCH_DEV=1 and dir exists, and the embed otherwise.
  • Reading: Get(id), All() (by Weight, then Date newest first, then ID), Where(fn), Taxonomy(field), Params(key), Redirects() (from each entry's aliases), and LastError(). content.Paginate(entries, per) returns []content.PageOf[T] with Number, Total, Items, Prev, and Next.
  • Options: GitDates() fills Updated from one git log over the directory. IncludeDrafts(on) defaults to on under FLETCH_DEV=1. WithClasses(map[content.Element]string) adds classes per element; output is classless without it. WithLinkResolver(fn) maps relative .md links to URLs. Check(fn) runs after every load and reload. WithCacheDir(dir) caches highlighted code by file hash.
  • Components: content.Components(content.Component("Callout", fn)) turns a capitalized tag at the start of a line into a Crest component with typed, validated attributes.
  • Markdown: goldmark with GFM tables, task lists, footnotes, > [!TIP]-style callouts, and code tabs from fenced blocks with tab="Go" in the info string. Heading IDs follow github-slugger.

content.Base holds title (required), description, date, updated, draft, slug, tags, weight, and aliases. Unknown frontmatter keys are rejected. A load collects every problem in every file into a *content.LoadError whose diagnostics (STATIC_FRONTMATTER, STATIC_LINK, STATIC_COMPONENT, STATIC_COLLECTION, STATIC_MARKDOWN) point at the file and line. In development a bad edit keeps the last good snapshot.

Highlighting

highlight.New() lexes with Chroma and writes one class per palette role (hl-keyword, hl-string, hl-func, and so on). It registers a Crest lexer for crest fences and *.crest files. highlight.CSS(highlight.Fletch) returns the matching stylesheet as light-dark() pairs; serve it as a pipeline asset. Because highlight is its own module, a binary that never highlights carries no Chroma.

Social Cards (OG), Search & Feeds

Open Graph cards

github.com/fletchhq/static/og draws 1200x630 PNG cards in pure Go from a node tree: Box (solid or LinearGradient fill, border, radius, padding), Row and Column, Layer, Grid, Spacer, Text, Badge, and FitTitle. Load fonts with og.ParseFont(ttfBytes) and colors with og.Hex(0xa21caf).

og.Handler(fn) serves a card as image/png with an ETag and caches it in .fletch/cache/static/og/ by a hash of its content (og.CacheDir(dir) changes that). Give card routes a .png path so the export writes files named after URLs:

r.Handle(http.MethodGet, "/og/{slug...}", og.Handler(func(r *http.Request) (og.Node, error) {
	slug, ok := strings.CutSuffix(r.PathValue("slug"), ".png")
	doc, found := docs.Get(slug)
	if !ok || !found {
		return nil, og.ErrNotFound
	}
	return og.Box{
		Fill:    og.Solid(og.Hex(0x181c23)),
		Padding: og.All(72),
		Width:   1200, Height: 630,
		Child: og.FitTitle(doc.Meta.Title, titleFont, 84, 48, 3, og.Hex(0xe9eaee)),
	}, nil
}), router.WithName("og.docs"))
static.Paths("og.docs", func(ctx context.Context) ([]static.Params, error) {
	ps, err := docs.Params("slug")(ctx)
	for _, p := range ps {
		p["slug"] += ".png"
	}
	return ps, err
})

static.Search(opts...) indexes every exported HTML page that is not noindex and writes /_search/index.json plus /_search/client.js, a small script with no eval or inline handlers, so it runs under a hashed CSP. Large indexes are sharded and loaded on demand. search.Include("/", "/docs/*"), search.Exclude(...), and search.ShardSize(n) tune it, and indexing honors Pagefind's data-pagefind-* attributes. search.Client() returns the client script's bytes if you serve it yourself.

<script src="/_search/client.js" defer></script>
<div data-fletch-search data-limit="8" data-empty="Nothing found">
  <input type="search" aria-label="Search the docs">
  <ol data-fletch-search-results hidden></ol>
</div>

Feeds

github.com/fletchhq/static/feed serves deterministic RSS 2.0, Atom 1.0, and JSON Feed 1.1 from one feed.Builder:

build := func(ctx context.Context) (feed.Feed, error) {
	return feed.Feed{Title: "Blog", SiteURL: "https://example.com", Items: items()}, nil
}
r.Handle(http.MethodGet, "/blog/feed.xml", feed.RSS(build))
r.Handle(http.MethodGet, "/blog/atom.xml", feed.Atom(build))
r.Handle(http.MethodGet, "/blog/feed.json", feed.JSON(build))

Routes with a file extension are auto-discovered by the export. feed.RenderRSS, feed.RenderAtom, and feed.RenderJSON render outside HTTP.

Strict CSP & SEO Checks

A static file cannot carry a per-request nonce. After rendering, the exporter removes every nonce attribute, hashes each inline <script> and <style> that carried it, and replaces 'nonce-…' in the policy with those 'sha256-…' sources. It then delivers the policy as one global header rule, per-path rules, or <meta> tags, whichever the target supports.

A cross-origin script that carried the nonce normally has its origin added to script-src with info S008. With static.CSPStrict() that is an error, so every third-party origin must already be listed in your secure.Config.

static.Checks(fns...) adds checks over the finished export, reported like the built-in ones. seo.Preset() requires a title, description, canonical URL, og:* and twitter:card tags, unique titles and descriptions, a valid 1200x630 og:image, sitemap coverage, and valid JSON-LD (SEO001 to SEO007):

static.New(app,
	static.CSPStrict(),
	static.Checks(seo.Preset()),
)

Errors fail the export and leave the output directory unchanged. To ship anyway while you fix one, name its code:

./app export --verify --allow S007,SEO005
Code Detects
S001 A Live route or data-f-live without split deploy
S002 A same-origin POST form with a CSRF field
S003 Set-Cookie on an exported response
S004 An unexpected status, render timeout, or bad 404 probe
S005 A broken link, asset, or #fragment
S006 Two renders differ (--verify)
S007 on*= or style= attributes under a hashed policy
S008 A cross-origin script origin added to script-src (error under CSPStrict)
S011 Two URLs on one output file
S012 A host rule budget exceeded, or a public/ rule-file conflict
S013 The nonce outside a nonce attribute
S014 The target cannot express a header or directive

Hosting Targets

Pick a target with --target or ExportOptions.Target (static.Cloudflare(), static.Vercel(), static.Netlify(), static.GitHubPages(), or static.Plain()):

Target Writes Notes
cloudflare (default) files, _redirects, _headers, 404.html Workers Static Assets and Pages. --write-config creates wrangler.jsonc (static.WriteWranglerConfig) and never overwrites one.
vercel .vercel/output/ (Build Output API v3) Deploy with vercel deploy --prebuilt. --vercel-json writes plain files and vercel.json for Git builds.
netlify files, _redirects, _headers, 404.html --write-config creates netlify.toml (static.WriteNetlifyConfig).
github-pages files, .nojekyll, 404.html, CNAME, redirect stubs No headers: policies go into <meta> and S014 lists what is lost. --write-workflow creates .github/workflows/pages.yml (static.WritePagesWorkflow).
plain files, 404.html, static-manifest.json For S3, nginx, or Caddy. Rules are listed in the manifest.

For a split deploy on Cloudflare with static.Proxy(), the export also writes fletch-proxy.js, a Worker that forwards proxied paths (including Live WebSocket upgrades) to the backend and serves everything else from env.ASSETS. static.WranglerProxy(dir, slash, proxy) returns the matching wrangler.jsonc block, which --write-config writes for you.

github.com/fletchhq/static/deploy/cloudflare and deploy/netlify upload an export directly with the standard library, with no host CLI or Node required.

Hybrid Prerendering

static.Prerender caches rendered snapshots of public pages inside a running Fletch server while every other route stays dynamic:

pre := static.Prerender(app,
	static.Routes("/", "/pricing", "/blog/*"),
	static.Paths("blog.show", blog.Params("slug")),
	static.Warm(static.AtBoot),        // or static.Lazy
	static.Revalidate(10*time.Minute), // 0 keeps snapshots until Invalidate
	static.WithErrorReporter(func(path string, err error) { slog.Error("prerender", "path", path, "err", err) }),
)
app.Use(pre.Middleware())
app.OnStart(pre.Warm)

// On publish:
pre.Invalidate("/blog/new-post", "/blog")
  • Snapshots serve strong ETags with 304 handling and precomputed br/gzip bodies, and swap the per-request nonce CSP for the snapshot's hashed policy.
  • Requests with an Authorization header or a session cookie (fletch_session or session by default) bypass the cache. Change that with static.SkipCookies(names...) and static.SkipRequest(fn).
  • Responses with Set-Cookie, Cache-Control: private or no-store, or Vary: Cookie are never cached.
  • static.InvalidateOn(ctx, sub, pre) fans invalidations out across nodes from any subscriber with Subscribe(ctx, func(static.Invalidation)), such as a pubsub typed topic.

To ship a plain export inside your binary instead, embed it and serve it with static.FromFS(fsys), an http.Handler with clean URLs, redirects, headers, 404.html, ETags, and compression.

Split Deploy

A split deploy puts your static export on a CDN and keeps Live pages, form posts, and dynamic routes on a Fletch backend at another origin. At export time each Live page renders as a shell: an HTML snapshot with no session ID, CSRF token, or cookie. In the browser the shell joins the backend's Live endpoint and takes over.

Both sides check the same contract. The export proves in process that your backend accepts the site, verify-backend checks the deployed backend over the network, and every shell checks the protocol and template fingerprint at join time so a skewed backend never patches the wrong DOM.

Backend

Tell the backend which static origins to trust with fletch.WithStaticFrontend:

app := fletch.New(
	fletch.WithStaticFrontend(fletch.StaticFrontend{
		Origins:     []string{"https://example.com", "https://*.example.pages.dev"},
		Credentials: true,
		Forms:       []string{"/contact"},
	}),
	fletch.WithRoutes(routes), // calls fletch.MountLive for each Live page
)
  • Every page registered with fletch.MountLive also answers GET and POST at /_fletch/live{path} (fletch.LivePrefix), behind the page's own middleware. The endpoints are added when fletch.New runs, so register those pages through fletch.WithRoutes; a Live page mounted later from a module's Register gets no endpoint, and the export reports S018.
  • GET /_fletch/contract (fletch.ContractPath) serves app.Contract(): the Live protocol, build ID, Fletch version, transports, and each Live page's path and template fingerprint.
  • Live endpoints and the contract answer CORS for Origins. An origin is exact or a leading-label wildcard (subdomains only). $FLETCH_STATIC_ORIGINS adds more, comma-separated.
  • fletch.CSRF accepts a cross-origin POST to a Live endpoint or a Forms glob by its allowed Origin instead of a token. A POST there with no Origin and no Sec-Fetch-Site: same-origin gets a 403.
  • Routes behind auth.OriginProtection need the same trust: pass fletch.StaticOrigin to auth.OriginProtectionFunc.

fletch.BuildID() names the running build: $FLETCH_BUILD_ID, else the binary's VCS revision (with -dirty for uncommitted changes), else unknown. You do not wire it yourself: fletch.Live, which MountLive uses, passes it to live.WithBuildID, so shells and probe frames carry it. The wire protocol is live.Protocol (currently 2); a join from a runtime on another protocol is refused with W6015 ("redeploy the static site").

Frontend

Pass static.Backend to static.New:

site := static.New(app,
	static.URL("https://example.com"),
	static.Backend("https://app.example.com",
		static.Dynamic("/app/*"),                    // backend-owned: not exported, links go to the backend
		static.Credentials(),                        // send cookies with Live and backend calls
		static.LiveShell("dashboard", static.Empty), // skip Mount at export for this page
	),
	static.Rewrite("/docs-app/*", "/docs-app/index.html"),
)
Option Purpose
Backend(url, opts...) The backend origin. --backend wins, then url, then $FLETCH_BACKEND_URL.
Dynamic(globs...) Paths the backend owns. They are not exported, and links and form actions pointing at them are rewritten to the backend (S020).
Proxy(prefixes...) Have the static host proxy the Dynamic globs (or prefixes), /_fletch/contract, and /_fletch/live/* to the backend, so everything stays same-origin.
LiveDirect() With Proxy(), Live still joins the backend origin directly.
Credentials() Send cookies with Live and backend requests; pair it with StaticFrontend.Credentials.
LiveShell(route, mode) How a Live route's shell renders: static.Render (default, runs Mount once with no user) or static.Empty.
Rewrite(from, to) A status-200 host rewrite, such as an SPA fallback. Needs no Backend.

A Render shell's HTML is public like any static page. Use static.Empty, or check live.IsShell(ctx) in Mount, for pages that would otherwise render per-user data.

Topologies

Topology Set with The shell joins Dynamic links and form posts
separate (default) Backend(url) https://app.example.com/_fletch/live/<path> Rewritten to absolute backend URLs
proxy Backend(url, Proxy()) /_fletch/live/<path>, proxied by the host Stay relative; the host proxies them
mixed Backend(url, Proxy(), LiveDirect()), or Proxy() on Netlify or Vercel The backend origin, as separate Proxied, as proxy

Cookies only reach the backend when both origins share a site (example.com and app.example.com) or when requests go through Proxy(); otherwise Credentials() is S021. Netlify and Vercel proxy rules are assumed not to forward WebSockets, so Proxy() there falls back to mixed with an S022 warning.

./app topology [--json] prints what an export will resolve without rendering: the mode, site, backend, Live base, origins the backend must allow, dynamic and proxied globs, rewrites, and each Live shell.

Preview & verify

Run the whole split deploy on one machine:

./app preview --backend auto

This starts the app's serve command on a free loopback port with FLETCH_STATIC_ORIGINS set, exports against it into .fletch/static/preview, runs verify-backend, serves the static site, and runs verify-backend --site-check through it. --cross-site puts the backend on 127.0.0.1 to reproduce S021.

Against a deployed backend, check before writing files, or check an existing export:

fletch export --backend https://app.example.com --verify-backend --require-build-match
./app verify-backend --dir dist --require-build-match --site-check --json

verify-backend checks /readyz, the contract's CORS, protocol, build, and fingerprints, each endpoint's preflight, and a probe join over WebSocket and SSE. --site-check runs after the static deploy and also checks the host's proxy rules and its _fletch/static.json.

Code Detects
S017 Invalid split config: no backend URL, a LiveShell naming no Live route, or a glob not starting with /
S018 No /_fletch/live{path} or /_fletch/contract on the backend, or it refuses the site's Origin
S019 A Live endpoint's CORS preflight fails, or lacks credentials under Credentials()
S020 Count of links and form actions rewritten to the backend (info)
S021 Credentials() with a cross-site backend and Live not proxied
S022 The target cannot proxy or rewrite (GitHub Pages), or falls back to LiveDirect (Netlify, Vercel)
S023 A Live shell answered 401, 403, or a redirect at export
S024 CSP connect-src or form-action sources the shells need: added (info) or missing under CSPStrict (error)
S025 The backend URL is unusable, or is the site's own origin without Proxy()
S026 A path is both Dynamic and exported, or a Rewrite overlaps Dynamic
S027 A shell carries a session ID, CSRF token, or no endpoint
S032 The backend runs another build than the export (warning; error with --require-build-match)
S033 The backend serves another template than a shell was built from, or the deployed site serves another export
S035 With --site-check on a proxied topology, the site's /_fletch/contract is not the backend's

S031 (protocol mismatch), S034 (Live probe failures), and S036 (backend unreachable or not ready) round out the network checks.

GitHub Actions

deploy/github-actions/split-deploy.yml in the Static repository wires the deploy order into one job. Copy it to .github/workflows/deploy.yml:

  1. Set FLETCH_BUILD_ID: ${{ github.sha }} for the whole job, so the backend and the export carry the same build.
  2. Deploy the backend first (the recipe uses ship deploy production).
  3. Export and prove the deployed backend: go run . export --target cloudflare --out dist --verify-backend --require-build-match.
  4. Deploy the static site to Cloudflare Workers Static Assets with cloudflare/wrangler-action@v3, which also uploads fletch-proxy.js.
  5. Check through the live site: go run . verify-backend --dir dist --site-check --require-build-match.

Any failure after the backend deploy stops the job before the static site changes, so visitors never get shells the running backend cannot serve.