Payload and Next.js: The Definitive Stack Guide for 2026

Payload and Next.js: The Definitive Stack Guide

A technical walkthrough of the Payload and Next.js stack — App Router, Local API, Live Preview, Next.js Proxy, Drizzle, Vercel, and six implementation patterns.

The Payload + Next.js stack runs Payload 3.0 inside the Next.js App Router as one codebase, one server, and one build pipeline. The architectural payoffs are the Local API for HTTP-free data access in Server Components, Live Preview plus a preview route built on Next.js draft mode, Next.js Proxy (called Middleware before Next.js 16) for internationalization routing, and Drizzle ORM with PostgreSQL for typed queries and auto-generated migrations. This guide walks the file structure, the four integration points with code, the Vercel production checklist, and six concrete implementation patterns.

Why Payload + Next.js is a strategic choice

Payload 3.0 shipped as a stable release in November 2024 with native Next.js App Router integration, and the significance is structural rather than promotional: Payload runs inside a Next.js application instead of beside it. There is no separate CMS service to deploy, version, and keep in compatibility lockstep with the frontend. One codebase, one server process, one build.

The single-codebase property has three concrete consequences. Types flow from the collection schema to React components without manual synchronization — a field renamed in the schema surfaces as a compile error in the component that consumed it, before it reaches an editor. Deployment collapses to one pipeline, removing the version-skew incident class where a schema change ships in one service and a deploy lag in the other breaks production. And the hosting story is npm install plus git push, because Vercel is first-class for both halves of the stack.

The honest boundary, stated once up front: every advantage below is real only if Next.js is genuinely your frontend. A team committed to a different framework gives most of it back and should weigh a content-API-first platform instead — the integration is a strength precisely because it is opinionated, and an opinionated tool is strong only inside the opinion. The same caveat applies to the runtime model. Running the CMS inside the Next.js process means the admin panel and the site share serverless function limits on a platform like Vercel; this is often not a problem at typical content scale, but it is a property to know rather than discover, and a build with an unusually heavy admin or very large media pipeline should size functions deliberately rather than assume the default is sufficient.

App Router integration — file structure and route mounting

The create-payload-app scaffold mounts Payload inside the App Router using route groups, which keep the admin and the public site fully separate while sharing one server.

code
src/app/
  (payload)/
    layout.tsx                        // Payload's root layout for the admin
    admin/[[...segments]]/page.tsx   // Payload admin UI mounted at /admin
    api/[...slug]/route.ts            // auto-generated REST endpoints
    api/graphql/route.ts              // auto-generated GraphQL endpoint
  (frontend)/
    layout.tsx                        // site root layout: fonts, theme, nav
    [locale]/[...slug]/page.tsx       // site pages

The (payload) route group owns the admin panel and the generated API surface — REST at /api/[collection] and /api/[collection]/[id], GraphQL at /api/graphql. The (frontend) group owns the site with its own layout, fonts, and components. In the scaffold, each route group has its own root layout — Payload's (payload)/layout.tsx manages the <html> tag for the admin, and (frontend)/layout.tsx does the same for the site — so the admin chrome and the site shell stay separate, and the editorial UI and the public design never leak into each other. This is the entire mounting model — there is no second application to wire up, because the route groups are the separation.

The route-group choice matters more than it looks. Because a route group does not add a path segment, /admin and /about are sibling URLs served by one application, not two deployments behind a reverse proxy. That is what makes the single-build claim true rather than aspirational: a schema change and the component that consumes it ship in the same commit, the same CI run, and the same deploy. The practical discipline this enables is that the content model and the frontend cannot drift into incompatible versions in production, because there is no version boundary between them to drift across — a class of incident that a decoupled CMS plus a separate frontend has to actively manage with contract tests and deploy ordering, and that this architecture removes by construction rather than by process.

The cost of the same property is that the admin and the site cannot scale independently. A team that needs the public site on aggressive edge caching and the admin on a long-running server has one process to tune for both, and the answer is usually correct caching headers on the public routes plus dynamic rendering on the admin routes rather than two services — but it is a design decision to make on purpose, not a default to inherit silently.

