Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    On this page

    Author semantic Markdown pages

    Brix can expose an authored semantic Markdown representation alongside an SSR HTML page. Opt in page by page and project the same successful loader data into intentionally different renderers.

    Use this for articles, product information, or documentation that should be readable without parsing the visual HTML layout. Write the useful content and links explicitly; navigation controls and decorative UI usually do not belong in the projection. This is an output API, not a parser for authored .md files. Its builders keep CMS and user text from becoming active Markdown or raw HTML.

    Export project-bound factories

    #

    Keep contracts browser-safe and route bindings server-only. New applications already export these bindings:

    // src/brix.ts
    export const { createMarkdownIndexContract, createPageContract, getMarkdownIndexPath, getPath } =
      brix;
    
    // src/brix.server.ts
    export const { createMarkdownIndexRoute, createPageRoute } = brixServer;
    

    See pages for the complete contract, loader, component, and route workflow.

    Add a page representation

    #
    // contract.ts
    import { createPageContract } from "#brix";
    
    export const articlePageContract = createPageContract({
      path: "/articles/:slug",
      representations: ["markdown"],
    });
    
    // route.ts
    import { md } from "brix/markdown";
    import { createPageRoute } from "#brix/server";
    import { ArticlePage } from "./Page.tsx";
    import { articlePageContract } from "./contract.ts";
    
    // getArticle is an application-specific data dependency.
    export const articlePageRoute = createPageRoute(articlePageContract, {
      component: ArticlePage,
      load: async (c, { params }) => ({ article: await getArticle(c, params.slug) }),
      markdown: (_c, { article }) =>
        md.document({
          body: [md.heading(1, md.text(article.title)), md.paragraph(md.text(article.summary))],
        }),
    });
    

    The markdown callback is required when the contract declares Markdown and forbidden otherwise. It receives a readonly view of successful loader props and returns a MarkdownDocument from md.document, synchronously or as a promise. Keep redirects, not-found responses, and other early Response values in load.

    Brix invokes exactly one renderer. HTML runs Preact, styling, islands, fragments, and hydration preparation. Markdown runs the callback and deterministic serializer without Preact or a browser runtime. The callback must explicitly include semantics for content that HTML obtains from a fragment; Markdown never fetches fragment endpoints.

    Query values classified as shellIndependent for HTML-only shells still vary both representation keys after Markdown is enabled. The Markdown body may include that query-dependent fragment content, and HTML's automatic alternate links preserve the query. Do not duplicate cache declarations for the two renderers. Follow the cache admission contract before enabling shared caching for represented pages.

    Build safe documents

    #

    Use md.text for every CMS or user-provided string. Builders return immutable branded values, not plain objects or raw strings:

    const content = md.fragment(
      md.paragraph(md.strong(md.text("Status: ")), md.text(status)),
      md.list(items.map((item) => md.listItem(md.paragraph(md.link(item.url, md.text(item.title)))))),
      md.paragraph(md.image(image.url, image.alt)),
      md.codeBlock(example, { language: "ts" }),
      md.table({
        align: ["left", "right"],
        header: [[md.text("Plan")], [md.text("Price")]],
        rows: plans.map((plan) => [[md.text(plan.name)], [md.text(plan.price)]]),
      }),
    );
    

    The md builders are:

    • inline: text, emphasis, strong, strikethrough, inlineCode, hardBreak, link(url, children, { title }), and image(url, alt, { title });
    • blocks: paragraph, heading(depth, ...children) with depth 1 through 6, blockquote, codeBlock(value, { language }), list(items, { ordered, start }) with listItem, thematicBreak, and table({ header, rows, align });
    • composition: fragment groups blocks for reuse and document({ body }) wraps a page projection; indexDocument builds navigation indexes;
    • serialized output: serializedDocument and serializedIndexDocument wrap Markdown that Brix serialized earlier, as described in serve Markdown serialized ahead of time.

    A table cell is an array of inline nodes; every row needs one cell per header column, and align ("left", "center", "right", or null) needs one entry per column. Lists need at least one item, and start is valid only for ordered lists.

    Builders validate input when called and serialization enforces document-wide limits. Each failure throws an error whose message starts with [brix/markdown]; URL rejections throw the exported MarkdownUrlError subclass:

    • Text rejects control characters other than tab and line breaks, and bidirectional formatting characters that could disguise content.
    • link, image, and index URLs accept absolute http and https URLs with a host and no credentials, mailto: and tel:, and relative URLs such as /docs/start.md, guide.md, ?page=2, or #install. They reject other schemes such as javascript: and data:, protocol-relative //host URLs, malformed percent encoding, schemes, slashes, or control characters hidden by single or double percent encoding, backslashes, surrounding whitespace, and URLs longer than 2,048 characters. An encoded percent sign such as /products/50%25-off.md, which getPath produces for a 50%-off param, is accepted.
    • A code block language is 1 to 64 letters, digits, _, +, ., or -, starting with a letter or digit.
    • A document may nest at most 64 levels and contain at most 10,000 nodes, and its serialized output may not exceed 1 MiB (1,048,576 bytes).

    Output is CommonMark plus GFM tables and strikethrough, never raw HTML, with - bullets, _emphasis_, **strong**, and fenced code. Empty strong, emphasis, and strikethrough content serializes as empty text rather than delimiters. This also applies to empty marked Contentful Rich Text, so a blank bold node cannot accidentally become a thematic break. Nested or adjacent strikethrough merges into one span, so ~~~~ cannot open a code fence. inlineCode turns each line ending into a space, which is how CommonMark renders a code span anyway, so multi-line CMS or user text cannot start an HTML block, heading, list, or table row.

    Do not cast strings or objects to Markdown types. Extract projection functions returning MarkdownContent or MarkdownFragment when multiple routes share semantic pieces. To narrow unknown values, use isMarkdownContent, isMarkdownDocumentContent, isMarkdownDocument, or isMarkdownIndexDocument. Outside a page route, for example in a unit test or a custom response, serializeMarkdownDocument and serializeMarkdownIndexDocument return the same deterministic string a route would send.

    Contentful adapters can compose asynchronously. Await their nested renderEntry calls or projectContentfulRichText before passing results to the synchronous builders. At page level:

    markdown: async (c, { entry }) => {
      const body = await markdownEntry(entry, c);
      return md.document({ body });
    },
    

    Import markdownEntry from brix/contentful/rendering/registry. Only explicitly projected entries load, with one bounded loader session for the requested tree. See Contentful rendering for projection bounds, cycle handling, cancellation and the distinction between loader deadlines and arbitrary async code.

    Serve Markdown serialized ahead of time

    #

    A route that returns md.document is serialized on every request. That is usually cheap, but a long guide takes noticeably longer on an edge runtime such as Fastly Compute, where every request starts from a fresh instance and runs the serializer without a JIT. When content does not change per request, serialize it once and return the stored string instead:

    1. Build the document with the md builders and pass it to serializeMarkdownDocument, at build time or when the module loads.
    2. Return md.serializedDocument(markdown) from the route's markdown callback.
    import { md } from "brix/markdown";
    import { createPageRoute } from "#brix/server";
    
    export const guidePageRoute = createPageRoute(guidePageContract, {
      component: GuidePage,
      // `guide.markdown` was produced by serializeMarkdownDocument when the site was built.
      load: async (c, { params }) => ({ guide: await loadCompiledGuide(c, params.slug) }),
      markdown: (_c, { guide }) => md.serializedDocument(guide.markdown),
    });
    

    The response is byte-identical to returning the structured document: Brix still prepends the covering index's navigation pointer, which it serializes once when the application is assembled, and sets the same headers, status handling, and 1 MiB output limit. Indexes take md.serializedIndexDocument the same way; see publish an index.

    The wrappers are not a way to write raw Markdown. md.serializedDocument returns a MarkdownDocument and md.serializedIndexDocument a MarkdownIndexDocument; neither accepts the other, and a route that returns a plain string fails type checking. At run time they check only that the string ends in a line feed, is at most 1 MiB, and contains no control or bidirectional formatting characters, and an index must start with # ; each failure throws a [brix/markdown] error. They cannot check that the syntax is safe, so wrap only strings returned by serializeMarkdownDocument or serializeMarkdownIndexDocument, never authored, CMS, or user Markdown. serializeMarkdownDocument and serializeMarkdownIndexDocument return a wrapped string unchanged.

    Serializing at module load is fine for small documents such as an error page. Fastly snapshots everything created at module load into the Wasm package, so serialize large content at build time and store it with other release assets, as Fastly deployment describes.

    #

    The canonical page URL defaults to HTML and selects Markdown for Accept: text/markdown. Brix ranks Accept by quality, then specificity, then order, and prefers HTML on a tie; a missing, empty, or unparseable header selects HTML. A canonical request whose Accept excludes both representations, such as Accept: application/json, receives 406. A durable .md alias always selects Markdown regardless of Accept.

    Generate both forms with getPath rather than appending a suffix:

    const htmlUrl = getPath(articlePageContract, { params: { slug: "example" } });
    const markdownUrl = getPath(articlePageContract, {
      params: { slug: "example" },
      representation: "markdown",
    });
    

    Brix derives one or more durable aliases from each canonical path:

    • / serves /index.md, and /articles/:slug serves /articles/example.md for /articles/example.
    • A terminal optional parameter also exposes its parent: /items/:id{[0-9]+}? serves /items.md and /items/42.md, but not /items/new.md.
    • A terminal wildcard keeps nested paths: /docs/* serves /docs/guides/start.md, and /docs.md for an empty tail.
    • A Markdown path that matches both / and /index, such as /* or /:slug?, is rejected because both would claim /index.md. Use a prefixed path or a constraint that excludes index.

    Successful responses carry the representation headers, so application code should not add them:

    • Canonical HTML: Vary: Accept, a Link header and head link with rel="alternate" and type="text/markdown" pointing at the durable URL.
    • Negotiated Markdown on the canonical URL: Content-Type: text/markdown; charset=utf-8, Vary: Accept, Content-Location with the durable URL, and the same Markdown alternate Link.
    • Durable .md alias: the Markdown Content-Type and a Link with rel="alternate" and type="text/html" pointing back at the canonical URL, without Vary: Accept.

    A page covered by a Markdown index also receives rel="describedby" discovery, and its Markdown body starts with a single > [Agent navigation index](/llms.txt) line pointing at the most specific covering index. Pages that do not declare a representation stay HTML-only and keep their previous Accept behavior.

    On Markdown-enabled canonical URLs, negotiation happens before the loader. Early loader responses, including redirects, therefore also merge Accept into Vary, preserving existing fields (including *), status, body, cookies, and other headers. Durable .md aliases do not negotiate and do not add Vary: Accept to these responses.

    Rendered non-2xx pages also keep their actual HTML or Markdown content type and, on canonical URLs, Vary: Accept. For example, a loader may set c.status(404) and return props for a rendered missing page. These responses do not receive success-only alternate/discovery headers, Content-Location, or the private edge-cache representation marker. HEAD retains the same headers without a body.

    Suffix recognition follows origin routing at the edge too: /articles/start%2Emd and /articles/start.md/ select Markdown and link back to /articles/start, including for HEAD. Alternate links preserve the remaining wire encoding and query. Encoded reserved separators and percent data remain data: %2F is not a structural slash, and %252E is not a dot. Nested suffixes such as guide.md.md and guide%2Emd.md return 404 rather than exposing an ambiguous canonical URL. These restrictions do not apply to HTML-only pages.

    Localize the projection

    #

    In a translation-enabled app, call the project-bound server getTranslator(c) inside markdown. Do not use useTranslate, which is a Preact hook. Loader and Markdown calls share request-local dictionary preparation. Localized canonical and durable URLs resolve the same locale and return Content-Language; generate paths with the localized getPath(contract, locale, options) overload.

    Localized index callbacks receive { locale } and can await the same translator for titles, summaries, sections, and links. Unlocalized page loaders and index callbacks receive locale: undefined; read the request locale with getLocale(c) when you need it. See translations for locale configuration and test fixtures.

    Diagnose missing or rejected output

    #
    • A .md URL needs representations: ["markdown"] on its page contract and a matching route callback.

    • A 406 on the canonical URL means its Accept header does not permit an available representation; use the durable URL when you always want Markdown.

    • A [brix/markdown] error names the rejected input: an unsafe URL, a control character, malformed structure, or a size limit. Fix the source or choose an explicit readable fallback; do not cast around the builder types. For untrusted links, catch only MarkdownUrlError so content and structure errors still surface:

      import { MarkdownUrlError, md, type MarkdownInline } from "brix/markdown";
      
      function linkOrText(url: string, label: MarkdownInline): MarkdownInline {
        try {
          return md.link(url, label);
        } catch (error) {
          if (error instanceof MarkdownUrlError) return label;
          throw error;
        }
      }
      
    • Content supplied by an HTML fragment does not appear automatically. Include its semantic content in the page projection or a shared projection function.

    • An unexpected navigation line at the top of the Markdown body comes from a covering index; see indexes for scope rules.

    Continue with publishing and operating semantic Markdown.