Most PHP to Next.js projects fail the same way. Someone estimates a rewrite, the team builds the new application beside the old one for a year, and on cutover day hundreds of small behaviors the old system had are missing. The project is late, search traffic drops, and the PHP code everyone wanted to leave is still in production because the new system cannot yet replace it.
This guide describes the approach that avoids that: Next.js goes in front of the PHP application on day one, and routes move across one at a time, each one live, measured and reversible. It covers every phase from the first inventory to switching the last PHP server off, with the specific decisions you will face on the way.
If you have not yet decided whether to migrate at all, read Upgrade PHP or migrate to Next.js? first. Many applications are better served by a PHP upgrade, and the honest answer saves money either way.
When moving from PHP to Next.js makes sense
Next.js is a React framework that renders pages on the server, statically at build time, or in the browser, and lets you mix all three per route. It is a good destination when:
- The front end is the bottleneck. Page speed, design changes and new features are slow because templates, jQuery and server-rendered HTML are tangled together.
- The team already writes TypeScript and React, or is hiring for it, and PHP knowledge is concentrated in a few people.
- The product is moving toward an app-like experience: dashboards, real-time updates, client-side interactivity that PHP templates handle badly.
- The public site and the application are one codebase and need to be separated, so marketing pages can change without touching billing code.
It is a poor fit when the application's value is in batch jobs, complex domain logic or integrations with no web front end. Those are better upgraded in place, with PHP upgrades done version by version.
The approach: strangler fig, not big bang
The strangler fig pattern, named by Martin Fowler after a vine that grows around a tree until it replaces it, is the standard way to replace a live system. Applied to PHP and Next.js it has three rules:
- Next.js is deployed in front of PHP before any route moves. Every request it cannot serve is passed to PHP unchanged.
- Routes move one at a time. Each move is a small release, compared against the old version in production, and switched behind a flag.
- PHP stays healthy until the end. It is patched, monitored and covered for security for as long as it serves traffic.
The detailed mechanics of the proxy layer, session sharing and route selection are in Migrating a PHP application to Next.js, one route at a time. The rest of this guide is the project around that pattern.
Phase 1: inventory what the PHP application actually does
The estimate is only as good as the inventory. Before writing any Next.js code, build a list of everything the application does, not just its pages.
| What to list | Where to find it | Why it matters |
|---|---|---|
| Every route with traffic | Access logs for the last 90 days, grouped by path pattern | Tells you what to move and in what order |
| URL rewrites and redirects | .htaccess, Nginx config, the front controller's router |
Every one has to be reproduced or deliberately dropped |
| Forms and POST endpoints | Templates, $_POST usage, router config |
These carry the most behavior per line |
| Authentication and roles | Session handling, login code, permission checks | Decides how both stacks share users |
| Background work | Cron entries, queue workers, CLI scripts | Not part of any page, and easy to forget |
| File uploads and generated files | Upload directories, PDF and image generation | Need a new home, usually object storage |
| Outbound integrations | Payment, email, CRM, ERP and API clients | Need credentials, retries and monitoring rebuilt |
| Search engine signals | Titles, meta tags, canonical tags, sitemap, structured data | Losing these costs rankings |
Access logs are the most useful source. A legacy PHP application usually has far more routes in code than routes with traffic. In our experience a minority of templates serve most requests, and some code paths have not been called in years. Those can be retired instead of migrated, which is the cheapest migration there is.
Phase 2: decide what stays in PHP
Not everything has to move. A common, sensible end state is Next.js for everything users see, with a slimmed-down PHP service behind it for logic that works and is expensive to rewrite: tax calculation, a pricing engine, an integration with a system nobody wants to touch.
Decide this per capability, and write it down:
- Move: pages, templates, forms, user-facing flows.
- Wrap: business logic that works. Expose it to Next.js as a small JSON API inside the PHP application, and keep it there for now.
- Retire: routes and features with no traffic and no owner.
Wrapped PHP still needs a supported runtime. If it runs on PHP 7.4 or 8.1, which are both past community end of life, either upgrade it as part of the project or cover it with long-term support until it is replaced.
Phase 3: put Next.js in front
The first production release changes nothing visible. Next.js is deployed in
front of the PHP application and passes every request it does not handle
through to PHP. Rewrites configured with fallback in next.config.js are
checked only after Next.js has looked for its own routes:
// next.config.js
module.exports = {
async rewrites() {
return {
fallback: [{ source: '/:path*', destination: `${process.env.LEGACY_ORIGIN}/:path*` }],
};
},
};
Point LEGACY_ORIGIN at an internal hostname for the PHP servers, so the
legacy stack can come off the public internet entirely.
Before moving a single route, compare the proxied site with the old one: response times at the median and the slowest percentiles, error rates, cache hit rates, cookies and headers. Fix any difference now. Once routes start moving, it becomes hard to tell whether a problem came from the proxy or from the new code.
Phase 4: map PHP concepts to Next.js
Most of the work is translation. This table is the map we use with teams moving from plain PHP, Laravel, Symfony or CodeIgniter to the Next.js App Router.
| In the PHP application | In Next.js | Notes |
|---|---|---|
page.php or a controller action that renders a template |
A route segment with page.tsx, rendered as a Server Component |
Server Components fetch data on the server like PHP did, with no client JavaScript by default |
| Twig, Blade or PHP templates and partials | React components | Port layout first, then shared partials, then page bodies |
.htaccess or Nginx rewrites |
redirects() and rewrites() in next.config.js |
Keep permanent redirects permanent (308 or 301) |
$_GET and route parameters |
searchParams and dynamic segments such as [slug] |
Validate input as strictly as the PHP code did, or more |
| Form posts to a PHP handler | Server Actions or Route Handlers (route.ts) |
Keep CSRF protection; Server Actions check the origin by default |
$_SESSION |
A shared session (see Phase 6), then signed, HttpOnly cookies or an identity provider | The hardest part of most migrations |
| Cron jobs and CLI scripts | A scheduler and a worker outside the request path | Next.js is not a job runner; keep jobs in PHP or move them to a queue |
| Uploads written to local disk | Object storage such as S3 or R2, served through a CDN | Migrate existing files once, then write new ones to storage |
| Output caching, Varnish | Static rendering, Incremental Static Regeneration and a CDN | Revalidate on content change instead of on a timer where you can |
| jQuery widgets | Client Components ('use client') |
Only the interactive parts need to run in the browser |
Two habits from PHP cause the most trouble in Next.js. The first is reading request data anywhere: in Next.js, server code that reads cookies or headers opts the route into dynamic rendering, so keep those reads close to where they are needed. The second is relying on per-request global state, which has no equivalent; pass data explicitly instead.
Phase 5: plan the data layer
Keep the database. Changing the data model and the application at the same time doubles the risk, and the PHP code that still runs depends on the current schema.
There are three ways for Next.js to reach the data, and most projects use them in this order:
- Through the PHP application. Add small JSON endpoints to the existing code, and have Next.js call them. Fastest to start, and the business rules stay in one place.
- Through a new API service. As more logic moves, build a service in TypeScript (or keep one in PHP) that owns the data, and point both stacks at it.
- Directly from Next.js. Server Components can query the database with a typed client such as Drizzle or Prisma. Fine for read-heavy pages, risky for writes that PHP also performs, because validation now lives in two places.
Schema clean-up comes last, once no PHP code reads the old shape.
Phase 6: share users and sessions across both stacks
From the moment a logged-in user can load pages from both stacks, both need to agree on who that user is. The options, from simplest to most durable:
- PHP stays the source of truth. Next.js forwards the session cookie to a PHP endpoint that returns the current user. Simple and safe; it adds one internal call per request, so cache the answer briefly.
- Shared session store. Both stacks read sessions from the same Redis or database. Faster, but Next.js has to read PHP's session serialization format, and both sides must agree on expiry and rotation.
- An identity provider. Move login to an OpenID Connect provider, and have both stacks verify the same signed tokens. The right end state, best done as its own step and before the account pages move.
Do not move the login page until the session approach is proven on read-only pages for logged-in users.
Phase 7: move routes in the right order
Order routes by value and risk. A typical sequence:
- Public, read-only pages: marketing pages, articles, help content. High traffic, low risk, and they prove the rendering, caching and SEO setup.
- Listings and search: category pages, search results, filters.
- Logged-in, read-only pages: dashboards, account overviews, order history.
- Forms and writes: settings, profile edits, contact forms.
- Critical flows last: sign-up, checkout, payments. By now the team knows the new stack and the shared session is proven.
For every route, the same loop: build it, render old and new for the same inputs and diff the output, compare performance, switch it behind a flag, and watch errors and conversions for a few days before the next one.
Phase 8: protect search rankings
A public PHP site carries years of search equity, and a migration is the easiest way to lose it. For every route that moves:
- Keep the URL. If it must change, add a permanent redirect in the same release, and update internal links to point at the new URL directly.
- Carry over the title, meta description, canonical URL, robots directives,
Open Graph tags and JSON-LD structured data. Next.js's Metadata API
(
generateMetadata) makes these explicit per route. - Keep the sitemap complete across both stacks. Generate it from one place that knows about every live URL, wherever it is served from.
- Compare rendered HTML, not just the screenshot. Content that PHP printed in the initial HTML must still be in the initial HTML.
- Watch Search Console for crawl errors and ranking changes after each batch. Pause if they move.
Phase 9: test for parity, not just for correctness
Unit tests confirm the new code does what its authors expected. A migration also has to confirm it does what the old code did, including behavior nobody documented.
- Output diffs. Request the same URLs from both stacks and compare the HTML after normalizing dynamic values. Differences are either bugs or decisions; record which.
- Recorded traffic. Replay a sample of real requests, especially form submissions with unusual input, against both.
- End-to-end tests on critical flows, written before the flow moves, run against the PHP version first so you know they are correct.
- Production monitoring per route: error rate, latency and conversion, compared with the same route before the switch.
Phase 10: switch PHP off
When the last route has moved and nothing calls the PHP application directly, remove the fallback rewrite. Leave the PHP servers running but unreachable for a few weeks, watching for any traffic that still arrives. Then archive the code and a final database snapshot, record what was retired and when, and shut it down.
What this costs, and what drives the cost
We do not quote per line of code, because line count barely predicts effort. The real drivers are:
- The number of routes with real traffic, after retiring dead ones.
- How much logic lives in templates. PHP that mixes queries, business rules and HTML in one file takes longest to port.
- Authentication complexity: single sign-on, roles, multi-tenancy.
- Integrations: each payment provider, ERP or CRM connection needs to be rebuilt and tested against real accounts.
- How much PHP stays wrapped rather than rewritten.
A two-week assessment produces the route inventory, the move, wrap and retire decisions, and a costed plan, which is the right starting point for any estimate.
Keeping the PHP side safe during the move
A migration of any size runs for months, and the PHP application serves real users the whole time. If it runs on an unsupported PHP version, every month of the project is a month on an unpatched runtime. Either upgrade it to a supported version first, which is usually a small project compared with the migration, or put it under SeaPHP LTS so security fixes keep arriving until the last route moves. The migration should be a choice about the future, not a race against the next vulnerability.
If you want help running one of these, see Next.js migration services.
Questions we get asked
How long does a PHP to Next.js migration take?
It depends on the number of routes that carry real traffic, not on lines of code. A content-heavy site with a few dozen templates can move in a few months. A transactional application with accounts, payments and integrations usually runs for several quarters, with value shipped every few weeks along the way.
Can Next.js and PHP run side by side?
Yes, and they should. Next.js sits in front and serves the routes it owns. Every other request is passed to the PHP application unchanged through a fallback rewrite, so users never see the seam.
Do we have to replace the database?
No. Most migrations keep the existing MySQL or PostgreSQL database for the whole project. Next.js reads it through the PHP application at first, then through a new service or directly, and schema changes wait until the PHP code that depends on the old schema is gone.
Will we lose search rankings?
Not if URLs, titles, canonical tags and structured data are carried over route by route, and rankings are watched after each batch. Most ranking losses in migrations come from changed URLs without redirects, which this approach avoids.
Should we upgrade PHP instead?
Often, yes. If the application's value is in business logic rather than in its pages, or if the team knows PHP well, upgrading to a current PHP version is cheaper and less risky. Next.js pays off when the front end is the bottleneck.