# Link previews in Next.js

> Build a server-side link preview endpoint with linkpeek and the Next.js App Router: a Route Handler, input checks, caching and safe rendering.

Browsers can't read other sites' HTML, so the preview runs in a Route Handler. It checks the input, calls `preview()`, and when something fails only the card falls back, not the page.

## Create the route handler

```bash
npm install linkpeek
```

```ts
// app/api/preview/route.ts
import { preview } from "linkpeek";
import { type NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
	const url = request.nextUrl.searchParams.get("url");
	if (!url) {
		return NextResponse.json({ error: "Missing url" }, { status: 400 });
	}

	try {
		const result = await preview(url);
		return NextResponse.json(result, {
			headers: {
				"Cache-Control":
					result.statusCode >= 200 && result.statusCode < 300 ? "public, s-maxage=3600" : "no-store",
			},
		});
	} catch {
		return NextResponse.json({ error: "Preview unavailable" }, { status: 422 });
	}
}
```

## Cache successful responses

Without a cache, every render waits on the target site. Cache only successful previews, pick a TTL that suits your app, and consider coalescing requests when many users load the same URL at once.

Don't forward cookies, authorization headers, internal tokens or caller-provided credentials to the target URL.

## Render metadata as untrusted data

React escapes text by default. Keep it that way. Allow images only from origins covered by your image policy, treat canonical and media URLs as untrusted links, and provide a hostname-only fallback card when extraction fails.

Related: [API reference](https://linkpeek.js.org/api/) · [Security model](https://linkpeek.js.org/security/) · [Cloudflare Workers](https://linkpeek.js.org/integrations/cloudflare-workers/) · [Complete example on GitHub](https://github.com/thegruber/linkpeek/tree/main/examples/nextjs-app-router)