Local API — the performance unlock

The Local API is the property that most distinguishes this stack from a conventional decoupled setup, and it is the one to understand first. Instead of a Server Component issuing an HTTP request to a content API, it calls Payload directly as a function.

typescript
import { getPayload } from 'payload'
import config from '@payload-config'

export default async function PostsPage() {
  const payload = await getPayload({ config })

  const { docs: posts } = await payload.find({
    collection: 'posts',
    where: { _status: { equals: 'published' } },
    depth: 2, // populate related documents two levels deep
    limit: 20,
  })

  return <PostList posts={posts} />
}

The Local API documentation describes the core difference from an HTTP-based headless setup: the call interacts directly with your database, so there is no server latency or network speed to deal with. Two practical consequences follow. There is no network round trip — the call resolves in-process, so there is no content-API endpoint to rate-limit, time out, or fall over independently of the page that needs it. And depth: 2 populates related documents within the same Local API call, with no extra HTTP request per related record. The Payload concepts documentation frames the Local API the same way: direct-to-database access with no HTTP overhead.

There is one access-control subtlety that catches teams new to this model, and it is worth stating before it becomes an incident. The Local API bypasses the HTTP layer, and with it the access-control checks that run on the REST and GraphQL endpoints unless you opt back into them. A payload.find from a Server Component returns data according to the arguments you pass; overrideAccess defaults in a way that, combined with a public page, can return content the access rules would have filtered on the API. The rule is to be explicit: pass overrideAccess: false and a user when a query should respect collection access control, and reserve overrideAccess: true for trusted server contexts such as the preview route below. Treating the Local API as "the same query, just faster" is the mistake; it is the same query with the access boundary moved into your hands, which is power and responsibility in the same call.

The depth parameter deserves the same deliberate treatment. A high depth populates more relationships in a single call, which saves follow-up requests but adds database load and response size — the depth documentation names both; on a deeply linked content model, an unbounded depth can pull far more of the graph than a page renders. The practitioner habit is to set depth to exactly what the component reads — often 1 or 2 — and to use select to limit fields on list views, so the single-call advantage does not quietly become a single very large response.

Live Preview and draft mode — editorial workflow integration

Live Preview is where the editorial workflow meets the same single-process architecture. Payload's Live Preview loads the frontend in an iframe inside the admin panel and sends document changes to it, including unsaved ones, through window.postMessage. Its separate Preview feature links to a route that checks a secret and the signed-in user, enables Next.js draft mode, and serves draft content from the Local API; the route below is a simplified version that checks only the secret.

typescript
// app/(frontend)/api/preview/route.ts
import { timingSafeEqual } from 'node:crypto'
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
import { getPayload } from 'payload'
import config from '@payload-config'

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url)
  const secret = searchParams.get('secret') ?? ''
  const slug = searchParams.get('slug')

  const expected = Buffer.from(process.env.PREVIEW_SECRET ?? '')
  const given = Buffer.from(secret)
  // timingSafeEqual throws on different byte lengths, so check length first
  if (
    expected.length === 0 ||
    given.length !== expected.length ||
    !timingSafeEqual(given, expected)
  ) {
    return new Response('Invalid token', { status: 401 })
  }

  const draft = await draftMode()
  draft.enable()
  redirect(`/${slug}`)
}

The page then reads draft content by passing draft: true and overrideAccess: true to the same payload.find call shown earlier, so there is no second rendering path to maintain. Because the preview route runs in the same Next.js process, editors see changes without a redeploy — the Next.js draft mode cookie switches the existing route into draft rendering rather than spinning up separate preview infrastructure. The token check is the security boundary and it is not optional: the secret comparison is what prevents an unauthenticated request from reading unpublished content, and it should be a constant-time comparison against an environment secret, as in the timingSafeEqual check above, never a value derived from the request.

