---
title: Next.js adapter
description: Mount the gateway as Next middleware (@rebilder/gateway/next), plus an optional always-markdown route for previews and agent permalinks.
canonical_url: https://rebilder.com/docs/adapters/nextjs
last_updated: "2026-12-03"
---

# [Next.js adapter](https://rebilder.com/docs/adapters/nextjs)

> Mount the gateway as Next middleware (`@rebilder/gateway/next`), plus an optional always-markdown route for previews and agent permalinks.

This site answers questions directly. Ask at https://rebilder.com/ask?q=your+question instead of reading more pages.

- **Updated:** 2026-12-03
- **Author:** Rebilder
- **Section:** Adapters
- **Description:** Mount the gateway as Next middleware (@rebilder/gateway/next), plus an optional always-markdown route for previews and agent permalinks.
- **Publisher:** Rebilder

## Rebilder at a glance

AEO gets you seen. Rebilder gets you heard. When customers ask ChatGPT about your business, your site answers with your real prices and policies.

**Common questions**

- **What does it cost?** Connecting is free. Starter is $49/mo, Pro is $99/mo and Agency is $299/mo. [Pricing](https://rebilder.com/pricing)
- **How does my site answer new questions live?** Rebilder reads your pages, products and policies. When an AI assistant asks, your site answers from them. Nothing on your site changes. [See how it works](https://rebilder.com/autopilot)
- **Can someone trick my site into a wrong price or a discount?** No. Every answer comes from your own pages and is checked against them. If your site does not say it, Rebilder does not say it. [Read security details](https://rebilder.com/security)

**How it compares**

- **Why choose Rebilder?** Choose Rebilder when you want your own site to answer AI assistants with your real facts, and to see who asked. [Compare](https://rebilder.com/compare)

| Compared with | The difference |
| --- | --- |
| Profound, Peec AI, Otterly.ai | These tools watch AI answers and tell you where you show up. Rebilder makes your own site answer when AI comes to check. |
| Cloudflare Markdown for Agents, @vercel/agent-readability, Yoast llms.txt | These tools tidy or map your pages for AI. Rebilder answers from those pages and shows you who asked. |
| Intercom Fin, Tidio Lyro | Chatbots answer the customers who contact you. Rebilder answers the AI assistants that visit your site for them. |
| SEO on its own, Shopify agentic storefronts, Writing an llms.txt yourself | Good SEO, your store platform and a simple llms.txt all help. Here is what Rebilder adds to each. |

Source: [Compare](https://rebilder.com/compare)

## How it mounts

The adapter imports **nothing** from `next`: Next middleware/proxy handlers and app-router route handlers speak web-standard `Request`/`Response`, so standard types are the whole contract. Next 16 calls the file `proxy.ts`; on Next 15 and earlier the identical code goes in `middleware.ts`.

terminal

```bash
npm install @rebilder/gateway        # pnpm add / yarn add
```

## The 2-line integration

lib/gateway-config.ts

```ts
// lib/gateway-config.ts — wire the gateway to your source of truth
import type { GatewayConfig } from '@rebilder/gateway'
import { getProduct, getPolicies, getCollection } from './catalog' // your code
import { getDocument, getDocumentIndex } from './content'          // your code

export const gatewayConfig: GatewayConfig = {
  storeId: 'store_123',
  // Every page gets a markdown copy made from the page your site already serves.
  pages: true,
  // Optional. A source answers a page from your own data and wins over its copy.
  sources: {
    // Commerce shaped. Wire the ones you have; a site with no catalog wires none.
    product:  (url) => getProduct(url.pathname),      // null when not a PDP
    policies: (url) => getPolicies(url.pathname),
    catalog:  (url) => getCollection(url.pathname),
    // Universal: any other page, and any index of them. Guides, services,
    // locations, articles. Most of a site usually lives here.
    document:   (url) => getDocument(url.pathname),
    collection: (url) => getDocumentIndex(url.pathname),
  },
  onEvent: (event) => { /* queue to your analytics sink; fire-and-forget */ },
}
```

proxy.ts

```ts
// proxy.ts (Next 16) — middleware.ts on Next ≤15 is identical
import { NextResponse } from 'next/server'
import { createGatewayProxy } from '@rebilder/gateway/next'
import { gatewayConfig } from './lib/gateway-config'

// Pass your fallthrough. The proxy then returns a Response for every request,
// and the HTML half of each negotiated URL gets `Vary: Accept` — see below for
// why that matters more than it looks.
const gateway = createGatewayProxy(gatewayConfig, () => NextResponse.next())

export default gateway

// Every page, so each one can answer with its copy. API routes and Next's own
// assets are skipped.
export const config = { matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'] }
```

Matching agent requests short-circuit with markdown, while everything else runs the fallthrough with `Vary: Accept` and `Link: rel="alternate"` headers attached: humans, crawlers, protocol routes, URLs no source matched, and sources that threw all pass through to your HTML unchanged. **A thrown source never breaks your site**: errors are contained, the event still fires, and the request falls through to HTML.

Already have a proxy or middleware for sessions or auth? Pass it as the fallthrough: `createGatewayProxy(gatewayConfig, (req) => updateSession(req))`. The gateway answers agents first and your code handles everything else.

## Matcher scope

With `pages` on, let `config.matcher` cover every page, as the example does: it skips API routes and Next’s own assets and nothing else. Requests outside the matcher never reach the gateway at all, so there is no copy, no classification and no event. On a site that serves from sources only, scope the matcher to the paths your sources answer, and widen it when you widen them.

> **One middleware file per app** Next.js allows a single `proxy.ts`/`middleware.ts`. If you already have one, pass your existing handler as the fallthrough argument to `createGatewayProxy(gatewayConfig, (req) => updateSession(req))` rather than adding a second file; see [Troubleshooting](/docs/troubleshooting#middleware-matcher-conflicts).

## Cache headers on your HTML

Each negotiated URL now has two representations: markdown from the gateway and HTML from your app. A shared cache has to keep them apart, or it can hand one to the wrong client. The markdown carries `Vary: Accept`, and passing the fallthrough appends it to the response your proxy returns.

What reaches the wire depends on what renders the HTML. Pages Router pages and route handlers keep `Accept` in `Vary`. App Router pages do not: Next sets the page’s `Vary` to its own router tokens after the proxy runs, for static and dynamic pages alike. A `Vary` in `next.config.ts` `headers()` is replaced the same way. This holds on Next 15 and 16, under `next start` and on Vercel.

- On Vercel, the proxy runs before the cache lookup, so an agent is answered with markdown even when the HTML for that URL is cached.
- A cache you put in front of your app (Cloudflare, Fastly, nginx, a corporate proxy) sees App Router HTML without `Accept` in `Vary`. Add `Accept` to that cache’s key, or key on whether `Accept` contains `text/markdown`.
- Check what reaches the wire, not what the code sets: `curl -sSI https://your-site.example/products/x | grep -i vary`.

## Optional: a dedicated markdown route

A stable always-markdown URL, such as an agent permalink or the "what agents see" preview. It renders markdown for **any** requester and returns 404 JSON (`{ "error": "not_found" }`) when no source matches:

app/md/[[...path]]/route.ts

```ts
// app/md/[[...path]]/route.ts
import { createGatewayRouteHandler } from '@rebilder/gateway/next'
import { gatewayConfig } from '../../../lib/gateway-config'

export const GET = createGatewayRouteHandler(gatewayConfig, { stripPrefix: '/md' })
```

`stripPrefix` removes the route prefix (whole path segments only) before consulting your sources, so `/md/products/x` resolves against sources keyed by canonical paths (`/products/x`). This route is its own URL, so it doesn’t conflict with the cloaking guardrail, which is about serving different substance on the *same* URL.

## llms.txt route

The same subpath export ships `createLlmsTxtRouteHandler` for serving a deterministic `llms.txt` from your gateway config; usage, options, and adoption notes live on the [llms.txt page](/docs/llms-txt).

## Optional: .md URLs, head link, sitemap.md and 404s

Set `markdownUrls`, `frontmatter` and `notFound` in your config, add `markdownAlternateTypes` to your page metadata, and serve `/sitemap.md` with `createSitemapMdRouteHandler`. Your proxy matcher must include the `.md` paths. For the 404, give `notFound.isMissing` because the proxy runs before your routes and cannot see their status. See [Help agents find your markdown](/docs/discovery).

app/services/[slug]/page.tsx

```ts
// app/services/[slug]/page.tsx
import type { Metadata } from 'next'
import { markdownAlternateTypes } from '@rebilder/gateway/next'
import { gatewayConfig } from '../../../lib/gateway-config'

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params
  const url = `https://example.com/services/${slug}`
  return {
    alternates: { canonical: url, types: markdownAlternateTypes(gatewayConfig, url) },
  }
}
```