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:
- Native WordPress Theme Export (default): Runs
forgewp exportto compile your App Router routes, shared layout chrome, CSS,defineBlockGutenberg blocks,next/imageassets,next/font.woff2subsets, and client islands into a standalone WordPress theme ZIP. No Node.js server is required in production. - 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_idpermalinks, menus, site info, and serialized Gutenberg blocks.
1. Quick Start
Scaffold a new Next.js ForgeWP project with create-forgewp:
# 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 WordPressAdding 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:
# 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):
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 nextConfigwithForgeWP() configures five things automatically so you don't have to:
- Boundary-selected output mode: Sets
output: "export"for native WordPress extraction, and omits it whenFORGEWP_DEPLOYMENT_MODE=decoupledis active. - Turbopack & Webpack compatibility: Configures both
turbopack.rulesandwebpack.resolve.extensionAliasso plainnext dev/next buildworks on Next.js 16 Turbopack with zero--webpackflags. transpilePackages: Includes@forgewp/reactautomatically.- Native image bridge: Sets
images.unoptimized = trueonly duringFORGEWP_NATIVE_EXPORT=1so ForgeWP's Sharp WebP pipeline can optimize<Image />tags (while keeping Next.js's/_next/imageoptimizer in decoupled mode). - 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":
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):
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:
Mode Trigger What wpClient DoesLocal 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-siteFetches 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. |
|---|
Navigation Menus & Site Info (getMenu, getSiteInfo, <WpMenu />)
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 insrc/blocks/*.tsx(or.jsx) with'use client'at the top. During native export, ForgeWP compiles them toblocks/<slug>/block.json,render.php, andassets/forgewp-editor.jswired to your packaged Next.js CSS. - Editable Regions (
<BlockArea />): ImportBlockAreafrom@forgewp/reactin App Router Server Components and passcontent={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 enablewithForgeWP({}, { autoHydrate: true }):- Automatically excluded from auto-hydration: Server Components, Gutenberg blocks (
src/blocks/ordefineBlock), purely static'use client'components, and any file containing/* @forgewp-no-hydrate */. - Active islands are bundled via
esbuildintoassets/islands/*with a sharedreact-runtime.js— zero_next/static/chunks/*are shipped in native WordPress themes, and static pages ship 0 KB of client JS.
- Automatically excluded from auto-hydration: Server Components, Gutenberg blocks (
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.phpsrc/app/projects/[slug]/page.tsx(matchingpostTypes.projectinwp.config.ts) →single-project.phpsrc/app/projects/page.tsx→archive-project.php
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:
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 WebPsrcsetvariants underassets/images/, and rewrites rendered<img>tags toget_theme_file_uri(...)— with zero/_next/imageURLs left behind. In decoupled mode, Next.js's built-in optimizer stays active.next/font→ Self-Hostedassets/fonts/: Build-time.woff2subsets are copied intoassets/fonts/with theme-relative CSSurl()s, preservingfont.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/*.tsor.js): Define forms usingdefineWpForm(). ForgeWP generates theforgewp_submissionCPT and/wp-json/forgewp/v1/forms/<slug>/submitREST endpoint infunctions.php, and lints form usage acrosssrc/, rootapp/, and rootcomponents/. - SEO (
export const metadata+ Yoast / Rank Math / SEOPress): Next.jsexport const metadata(title,description, OpenGraph, Twitter cards, JSON-LD) flows intoforgewp-static/head.htmlbehindif ( ! forgewp_seo_plugin_active() ), so WordPress SEO plugins take over automatically when active. - Auth (
WpRequireAuth,WpAuthGate): Import Server-Component-safeWpRequireAuthandWpAuthGatefrom@forgewp/reactto protect pages or gate sections by login status or WordPress capability without client hooks:
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/woocommerceregisters universal WooCommerce cart/product/checkout REST endpoints (/wp-json/forgewp/v1/cart,/products,/checkout,/orders) and supportscms/products.tsseeding. Query products viawpClient.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:
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 doctor9. Compatibility Matrix
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 routesSupported Supported Requires generateStaticParams(). Compiles to single.php / archive.php (+ CPT variants).Catch-all ( [...slug]) & multi-dynamic ([cat]/[slug]) routesNot 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/localSupported 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' islandsSupported Supported Bundled via esbuild into assets/islands/*; opt out with /* @forgewp-no-hydrate */.Route Handlers ( route.ts), Middleware, Server Actions, next/headers, force-dynamicNot 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. |
|---|