Skip to Content
Takumi

TanStack Start

Generate Open Graph images or PDFs from React components in TanStack Start server file routes.

Add a server file route that returns an ImageResponse. The example reads the title and description from the query string.

Install Takumi

npm i takumi-js

Create a server file route

A file route defines HTTP handlers under server.handlers.

src/routes/og-image.tsx
import { createFileRoute } from "@tanstack/react-router";
import ImageResponse from "takumi-js/response";

export const Route = createFileRoute("/og-image")({
  server: {
    handlers: {
      GET({ request }) {
        const url = new URL(request.url);
        const title = url.searchParams.get("title") ?? "Takumi + TanStack Start";
        const description =
          url.searchParams.get("description") ?? "Render OG images from a route handler.";

        return new ImageResponse(
          <div
            style={{
              width: "100%",
              height: "100%",
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              padding: "64px",
              backgroundImage: "linear-gradient(to bottom right, #eff6ff, #dbeafe)",
            }}
          >
            <p style={{ fontSize: 72, fontWeight: 700, color: "#111827" }}>{title}</p>
            <p style={{ fontSize: 42, fontWeight: 500, color: "#4b5563" }}>{description}</p>
          </div>,
          {
            width: 1200,
            height: 630,
          },
        );
      },
    },
  },
});

Request the endpoint

Visit /og-image?title=Hello&description=From%20TanStack%20Start.

Render a PDF

takumi-pdf renders a React component to a PDF from a server file route. The [.] in the file name escapes the dot, so the route answers at /invoice.pdf.

npm i takumi-pdf
src/components/Invoice.tsx
export default function Invoice({ id }: { id: number }) {
  return (
    <main style={{ padding: 48 }}>
      <h1>Invoice {id}</h1>
      <p>Total: $1,290</p>
    </main>
  );
}
src/routes/invoice[.]pdf.tsx
import { createFileRoute } from "@tanstack/react-router";
import { render } from "takumi-pdf";
import Invoice from "../components/Invoice";

export const Route = createFileRoute("/invoice.pdf")({
  server: {
    handlers: {
      async GET() {
        const pdf = await render(<Invoice id={1042} />, { size: "a4" });

        return new Response(pdf, {
          headers: { "content-type": "application/pdf" },
        });
      },
    },
  },
});

The route also runs on Cloudflare Workers through @cloudflare/vite-plugin. See Pagination to control page breaks.

Next steps

Style the layout with Styles, load fonts with Fonts, and see ImageResponse for every option.

Last updated on