ForgeWP

Next.js App Router Adapter

Author WordPress themes with standard Next.js App Router code, export into native WordPress theme ZIPs, or deploy decoupled against live WordPress REST.

The Next.js App Router adapter (frameworkAdapter: "nextjs") lets you build WordPress themes using standard Next.js App Router conventions (src/app/, next/link, next/image, next/font, Turbopack) and choose between two deployment modes from the exact same codebase:

  1. Native WordPress Theme Export (default): Runs forgewp export to compile your App Router routes, shared layout chrome, CSS, defineBlock Gutenberg blocks, next/image assets, next/font .woff2 subsets, and client islands into a standalone WordPress theme ZIP. No Node.js server is required in production.
  2. Decoupled Next.js Frontend: Runs your app as a live Next.js server (FORGEWP_DEPLOYMENT_MODE=decoupled + FORGEWP_WP_URL=https://your-wp-site) reading live WordPress REST content, forgewp_route_id permalinks, menus, site info, and serialized Gutenberg blocks.

1. Quick Start

Scaffold a new Next.js ForgeWP project with create-forgewp:

Terminal
# TypeScript (default)
pnpm create forgewp my-next-theme --adapter nextjs

# Or JavaScript + JSX
pnpm create forgewp my-next-theme --adapter nextjs --js

cd my-next-theme
pnpm dev      # Start Next.js 16 dev server (Turbopack) with local cms/mock-data fixtures
pnpm export   # Compile and package .forgewp/my-next-theme.zip for WordPress

Adding ForgeWP to an Existing Next.js App (forgewp init)

If you already have a Next.js App Router codebase (TypeScript or JavaScript), run forgewp init to check native vs. decoupled compatibility upfront and wire ForgeWP non-destructively:

Terminal
# Preview compatibility report and planned file changes without writing
pnpm forgewp init --dry-run

# Wrap next.config.* with withForgeWP(), create wp.config.{ts,js}, cms/mock-data.{ts,js}, src/lib/content.{ts,js}, and .env.example
pnpm forgewp init
  • Marketing / static Next.js repos without request-time server APIs are marked ready for native WordPress theme export.
  • Full-stack Next.js repos (using middleware.ts, route.ts, Server Actions, Prisma/Supabase, or catch-all [...slug] routes) receive an upfront recommendation to use decoupled mode (pnpm dev:decoupled + FORGEWP_WP_URL) rather than native PHP export.

2. Configuration (next.config.ts & wp.config.ts)

Wrap your Next.js config with withForgeWP() imported from @forgewp/react/next (also re-exported from @forgewp/react/config):

next.config.ts
1import type { NextConfig } from "next"
2import { withForgeWP } from "@forgewp/react/next"
3
4const nextConfig: NextConfig = withForgeWP(
5  {
6    // Your standard Next.js options
7  },
8  {
9    // Optional: automatically wrap interactive 'use client' components in <Hydrate>
10    // during native WordPress export (FORGEWP_NATIVE_EXPORT=1).
11    autoHydrate: true, // or { defaultTrigger: "visible" | "load" | "idle" | "interaction" }
12  },
13)
14
15export default nextConfig

withForgeWP() configures five things automatically so you don't have to:

  1. Boundary-selected output mode: Sets output: "export" for native WordPress extraction, and omits it when FORGEWP_DEPLOYMENT_MODE=decoupled is active.
  2. Turbopack & Webpack compatibility: Configures both turbopack.rules and webpack.resolve.extensionAlias so plain next dev / next build works on Next.js 16 Turbopack with zero --webpack flags.
  3. transpilePackages: Includes @forgewp/react automatically.
  4. Native image bridge: Sets images.unoptimized = true only during FORGEWP_NATIVE_EXPORT=1 so ForgeWP's Sharp WebP pipeline can optimize <Image /> tags (while keeping Next.js's /_next/image optimizer in decoupled mode).
  5. Opt-in autoHydrate: When enabled, detects interactive 'use client' components during native export and wraps them in <Hydrate> automatically.

In wp.config.ts (or wp.config.js), set frameworkAdapter: "nextjs":

wp.config.ts
1import { defineConfig } from "@forgewp/compiler/define-config"
2
3export default defineConfig({
4  configVersion: 1,
5  name: "My Next Theme",
6  slug: "my-next-theme",
7  version: "0.1.0",
8  description: "A WordPress theme built with Next.js App Router and ForgeWP.",
9  textDomain: "my-next-theme",
10  frameworkAdapter: "nextjs",
11})

3. Reading WordPress Data in Server Components (@forgewp/react)

Next.js App Router pages are React Server Components by default — they cannot call React client hooks like useWpTitle() or useWpMenu(). Instead, Next.js projects import createWpServerClient and server-safe components from @forgewp/react.

Every new Next.js starter comes pre-wired with src/lib/content.ts (or content.js):

src/lib/content.ts
1import { createWpServerClient } from "@forgewp/react"
2import { mockData } from "../../cms/mock-data"
3
4export const wpClient = createWpServerClient({
5  fixtures: mockData,
6})
7
8export async function getPageContent(slug: string) {
9  return wpClient.getLivePage(slug)
10}

