Postream

Loading the index…

Docs: Next.js example

Next.js example

An App Router blog that lists and shows Postream posts, with ISR, SEO and old slug redirect.

This example uses fetch directly, to show what happens. For ready-made metadata, hreflang, JSON-LD, sitemaps and RSS, use the SEO kit, which ships the same client.

Environment variables

Server only, without the NEXT_PUBLIC_ prefix. The key is the secret one (sk_); the site id shows in the panel, under Public API.

.env
POSTREAM_API_URL=https://api.postream.blog/public/v1
POSTREAM_SITE_ID=7c0e...
POSTREAM_API_KEY=sk_...

Client

With the siteId in the URL, the calls go to the per-site route: the Cloudflare edge answers most of them and Postream purges it when the post changes. The query goes in the canonical form (locale before tag, no page=1), the same URL that gets purged.

lib/postream.ts
const BASE = `${process.env.POSTREAM_API_URL}/sites/${process.env.POSTREAM_SITE_ID}`;
 
async function postream<T>(path: string): Promise<T | null> {
  const res = await fetch(`${BASE}${path}`, {
    headers: { Authorization: `Bearer ${process.env.POSTREAM_API_KEY}` },
    // Revalidate every 5 minutes (ISR) or right away, by tag, when a webhook arrives.
    next: { revalidate: 300, tags: ["postream"] },
  });
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`Postream ${res.status} ${(await res.json()).code}`);
  return res.json() as Promise<T>;
}
 
export type PostSummary = {
  id: string;
  locale: string;
  slug: string;
  title: string;
  excerpt: string;
  tags: string[];
  seo: { metaTitle: string; metaDescription: string; og: { title: string; description: string; type: string } };
  translations: { locale: string; slug: string; title: string }[];
  author: { name: string } | null;
  publishedAt: string;
  updatedAt: string;
};
export type Post = PostSummary & { bodyHtml: string; bodyMarkdown: string };
 
export const listPosts = (locale: string, page = 1) =>
  postream<{ data: PostSummary[]; pagination: { page: number; perPage: number; total: number; totalPages: number } }>(
    `/posts?locale=${encodeURIComponent(locale)}${page > 1 ? `&page=${page}` : ""}`,
  );
 
export const getPost = (slug: string, locale: string) =>
  postream<{ data: Post }>(`/posts/${encodeURIComponent(slug)}?locale=${encodeURIComponent(locale)}`).then((r) => r?.data ?? null);

Post page

app/blog/[slug]/page.tsx
import type { Metadata } from "next";
import { notFound, permanentRedirect } from "next/navigation";
import { getPost } from "@/lib/postream";
 
type Props = { params: Promise<{ slug: string }> };
 
export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const post = await getPost((await params).slug, "en-US");
  if (!post) return {};
  // Old slug: the page does the redirect; the metadata points to the new URL.
  return {
    title: post.seo.metaTitle,
    description: post.seo.metaDescription,
    alternates: { canonical: `/blog/${post.slug}` },
    openGraph: { title: post.seo.og.title, description: post.seo.og.description, type: "article", publishedTime: post.publishedAt },
  };
}
 
export default async function BlogPost({ params }: Props) {
  const { slug } = await params;
  const post = await getPost(slug, "en-US");
  if (!post) notFound();
  // The API followed the 301 of an old slug: send the visitor to the new URL
  // (308, which Google treats like the 301).
  if (post.slug !== slug) permanentRedirect(`/blog/${post.slug}`);
  return (
    <article>
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.bodyHtml }} />
    </article>
  );
}

List

app/blog/page.tsx
import Link from "next/link";
import { listPosts } from "@/lib/postream";
 
export default async function Blog() {
  const result = await listPosts("en-US");
  return (
    <ul>
      {result?.data.map((post) => (
        <li key={post.id}>
          <Link href={`/blog/${post.slug}`}>{post.title}</Link>
        </li>
      ))}
    </ul>
  );
}

hreflang for translations

translations brings the other published versions of the same post. Use it in alternates.languages:

alternates: {
  canonical: `/blog/${post.slug}`,
  languages: Object.fromEntries(post.translations.map((t) => [t.locale, `/${t.locale}/blog/${t.slug}`])),
},