AI

Migrating Legacy Apps to Next.js with Claude Code

· 13 min read

Migrating Legacy Apps to Next.js with Claude Code
Contents

Over the past year I moved a handful of legacy projects to Next.js with Claude Code. Most of them were PHP applications. Claude Code read each legacy codebase, pulled out the business logic, content, UI components and even parts of the admin interface, and rebuilt them as a clean Next.js application. After a few of these I ended up with a workflow that keeps giving good results, and it saved me a surprising amount of time.

Hugo to Next.js, admin included#

For this post I take my own blog as the example. The current version is built with Hugo. The Hugo project is the source of truth for layout, styling, JavaScript and content, which is stored as Markdown files with images. Claude Code has to analyze those sources and build a fresh Next.js application that looks and behaves the same.

Rendering pages is only part of the job. I also want Claude Code to import all the posts into a database and generate an admin UI, so the content can be managed without touching Markdown files anymore.

Let’s assume the legacy project lives in /home/sheiko/projects/legacy, and the new Next.js application goes into an empty directory, /home/sheiko/projects/blog.

The first thing I put into that directory is nextjs16-migration-agent-spec.md. It describes the general architecture and coding conventions. The migration prompt refers to it for everything outside the /admin section, so Claude Code follows one set of rules across the whole project.

# AI Agent Spec: Legacy App → Next.js 16 (excerpt)

## Project Structure