You write your pages once, and wpClient automatically switches behavior across all three modes — you never need to write if (isDecoupled) checks or manual fetch('/wp-json/...') calls:

Table · 3 columns
Mode
Trigger
What wpClient Does
Local Development
Default (pnpm dev, no FORGEWP_WP_URL)
Reads typed fixtures from cms/mock-data.ts (defineWpPosts) and cms/menus.ts (defineWpMenus).
Decoupled WordPress
FORGEWP_WP_URL=https://your-wp-site
Fetches live WordPress REST content, route permalinks (/wp-json/forgewp/v1/routes), menus (/menus/<location>), site info (/site-info), and forgewp_blocks.
Native WordPress Export
FORGEWP_NATIVE_EXPORT=1 (set automatically by forgewp export)
Emits ForgeWP compile tokens (__FORGEWP_THE_TITLE__, __FORGEWP_THE_CONTENT__, __FORGEWP_HOME_URL__, etc.) and <WpMenu /> / <WpQueryLoop /> markers that compile into native WordPress PHP template tags.
src/app/layout.tsx
1import { WpMenu } from "@forgewp/react"
2import { wpClient } from "@/lib/content"
3
4export default async function RootLayout({
5  children,
6}: {
7  children: React.ReactNode
8}) {
9  const [site, primaryMenu] = await Promise.all([
10    wpClient.getSiteInfo(),
11    wpClient.getMenu("primary"),
12  ])
13
14  return (
15    <html lang={site.language}>
16      <body>
17        <header>
18          <a href={site.homeUrl}>{site.name}</a>
19          <WpMenu location="primary" items={primaryMenu} className="nav" />
20        </header>
21        {children}
22      </body>
23    </html>
24  )
25}

