Render a post
polis.getPost() reads one post from its signed source: the frontmatter (title, dates, licence), and the
markdown with its images and internal links already resolved for your website. It never gives you HTML. You
render the markdown yourself, so the design is entirely yours. This site uses unified, with a sanitizer:
// Markdown → HTML, this website's choice (the SDK has no renderer on purpose).
//
// unified with GFM (tables, footnotes, strikethrough), heading ids for
// anchors, and a sanitizer: the posts are the owner's, but a renderer that
// passes raw HTML through is one bad paste away from running script here.
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkGfm from 'remark-gfm';
import remarkRehype from 'remark-rehype';
import rehypeRaw from 'rehype-raw';
import rehypeSlug from 'rehype-slug';
import rehypeSanitize, { defaultSchema, type Options as SanitizeSchema } from 'rehype-sanitize';
import rehypeStringify from 'rehype-stringify';
const schema: SanitizeSchema = {
...defaultSchema,
// Keep heading ids (rehype-slug) without the sanitizer's "user-content-" prefix.
clobberPrefix: '',
attributes: {
...defaultSchema.attributes,
code: [...(defaultSchema.attributes?.code ?? []), ['className', /^language-./]],
},
};
const pipeline = unified()
.use(remarkParse)
.use(remarkGfm)
.use(remarkRehype)
.use(rehypeSlug)
.use(rehypeSanitize, schema)
.use(rehypeStringify);
export async function renderMarkdown(markdown: string): Promise<string> {
return String(await pipeline.process(markdown));
}
// This site's own pages (the tutorial) may use a little HTML. Never for posts.
const trusted = unified()
.use(remarkParse)
.use(remarkGfm)
.use(remarkRehype, { allowDangerousHtml: true })
.use(rehypeRaw)
.use(rehypeSlug)
.use(rehypeStringify);
export async function renderOwnMarkdown(markdown: string): Promise<string> {
return String(await trusted.process(markdown));
}The post page then does four things every page showing a post must do. They are polis's projection contract:
- a canonical link to this page, because this is the display the author authorised;
- a link to the signed source, and a way to verify it (validate.polis.pub);
- the post's own licence:
<link rel="license">, thecontent-usagesignal for crawlers, and the terms notice, visibly (polis.licenseNotice(post)); - comments addressed by the post's polis address (
post.url), never this page's, so the conversation is the same one wherever the post appears.
// One post. Read from its signed source on the polis site, rendered here.
//
// THE PROJECTION CONTRACT, which every page showing a post carries:
// · a canonical link to this page (this is the authorised display);
// · a link to the signed source, and a way to verify it;
// · the post's own licence: <link rel="license">, a content-usage signal
// for crawlers, and the terms notice, visibly;
// · comments addressed by the post's polis address, never this page's.
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { PolisComments } from '@polis-pub/next/comments';
import { polis, paramsFor, polisPage, ourPath, formatDate, readingTime, validateURL, SITE_HOST } from '@/lib/polis';
import { renderMarkdown } from '@/lib/markdown';
type Params = { date: string; slug: string };
// Every post is built ahead of time; the webhook refreshes one when it changes.
export async function generateStaticParams(): Promise<Params[]> {
return (await polis.getPosts()).map((p) => paramsFor(p.url)).filter((x): x is Params => x !== null);
}
async function load(params: Promise<Params>) {
const { date, slug } = await params;
if (!/^\d{8}$/.test(date) || !/^[a-z0-9-]+$/i.test(slug)) notFound();
try {
return await polis.getPost(polisPage(date, slug));
} catch {
notFound();
}
}
/** The crawler signal from the post's own terms: AIPREF's two keys, as stated. */
function contentUsage(license: Record<string, string> | null): string | undefined {
if (!license) return undefined;
const parts = (['train-ai', 'search'] as const).filter((k) => license[k]).map((k) => `${k}=${license[k]}`);
return parts.length ? parts.join(', ') : undefined;
}
export async function generateMetadata({ params }: { params: Promise<Params> }): Promise<Metadata> {
const post = await load(params);
const usage = contentUsage(post.license);
return {
title: post.title,
alternates: { canonical: ourPath(post.url) ?? undefined },
other: usage ? { 'content-usage': usage } : undefined,
};
}
export default async function PostPage({ params }: { params: Promise<Params> }) {
const post = await load(params);
const [html, all] = await Promise.all([renderMarkdown(post.markdown), polis.getPosts()]);
const i = all.findIndex((p) => p.path === post.path);
const newer = i > 0 ? all[i - 1] : null;
const older = i >= 0 && i < all.length - 1 ? all[i + 1] : null;
const notice = polis.licenseNotice(post);
const short = post.version.replace(/^sha256:/, '');
return (
<article className="post">
{post.license?.terms && <link rel="license" href={post.license.terms} />}
<header className="post-head">
<div className="crumbs">
<a href="/">writing</a>
<span>/</span>
<span>{post.published.slice(0, 10)}</span>
</div>
<h1>{post.title}</h1>
<div className="meta">
<span>{formatDate(post.published)}</span>
<span>{readingTime(post.markdown)} min read</span>
<span className="sig">● signed by {SITE_HOST}</span>
</div>
</header>
<div className="prose" dangerouslySetInnerHTML={{ __html: html }} />
<aside className="provenance" aria-label="Where this post lives">
<div className="bar">Provenance</div>
<dl>
<dt>written on</dt>
<dd><a href={post.url}>{post.url.replace(/^https:\/\//, '')}</a></dd>
<dt>signed file</dt>
<dd><a href={post.source}>{post.path}</a></dd>
<dt>version</dt>
<dd title={post.version}>sha256:{short.slice(0, 12)}…{short.slice(-6)}</dd>
<dt>check it</dt>
<dd><a href={validateURL(post.source)}>validate.polis.pub ↗</a></dd>
</dl>
{notice && <div className="terms">{notice}</div>}
</aside>
<section className="conversation" aria-label="Conversation">
<div className="section-head">
<h2>Conversation</h2>
<span className="eyebrow">reply from your own polis site</span>
</div>
<PolisComments className="widget" author={SITE_HOST} post={post.url} />
<p className="elsewhere">
Comments are published on each reader’s own polis site. The whole conversation is also at{' '}
<a href={post.url}>{SITE_HOST}</a>.
</p>
</section>
<nav className="pager" aria-label="More writing">
{older && (
<a href={ourPath(older.url) ?? older.url}>
<span className="eyebrow">← Older</span>
<span className="t">{older.title}</span>
</a>
)}
{newer && (
<a className="next" href={ourPath(newer.url) ?? newer.url}>
<span className="eyebrow">Newer →</span>
<span className="t">{newer.title}</span>
</a>
)}
</nav>
</article>
);
}generateStaticParams builds every post ahead of time. The webhook in step 8 refreshes one when it changes.