~~~
src/
├── app/
│   ├── (main)/          # public routes, own layout.jsx
│   │   └── api/v1/[resource]/route.js
│   ├── (admin)/         # protected routes, own layout.jsx
│   ├── global-error.jsx
│   └── global-not-found.jsx
├── lib/
│   ├── store.js, features/*Slice.js   # Redux
│   ├── actions/         # Server Actions
│   └── models/          # DB access
├── ui/main/components/ComponentName/
│   ├── ComponentName.jsx
│   ├── ComponentName.scss
│   └── ComponentName.test.jsx
└── utils/session, api, security, ...
~~~

One component per folder. Never put components directly under `src/app/`.

## Server vs Client Components

Default to Server Components. Add `"use client"` only for hooks, browser APIs, event handlers, or DOM-dependent libraries. Push the directive to the smallest leaf component, never to a whole page or layout.

~~~jsx
// page.jsx: Server Component
export default async function ExamplePage() {
  const data = await fetchData();
  return <InteractiveWidget initialData={ data } />;
}
~~~

## API Routes

- Live under `(main)/api/v1/[resource]/route.js`, export `GET`/`POST`/etc.
- Validate the session first, return `401` if missing.
- Delegate logic to `src/lib/models/`; keep handlers thin.
- Consistent shape: `{ ok: true, data }` / `{ ok: false, error }`.

## Auth

- Session token in an HttpOnly cookie, read via `next/headers` `cookies()`. Never expose it to JS.
- Client only holds derived state (Redux `auth` slice), never the raw token.
- Auth mutations are Server Actions (`"use server"`).

## Code Style

- Double quotes, curly braces always required, `{ foo }` spacing in JSX.
- No `console.log` (warn/error/info are fine).
- No TypeScript, JS + PropTypes.
- SCSS: `@use`, not `@import`; BEM-like naming (`.card__title`, `.card_featured`).

## Anti-Patterns

- No `getInitialProps`/`getServerSideProps`.
- No client-side calls to external APIs, proxy through `/api/v1/`.
- No session tokens in `localStorage` or React state.
- No unnecessary abstractions or explanatory comments.

The admin gets its own spec, admin-ui-agent-spec.md, which defines how the CMS under /admin is built. Why not put these requirements straight into the prompt? Because then you repeat them in every prompt. With a spec file you review and refine the rules once, the migration prompt refers to it, and every generated admin screen follows the same structure and conventions.

# AI Agent Spec: Admin UI CRUD Interface (excerpt)

Internal framework: Next.js App Router + Ant Design + Redux Toolkit + a custom REST client/model layer.

## File Structure (per entity)

~~~
src/
├── app/(admin)/admin/[section]/[entity]/
│   ├── layout.jsx     # fetches table data server-side, renders Table
│   ├── page.jsx       # returns null
│   └── [id]/page.jsx  # fetches one record, renders EditModal
├── lib/
│   ├── api/admin/[Entity].js      # REST connector (client-side)
│   └── models/admin/[Entity].js   # DB model (server-side)
└── ui/admin/components/Main/[Section]/[Entity]/
    ├── [Entity]Table.jsx
    └── [Entity]EditModal.jsx
~~~

## Model

~~~js
import AbstractModel from "./AbstractModel";

export default class TagModel extends AbstractModel {
  table = "tag";
}
~~~

Extend `AbstractModel`, set `table`, add custom query methods only if needed. Base class already provides `findAll`, `find`, `add`, `update`, `remove`, `removeSelected`.

## API Connector

~~~js
import AbstractAdminRestClient from "./AbstractAdminRestClient";

class TagApi extends AbstractAdminRestClient {
  collection = "tags";
}

export const entityApi = new TagApi();
~~~

Always export the instance as `entityApi`: `UiTable` and `UiModalForm` consume it directly. Override `add`/`update` only when the payload needs shaping (e.g. `cleanDeep()`, `JSON.stringify()` on arrays).

## Table Component

~~~jsx
"use client";
import UiAdvancedTable from "@/ui/admin/components/UiTable/UiAdvancedTable";
import { entityApi as api } from "@/lib/api/admin/Tag";

export default function TagTable(props) {
  const columns = [
    { title: "Name", dataIndex: "name", sorter: true, getColumnSearchProps: "name" },
    { title: "Actions", key: "action", width: "120px", actions: "EditDelete" }
  ];

  return (
    <UiAdvancedTable
      columns={ columns }
      api={ api }
      enableSelection={ true }
      prefetchedData={ props.initialTableData }
      { ...props }
    />
  );
}
~~~

Use `UiTable` for simple lists, `UiAdvancedTable` when a column needs search.

## Modal Form Component

~~~jsx
"use client";
import UiModalForm from "@/ui/admin/components/UiModalForm/UiModalForm";
import { Form, Input } from "antd";
import { entityApi as api } from "@/lib/api/admin/Tag";

export default function TagEditModal({ pk, initialFormData }) {
  return (
    <UiModalForm pk={ pk } api={ api } initialValues={ initialFormData ?? { name: "" } }>
      { ({ onKeyDown }) => (
        <Form.Item label="Name" name="name" rules={ [{ required: true }, { min: 3 }] }>
          <Input onKeyDown={ onKeyDown } />
        </Form.Item>
      ) }
    </UiModalForm>
  );
}
~~~

`pk` falsy = create, truthy = edit. Use `transformInitialValues` / `transformFormData` to parse/serialize complex fields (arrays, JSON columns).

## Route Files

~~~jsx
// page.jsx: always returns null, layout renders everything
export default function EntityPage() { return null; }
~~~

~~~jsx
// layout.jsx: fetches list server-side, always force-dynamic
export const dynamic = "force-dynamic";

export default async function EntityLayout({ children }) {
  const initialTableData = await model.findAll();
  return (
    <>
      { children }
      <EntityTable initialTableData={ initialTableData } />
    </>
  );
}
~~~

~~~jsx
// [id]/page.jsx: fetches one record, renders the modal
export const dynamic = "force-dynamic";

export default async function EntityModalPage({ params }) {
  const { id } = await params ?? {};
  const initialFormData = id ? await model.find(id) : null;
  return <EntityEditModal pk={ id } initialFormData={ initialFormData } />;
}
~~~

## CRUD Flow

1. `layout.jsx` fetches `model.findAll()`, passes it to the Table as `prefetchedData`.
2. Add/Edit navigates to the `[id]` route.
3. `[id]/page.jsx` fetches `model.find(pk)`, passes it to the modal.
4. Modal opens pre-populated; submit runs `transformFormData` then `api.add()`/`api.update()`.
5. On success, the table refetches; the layout persists underneath the modal the whole time.

## Anti-Patterns

- No `"use client"` on layout/page files, they're Server Components.
- No calling `model.*` from client components, models are server-only.
- No fetching inside `UiTable`/`UiModalForm` via `useEffect`, always pass `prefetchedData`.
- Don't omit `export const dynamic = "force-dynamic"` on admin layouts and pages.
- Don't override base API/model methods unless the payload shape actually differs.

With that groundwork done, the prompt has almost nothing left to explain. Project layout and conventions already live in the spec files, so the prompt is only about the task. This is what I feed to Claude Code:

# Project Goal (excerpt)

Migrate the legacy Hugo site at `/home/sheiko/projects/legacy` to Next.js 16 (App Router) + JavaScript (no TypeScript) + SCSS + MariaDB. Build the new app in the current directory, incrementally, staying runnable throughout.

## Source of Truth

The legacy Hugo project is read-only and authoritative.

- Reproduce existing functionality, content, URLs, and visual design as closely as possible.
- Modernize the implementation, not the design.
- Reuse existing assets (fonts, images, icons); preserve HTML structure and class names where practical.

## Frontend

- Extract reusable React components, follow App Router conventions.
- Prefer Server Components unless interactivity is required.
- Preserve URLs and SEO/Open Graph metadata.

## Content

Import all blog posts into MariaDB (design the schema), render pages dynamically, preserve all metadata (title, slug, date, tags, categories, excerpt, body, SEO fields).

## Administration

Build a CMS under `/admin` using Ant Design v5 (header + collapsible sidebar + content area), following `admin-ui-agent-spec.md`.

Auth flow: unauthenticated users see only the header and login page (no sidebar, no protected pages); after login, show the sidebar and go to the dashboard; after logout, return to login.

Seed an `admin_user` table with a default `admin`/`admin` account, password hashed with bcrypt.

## Database

Use dbmate for all schema changes, no exceptions. Never hardcode credentials, stop and ask for the MariaDB root password before any privileged operation.

## Development Rules

Follow `nextjs16-migration-agent-spec.md` for implementation details; it takes precedence over ad hoc decisions. If something can't be inferred from the legacy site or the spec, stop and ask rather than assume.

After I submit it, Claude Code spends a few minutes analyzing the project before writing any code. What I like is that it doesn’t jump into implementation right away. It builds a migration plan first, and you can check whether it understood the task.

Claude Code todo list for the Hugo to Next.js migration, from project setup to importing blog posts into MariaDB

When the migration finishes, it prints a recap of everything it changed.

Claude Code recap table listing the migrated public routes and admin CMS features, with the default admin login

So what did we get? We start the application with npm run dev and open http://localhost:3000.

Migrated Next.js blog homepage matching the original Hugo site's layout, sidebar, and post excerpt

Better than I expected. The original Hugo site uses fairly plain CSS and JavaScript, with no old frameworks and no deeply coupled frontend code. Because of that, Claude Code reproduced the layout almost pixel for pixel, and I didn’t have to spend any time fixing styles or chasing visual regressions.

What about the CMS? Open http://localhost:3000/admin.

Blog admin sign-in screen with username and password fields

The prompt asked for temporary credentials (admin / admin), so we can sign in right after the migration. The admin panel already has a list of imported posts and a screen for managing administrator accounts.

Admin UI posts table with imported blog posts, their categories, publish status, and dates

Open any post and all the expected fields are there, mapped from the original Markdown.

Admin UI edit post form with title, slug, description, and body fields populated from the imported Markdown post

At this point the project is usable. The public site matches the original and the content sits in the database with a working admin on top. That’s a solid starting point for replacing the legacy application, and it didn’t take weeks of rebuilding everything by hand.

Chasing visual regressions#

The Hugo example was almost too easy. Real migrations are rarely that clean. Most of the time you go through at least a few rounds of fixing visual regressions, especially when the original application has a larger design system, custom assets, third-party UI libraries or a complex build pipeline.

The free CoreUI admin template is a good example. Its source is on GitHub: CoreUI Free Bootstrap Admin Template. I cloned the repository into /home/sheiko/projects/coreui, started it locally and created a new empty Next.js project in /home/sheiko/projects/coreui-nextjs.

This time I kept the prompt simple on purpose:

Migrate the legacy application located at /home/sheiko/projects/coreui (http://localhost:3000/) into a new Next.js application (running on port 3003) in the current directory (JavaScript only).

The project at /home/sheiko/projects/coreui is the source of truth. Keep the new implementation as close as possible to the legacy application's design, styling, layout, and functionality while adopting modern Next.js architecture and best practices.

As before, Claude Code started with a migration plan.

Claude Code todo list for migrating the CoreUI admin template to Next.js

Before settling on that plan, it also summarized what the legacy template is built with.

Claude Code's analysis of the legacy CoreUI template: static pages, Pug templating, SASS styling, and Chart.js usage

At first glance the generated application looked convincing. Put it next to the original and the problems show up right away.

Migrated Next.js CoreUI dashboard with blank sidebar and toolbar icons

And this is the original:

Original CoreUI dashboard with sidebar icons and toolbar icons intact

The layout is mostly there, but the details are off. The sidebar icons are missing, some assets didn’t get migrated correctly, and the logo SVG renders black instead of white. None of this is hard to fix by hand. It’s the typical kind of regression you get when migrating a non-trivial frontend.

This is where many developers take over and patch things themselves. I prefer to keep Claude Code in the loop. It has already analyzed the project structure and written the implementation, so letting it inspect the differences and iterate is usually faster than taking over by hand. With a handful of issues I still point them out myself. Once the list grows, I let Claude Code inspect both applications and iterate until the differences disappear.

How does it see the differences? Through Playwright. A prompt like this works surprisingly well:

Make sure you have Playwright access. 
Act as a visual regression engineer.
Open legacy page http://localhost:3000. Take screenshot.
Open Next.js page http://localhost:3003. Take screenshot.
List all visual differences.
Fix them one by one.
Repeat until only negligible differences remain.

How far it gets depends on how complicated the application is. If most of the layout migrated correctly, Claude Code often clears dozens of small regressions in a few iterations without much guidance.

For larger projects I’d rather give it something more objective than two browser windows to compare. I add a small script, compare.mjs, to the Next.js project. It opens both applications with Playwright, takes screenshots and builds a pixel-by-pixel diff image.

import { chromium } from "playwright";
import { PNG } from "pngjs";
import pixelmatch from "pixelmatch";
import fs from "fs";

const legacy = "http://localhost:3000/";
const next   = "http://localhost:3003/";

const b = await chromium.launch();
const [p1, p2] = [ await b.newPage(), await b.newPage()];
await p1.goto( legacy, { waitUntil: "networkidle"} ); await p1.setViewportSize( { width:1440, height:900 } );
await p2.goto( next,   { waitUntil: "networkidle"} ); await p2.setViewportSize( { width:1440, height:900 } );

// dev-server-only UI that isn't part of the app itself
await p1.evaluate( () => document.getElementById( "__bs_notify__" )?.remove() );
await p2.evaluate( () => document.querySelector( "nextjs-portal" )?.remove() );

// give client-side chart rendering (Chart.js canvases) time to finish drawing on both pages
await p1.waitForTimeout( 2000 );
await p2.waitForTimeout( 2000 );

const [s1, s2] = await Promise.all( [
  p1.screenshot( { fullPage:true } ),
  p2.screenshot( { fullPage:true } )
] );

// write screenshots + diff
fs.writeFileSync( "legacy.png", s1 );
fs.writeFileSync( "next.png", s2 );

const img1 = PNG.sync.read( s1 ), img2 = PNG.sync.read( s2 );
const width = Math.min( img1.width, img2.width );
const height = Math.min( img1.height, img2.height );

function crop( img ) {
  const out = new PNG( { width, height } );
  PNG.bitblt( img, out, 0, 0, width, height, 0, 0 );
  return out;
}

const c1 = crop( img1 ), c2 = crop( img2 );
const diff = new PNG( { width, height } );
const mismatch = pixelmatch( c1.data, c2.data, diff.data, width, height, { threshold: 0.1 } );
fs.writeFileSync( "diff.png", PNG.sync.write( diff ) );
console.log( `Mismatch: ${(mismatch/(width*height)*100).toFixed( 2 )}%` );
await b.close();

Both dev servers inject their own UI into the page (Browsersync’s notification on the legacy side, the Next.js dev overlay on the new one), so the script removes it before taking screenshots. The two-second wait is for Chart.js, which draws its canvases on the client after the page loads.

The script needs a few dependencies:

npm install --save-dev playwright pngjs pixelmatch 
npx playwright install chromium 

Then we run it:

node compare.mjs

Mismatch: 1.22%

So 1.22% of the pixels differ. Now we tell Claude Code: “Here is diff.png. The red areas are mismatches. Fix only the largest red region first. Re-run the script after each fix.”

With a diff image the regressions turn into a short list ranked by size. Claude Code works through it one fix at a time and gets a number back after each step, so it doesn’t have to guess whether things got better.

Claude Code chat listing the fixes applied over five compare-and-fix iterations, bringing the pixel mismatch down to 0.52%

After five compare-and-fix rounds Claude reports the mismatch went down from 1.22% to 0.52%.

Migrated Next.js CoreUI dashboard after fixes, with sidebar icons and toolbar icons restored

Everything looks right to me except the logo, and that’s the fly in the ointment. A pixel diff shows where two pages differ but says nothing about why. To find out what’s wrong I used a skill of mine, css-style-sync, which lives at .claude/skills/css-style-sync/SKILL.md. You give it a CSS selector on each side. It checks that both point at the same kind of element, extracts the computed styles with Playwright, diffs them and prints a CSS fix.

From my experience, the setup is what keeps paying off: architecture and admin conventions go into spec files up front, the migration prompt stays short, and Claude Code shows a plan before it touches any code. That’s what made the Hugo migration close to a non-event. CoreUI was the more honest test. One simple prompt got me most of the way, but a template with hundreds of icons and Chart.js widgets will always leave regressions behind. For a project like that I’d go to the pixel diff early instead of asking Claude Code to eyeball two browser windows, and pull in css-style-sync for whatever SVG or icon-font mismatch survives the loop.