4. Client Interactivity & Gutenberg Blocks

  • Gutenberg Blocks (defineBlock + WpEditable): Place blocks in src/blocks/*.tsx (or .jsx) with 'use client' at the top. During native export, ForgeWP compiles them to blocks/<slug>/block.json, render.php, and assets/forgewp-editor.js wired to your packaged Next.js CSS.
  • Editable Regions (<BlockArea />): Import BlockArea from @forgewp/react in App Router Server Components and pass content={page.content} for local/decoupled preview. Native export compiles <BlockArea /> to <?php the_content(); ?>.
  • Client Islands (<Hydrate> & autoHydrate): Wrap interactive 'use client' components in <Hydrate id="counter-island"> (imported from @forgewp/react) or enable withForgeWP({}, { autoHydrate: true }):
    • Automatically excluded from auto-hydration: Server Components, Gutenberg blocks (src/blocks/ or defineBlock), purely static 'use client' components, and any file containing /* @forgewp-no-hydrate */.
    • Active islands are bundled via esbuild into assets/islands/* with a shared react-runtime.js — zero _next/static/chunks/* are shipped in native WordPress themes, and static pages ship 0 KB of client JS.

5. Dynamic Routes ([slug]) & WordPress Archives

Single-segment dynamic App Router routes that export generateStaticParams() compile directly into WordPress's single.php / single-<cpt>.php hierarchy, and paired listing routes compile into archive.php / archive-<cpt>.php:

  • src/app/blog/[slug]/page.tsx → single.php (postType: "post")
  • src/app/blog/page.tsx → archive.php
  • src/app/projects/[slug]/page.tsx (matching postTypes.project in wp.config.ts) → single-project.php
  • src/app/projects/page.tsx → archive-project.php
src/app/blog/[slug]/page.tsx
1import { BlockArea } from "@forgewp/react"
2import { wpClient } from "@/lib/content"
3
4export async function generateStaticParams() {
5  return wpClient.getStaticParams("post")
6}
7
8export default async function SinglePostPage({
9  params,
10}: {
11  params: Promise<{ slug: string }>
12}) {
13  const { slug } = await params
14  const post = await wpClient.getLivePost("post", slug)
15
16  return (
17    <main>
18      <h1>{post?.title}</h1>
19      <BlockArea name="post-content" content={post?.content} />
20    </main>
21  )
22}

For archive listings, render posts with <WpQueryLoop> from @forgewp/react:

src/app/blog/page.tsx
1import { WpQueryLoop } from "@forgewp/react"
2import { wpClient } from "@/lib/content"
3
4export default async function BlogArchivePage() {
5  const posts = await wpClient.getPosts("post")
6
7  return (
8    <main>
9      <h1>Blog</h1>
10      <WpQueryLoop
11        postType="post"
12        posts={posts}
13        renderItem={(post) => (
14          <article key={post.id}>
15            <h2>
16              <a href={post.permalink}>{post.title}</a>
17            </h2>
18            <p>{post.excerpt}</p>
19          </article>
20        )}
21      />
22    </main>
23  )
24}

6. Images (next/image) & Fonts (next/font)

Write standard Next.js next/image and next/font (next/font/google or next/font/local) with zero ForgeWP-specific rewrites:

  • next/image → Sharp WebP Pipeline: During native export, ForgeWP's Asset Graph scans <Image src="/hero.png" ... /> and static ES imports, generates responsive WebP srcset variants under assets/images/, and rewrites rendered <img> tags to get_theme_file_uri(...) — with zero /_next/image URLs left behind. In decoupled mode, Next.js's built-in optimizer stays active.
  • next/font → Self-Hosted assets/fonts/: Build-time .woff2 subsets are copied into assets/fonts/ with theme-relative CSS url()s, preserving font.className, font.variable, font-display: swap, and fallback metrics.

7. Optional ForgeWP Modules (Forms, SEO, Auth, WooCommerce)

All four optional ForgeWP modules work on the Next.js adapter:

  • Native Forms (cms/forms/*.ts or .js): Define forms using defineWpForm(). ForgeWP generates the forgewp_submission CPT and /wp-json/forgewp/v1/forms/<slug>/submit REST endpoint in functions.php, and lints form usage across src/, root app/, and root components/.
  • SEO (export const metadata + Yoast / Rank Math / SEOPress): Next.js export const metadata (title, description, OpenGraph, Twitter cards, JSON-LD) flows into forgewp-static/head.html behind if ( ! forgewp_seo_plugin_active() ), so WordPress SEO plugins take over automatically when active.
  • Auth (WpRequireAuth, WpAuthGate): Import Server-Component-safe WpRequireAuth and WpAuthGate from @forgewp/react to protect pages or gate sections by login status or WordPress capability without client hooks:
src/app/dashboard/page.tsx
1import { WpRequireAuth, WpAuthGate } from "@forgewp/react"
2
3export default function DashboardPage() {
4  return (
5    <WpRequireAuth redirect="/login" allowed="edit_posts">
6      <main>
7        <h1>Editor Dashboard</h1>
8        <WpAuthGate allowed="manage_options" fallback={<p>Standard editor view</p>}>
9          <p>Administrator controls</p>
10        </WpAuthGate>
11      </main>
12    </WpRequireAuth>
13  )
14}
  • WooCommerce (@forgewp/woocommerce): Installing @forgewp/woocommerce registers universal WooCommerce cart/product/checkout REST endpoints (/wp-json/forgewp/v1/cart, /products, /checkout, /orders) and supports cms/products.ts seeding. Query products via wpClient.getPosts("product") and render archives with <WpQueryLoop postType="product" />.

8. CLI Scaffolding Commands

All make:* commands work on Next.js and emit .tsx/.ts or .jsx/.js automatically based on your project:

Terminal
pnpm forgewp make:block FeatureCard --attributes=heading,summary
pnpm forgewp make:page ContactUs
pnpm forgewp make:island NewsletterSignup
pnpm forgewp make:form Contact
pnpm forgewp make:loop BlogGrid --postType=post
pnpm forgewp make:shell SplitSection --layout=2-col
pnpm forgewp doctor

9. Compatibility Matrix

Table · 4 columns
Feature / API
Native WordPress Export
Decoupled Next.js Mode
Notes
Fixed App Router pages (/, /about, nested routes, not-found)
Supported
Supported
Shared <header> / <footer> extracted to header.php / footer.php.
Single-segment [slug] & paired archive routes
Supported
Supported
Requires generateStaticParams(). Compiles to single.php / archive.php (+ CPT variants).
Catch-all ([...slug]) & multi-dynamic ([cat]/[slug]) routes
Not supported (NEXT_NATIVE_DYNAMIC_ROUTE)
Supported
Keep in decoupled mode or use single-segment [slug] routes for native themes.
Global & CSS Module stylesheets
Supported
Supported
Shared CSS preserves <head> cascade order; route-only CSS is scoped per route.
next/image (public/ & static ES imports)
Supported
Supported
Bridged to ForgeWP Sharp WebP srcset in native export; Next.js optimizer in decoupled mode.
next/font/google & next/font/local
Supported
Supported
Build-time .woff2 subsets packaged into assets/fonts/.
next/link (string, template, or { pathname, query, hash })
Supported
Supported
Rewritten to forgewp_resolve_route_url(); raw <a> tags are left untouched.
@forgewp/react (createWpServerClient, BlockArea, Hydrate, WpQueryLoop, WpMenu, WpRequireAuth, WpAuthGate)
Supported
Supported
Switches automatically between cms/mock-data, WordPress REST, and native PHP tokens.
Explicit <Hydrate> & opt-in autoHydrate 'use client' islands
Supported
Supported
Bundled via esbuild into assets/islands/*; opt out with /* @forgewp-no-hydrate */.
Route Handlers (route.ts), Middleware, Server Actions, next/headers, force-dynamic
Not supported (NEXT_NATIVE_* error)
Supported
Require a request-time Next.js server; use WordPress REST or src/server/*.php for native themes.
Turbopack (next dev / next build without --webpack)
Supported
Supported
Configured automatically by withForgeWP().
Optional ForgeWP modules (Forms, SEO, Auth, WooCommerce)
Supported
Supported
Full parity across both deployment modes.