# 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**

```bash
# 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**

```bash
# 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**

```ts
import type { NextConfig } from "next"
import { withForgeWP } from "@forgewp/react/next"

const nextConfig: NextConfig = withForgeWP(
  {
    // Your standard Next.js options
  },
  {
    // Optional: automatically wrap interactive 'use client' components in <Hydrate>
    // during native WordPress export (FORGEWP_NATIVE_EXPORT=1).
    autoHydrate: true, // or { defaultTrigger: "visible" | "load" | "idle" | "interaction" }
  },
)

export 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**

```ts
import { defineConfig } from "@forgewp/compiler/define-config"

export default defineConfig({
  configVersion: 1,
  name: "My Next Theme",
  slug: "my-next-theme",
  version: "0.1.0",
  description: "A WordPress theme built with Next.js App Router and ForgeWP.",
  textDomain: "my-next-theme",
  frameworkAdapter: "nextjs",
})
```

---

## 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**

```ts
import { createWpServerClient } from "@forgewp/react"
import { mockData } from "../../cms/mock-data"

export const wpClient = createWpServerClient({
  fixtures: mockData,
})

export async function getPageContent(slug: string) {
  return wpClient.getLivePage(slug)
}
```

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` 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. |

### Navigation Menus & Site Info (`getMenu`, `getSiteInfo`, `<WpMenu />`)

**src/app/layout.tsx**

```tsx
import { WpMenu } from "@forgewp/react"
import { wpClient } from "@/lib/content"

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const [site, primaryMenu] = await Promise.all([
    wpClient.getSiteInfo(),
    wpClient.getMenu("primary"),
  ])

  return (
    <html lang={site.language}>
      <body>
        <header>
          <a href={site.homeUrl}>{site.name}</a>
          <WpMenu location="primary" items={primaryMenu} className="nav" />
        </header>
        {children}
      </body>
    </html>
  )
}
```

---

## 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**

```tsx
import { BlockArea } from "@forgewp/react"
import { wpClient } from "@/lib/content"

export async function generateStaticParams() {
  return wpClient.getStaticParams("post")
}

export default async function SinglePostPage({
  params,
}: {
  params: Promise<{ slug: string }>
}) {
  const { slug } = await params
  const post = await wpClient.getLivePost("post", slug)

  return (
    <main>
      <h1>{post?.title}</h1>
      <BlockArea name="post-content" content={post?.content} />
    </main>
  )
}
```

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

**src/app/blog/page.tsx**

```tsx
import { WpQueryLoop } from "@forgewp/react"
import { wpClient } from "@/lib/content"

export default async function BlogArchivePage() {
  const posts = await wpClient.getPosts("post")

  return (
    <main>
      <h1>Blog</h1>
      <WpQueryLoop
        postType="post"
        posts={posts}
        renderItem={(post) => (
          <article key={post.id}>
            <h2>
              <a href={post.permalink}>{post.title}</a>
            </h2>
            <p>{post.excerpt}</p>
          </article>
        )}
      />
    </main>
  )
}
```

---

## 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**

```tsx
import { WpRequireAuth, WpAuthGate } from "@forgewp/react"

export default function DashboardPage() {
  return (
    <WpRequireAuth redirect="/login" allowed="edit_posts">
      <main>
        <h1>Editor Dashboard</h1>
        <WpAuthGate allowed="manage_options" fallback={<p>Standard editor view</p>}>
          <p>Administrator controls</p>
        </WpAuthGate>
      </main>
    </WpRequireAuth>
  )
}
```

- **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**

```bash
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

| 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. |

---

Source: [Next.js App Router Adapter](https://www.forgewp.dev/docs/core/adapters/nextjs-adapter)
