Next.js
The Quickstart talks to the Knit API straight from the browser (Direct mode). On Next.js you can do better: keep the reader's session in an HttpOnly cookie on your own domain (BFF mode), render posts on the server, and give each post its own page with metadata.
Relay requests through your site
Add a catch-all route handler. It forwards the browser's requests to Knit and stores the session in an HttpOnly cookie, so scripts on the page never see the token.
import { createKnitHandler } from "@knit/react/next";
// Relays the browser's requests to Knit and keeps the session in an HttpOnly cookie
export const { GET, POST, PUT, PATCH, DELETE } = createKnitHandler();The handler and the server client read these environment variables:
| Variable | Use |
|---|---|
KNIT_API_URL | API URL. Falls back to NEXT_PUBLIC_KNIT_API_URL. |
KNIT_PUBLISHABLE_KEY | Publishable Key. Falls back to NEXT_PUBLIC_KNIT_PUBLISHABLE_KEY. |
KNIT_SECRET_KEY | Secret Key, only for sites that require it. Never expose it to the browser. |
KNIT_SITE_ORIGIN | Your site's origin. Always set it in production: the server client falls back to http://localhost:3000, and the route handler to the request's origin (wrong behind a reverse proxy). |
Wrap pages in a client provider
KnitProvider is a Client Component, so wrap it in a small component of your own. Set bffBasePath to the route above, and refresh server data when the reader signs in or out.
"use client";
import { KnitProvider, type KnitSiteBootstrapResponse } from "@knit/react";
import { useRouter } from "next/navigation";
import type { ReactNode } from "react";
export function KnitShell({
initialData,
children,
}: {
initialData: KnitSiteBootstrapResponse | null;
children: ReactNode;
}) {
const router = useRouter();
return (
<KnitProvider
publishableKey={process.env.NEXT_PUBLIC_KNIT_PUBLISHABLE_KEY ?? ""}
apiUrl={process.env.NEXT_PUBLIC_KNIT_API_URL ?? ""}
bffBasePath="/api/knit"
initialData={initialData}
// Re-render server data (drafts, the owner's tools) after sign-in or sign-out
onAuthChange={() => router.refresh()}
>
{children}
</KnitProvider>
);
}Render the list on the server
Create a server client with createKnitServerClient and pass the reader's session cookie with each request. getBootstrap returns the site settings and the session; pass it as initialData so the first render needs no request from the browser.
import { createKnitServerClient } from "@knit/react/next";
import { cookies } from "next/headers";
/** The server-side client, and the reader's session token from the HttpOnly cookie */
export async function getKnitServer() {
const knitServer = createKnitServerClient();
const cookieStore = await cookies();
const sessionToken = cookieStore.get(knitServer.cookieName)?.value ?? null;
return { knitServer, sessionToken };
}import { PostList } from "@knit/react/ui";
import { getKnitServer } from "../../lib/knit-server";
import { KnitShell } from "./knit-shell";
export default async function BlogPage() {
const { knitServer, sessionToken } = await getKnitServer();
const initialData = await knitServer.getBootstrap({ sessionToken });
const initialPosts = await knitServer.listPosts({
sessionToken,
// The space is required. A new site starts with a public space named "default"
space: "default",
// The owner also sees drafts
status: initialData.session.role === "owner" ? "all" : "published",
pageSize: 10,
});
return (
<KnitShell initialData={initialData}>
<PostList space="default" initialPosts={initialPosts} postBasePath="/blog" pageSize={10} />
</KnitShell>
);
}Every server call takes the space it reads from (listPosts, listCollections and getPostBySlug). Drafts are only returned to the owner, so ask for status: "all" only when the session's role is owner. Set postBasePath so cards link to your post pages.
Add a page for each post
getPostBySlug returns the post, or null when it does not exist or the reader cannot see it. generateKnitPostMetadata builds the title, description, Open Graph and Twitter tags from the post.
import { generateKnitPostMetadata } from "@knit/react/next";
import { PostDetail } from "@knit/react/ui";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { cache } from "react";
import { getKnitServer } from "../../../lib/knit-server";
import { KnitShell } from "../knit-shell";
interface PageProps {
params: Promise<{ slug: string }>;
}
// Fetch the post once for both generateMetadata and the page
const loadPost = cache(async (slug: string) => {
const { knitServer, sessionToken } = await getKnitServer();
return knitServer.getPostBySlug(slug, { sessionToken, space: "default" });
});
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const { slug } = await params;
return generateKnitPostMetadata(await loadPost(slug), { siteName: "My Blog" });
}
export default async function PostPage({ params }: PageProps) {
const { slug } = await params;
const post = await loadPost(slug);
if (!post) notFound();
const { knitServer, sessionToken } = await getKnitServer();
const initialData = await knitServer.getBootstrap({ sessionToken });
return (
<KnitShell initialData={initialData}>
<PostDetail initialPost={post} backHref="/blog" postBasePath="/blog" showComments />
</KnitShell>
);
}showComments adds the comment section under the post. Wrap the fetch in React's cache so generateMetadata and the page share one request.