Two operational details turn this from a demo into a production workflow. First, the draft-mode cookie has a lifetime, and an editor who enables preview and never disables it carries a draft-rendering cookie into normal browsing — so a corresponding route that calls draftMode().disable() and a clear exit affordance in the preview UI are part of the feature, not an afterthought. Second, PREVIEW_SECRET is a credential and should rotate on the same cadence as other secrets; because the comparison is a single environment value rather than a per-user token, a leaked secret exposes every draft until it is rotated, which is acceptable for an internal editorial tool but should be a conscious acceptance rather than an unexamined default. For higher-sensitivity content, scoping the token to a collection or signing it with an expiry is a reasonable hardening step that fits the same route handler without changing the architecture.

Proxy (formerly Middleware) — i18n routing and geolocation

Next.js Proxy — the file convention called Middleware before Next.js 16 — executes before routes are rendered, on the Node.js runtime by default, which makes it the right place to decide locale, geography, and routing without paying for a server render to discover them.

typescript
// proxy.ts (middleware.ts before Next.js 16)
import { NextRequest, NextResponse } from 'next/server'

const LOCALES = ['en', 'ko', 'ja', 'de']
const DEFAULT_LOCALE = 'en'

export function proxy(req: NextRequest) {
  const { pathname } = req.nextUrl
  const hasLocale = LOCALES.some(
    (l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`),
  )
  if (hasLocale) return NextResponse.next()

  const cookieLocale = req.cookies.get('NEXT_LOCALE')?.value
  const country = req.headers.get('x-vercel-ip-country')
  const accept = req.headers.get('accept-language')?.split(',')[0]?.split('-')[0]

  const locale =
    (cookieLocale && LOCALES.includes(cookieLocale) && cookieLocale) ||
    (accept && LOCALES.includes(accept) && accept) ||
    DEFAULT_LOCALE

  return NextResponse.redirect(new URL(`/${locale}${pathname}`, req.url))
}

export const config = { matcher: ['/((?!_next|api|admin|.*\\..*).*)'] }

Locale is resolved from an explicit cookie first, then the Accept-Language header, with a geographic signal such as Vercel's x-vercel-ip-country available as a fallback or for geo-specific routing. The URL settles on the canonical /[locale]/[...path] shape that the App Router file structure expects, so Payload's localized content reads cleanly against the resolved locale. The same proxy layer is where A/B test assignment, feature-flag gating, and geo-blocking belong — they are all pre-render routing decisions, and consolidating them there keeps them out of the page components.

Drizzle ORM with PostgreSQL — typed queries and migrations

Payload's official PostgreSQL adapter is built on Drizzle ORM and node-postgres. The query builder is typed end to end, and the migration story is the part that matters operationally.

Migrations are generated from collection schema changes with payload migrate:create, which produces a TypeScript migration file and a JSON schema snapshot. Both must be committed together. payload migrate runs the .ts file; the .json snapshot is what the next migrate:create diffs against, so a snapshot left out of the commit can make the next generated migration repeat schema changes that are already applied. Treat the snapshot pair as a single indivisible commit, and verify before committing that a freshly generated migrate:create reports an empty diff — an empty diff is the signal that the snapshot matches the schema.

The other migration hazard is the development push. In development, the ORM can push schema changes directly to the database for fast iteration, which writes a development marker into the migrations table. If that marker reaches an environment that then runs payload migrate, the migrate step will not run migrations unattended: it either asks for interactive confirmation ("It looks like you've run Payload in dev mode…") or, when prompting is turned off, cancels the run unless warnings are force-accepted. The defensive pattern is to force a production runtime for any script that calls the Local API against a real database — set the runtime environment to production before the database connects — so the dev push path is never taken outside of local iteration. A schema change is also diffable by design: a reviewer reading the generated migration sees exactly which column was added, renamed, or constrained, which is the audit property a UI-configured CMS cannot offer after the fact. Rolling back is a deliberate payload migrate:down, not an implicit behavior, so a destructive change is reversible but never automatic.

ItemSettingReason
ORMDrizzle (the basis of Payload's official PostgreSQL adapter)Typed query builder, fast, schema-derived migrations
Migration generation`payload migrate:create`Produces a `.ts` migration and a `.json` snapshot — commit both
Migration apply`payload migrate` in the build stepRuns against the production database before the Next.js build
Database connection`DATABASE_URL_DIRECT` (example name) pointing at your provider's poolerOn Supabase, transaction mode (port 6543) does not support prepared statements

Vercel deployment — production checklist

Vercel is first-class for the whole stack, but production has a small number of settings that are not optional and a known failure mode if any is missed.

code
DATABASE_URL_DIRECT=postgres://...          # example name; pooler mode: see below
PAYLOAD_SECRET=...                            # signing secret, rotate carefully
NEXT_PUBLIC_SERVER_URL=https://...            # client-visible server URL
PREVIEW_SECRET=...                            # preview route secret

DATABASE_URL_DIRECT is an example name — use whatever variable your Payload config reads (Payload's Postgres examples use DATABASE_URL) — and point it at a pooler mode your provider and driver support. The port numbers are provider-specific: on Supabase, port 5432 reaches Postgres directly or the Supavisor pooler in session mode, and port 6543 reaches its transaction-mode poolers, which do not support prepared statements. Supabase points serverless and edge functions at transaction mode with prepared statements turned off in the connection library, so check which mode your driver settings fit rather than assuming one. The next.config.js image domain allowlist must include the hostnames you serve images from, such as a Cloudinary or S3 domain, or next/image rejects them at render. The build command runs the migration before the Next.js build, so the production database is migrated as part of the deploy rather than as a separate manual step. The Vercel deployment documentation covers the platform mechanics; the stack-specific risk is concentrated entirely in the database connection string and the migration-snapshot pairing from the previous section.

Six concrete implementation patterns

The four integration points above compose into the patterns most production builds actually need. Each is a combination of stack primitives rather than a new concept.

Pattern one is a localized marketing site: Next.js i18n routing through the proxy above, paired with Payload Localization so one content model serves every locale from one record. Pattern two is a product catalog with regional pricing: Payload Collections model the catalog, and Incremental Static Regeneration revalidates pages on a schedule or on demand so pricing changes propagate without a full rebuild. Pattern three is editorial publishing with the preview workflow already shown — Live Preview plus a draft-mode route behind a preview secret, no separate preview environment. Pattern four is multi-tenant SaaS: a single Payload instance with a tenant field and access control scoping every query, rather than one deployment per tenant. Pattern five is RAG-ready content: Payload's Enterprise auto-embedding feeding a retrieval layer, with the Vercel AI SDK streaming responses to the client — the implementation depth of the embedding pipeline itself belongs to a dedicated treatment and is referenced here only as a stack pattern. Pattern six is an e-commerce front: Payload's official e-commerce template (marked beta as of Oct 2026, with the Stripe adapter configured by default), with Next.js Server Actions handling cart and checkout mutations without a separate API tier.

The common thread across all six is that none of them adds a service. Each is the same single codebase, the same Local API, and the same deployment pipeline reconfigured for a different requirement, which is the entire reason the integration depth matters: the patterns are compositions of the stack, not bolt-ons to it.

Phase 1 deliverables and acceptance criteria

  • Scaffold with create-payload-app and confirm the (payload) and (frontend) route groups render /admin and the site independently before adding any collection.
  • Convert one Server Component data fetch to the Local API with an explicit depth, and confirm related documents are populated only to the depth the component reads.
  • Wire the draft-mode preview route end to end with its secret check, and verify draft content renders only behind a valid PREVIEW_SECRET.
  • Generate one migration with payload migrate:create, confirm the .ts and .json snapshot pair, and verify a re-run reports an empty diff before committing.
  • Set the production database connection string to a pooler mode your provider and driver support (on Supabase, transaction mode requires prepared statements to be off) and confirm the build runs payload migrate before next build.
Project Inquiry