Migrating from PHP/Laravel to Next.js: Lessons Learned
After spending over a decade building applications with PHP and Laravel, I recently led a major migration to Next.js. This article shares the strategies and lessons learned from that journey.
Why Migrate?
Our PHP/Laravel application served us well for years, but we faced challenges:
- Performance - Server-side rendering was slow for complex pages
- Developer experience - Frontend and backend were tightly coupled
- Scalability - Scaling PHP horizontally was expensive
- Modern features - Users expected SPA-like interactions
Planning the Migration
Never attempt a big-bang migration. Instead, use the strangler fig pattern:
Phase 1: New features in Next.js
Phase 2: Migrate high-traffic pages
Phase 3: Migrate remaining features
Phase 4: Decommission PHP backendSetting Up the API Layer
First, I converted Laravel endpoints to a clean API:
// Laravel API Controller
class UserController extends Controller
{
public function show($id)
{
$user = User::with(['orders', 'profile'])->findOrFail($id);
return response()->json([
'data' => new UserResource($user)
]);
}
}Then consumed it from Next.js:
// Next.js API Route or Server Component
async function getUser(id: string) {
const res = await fetch(`${process.env.API_URL}/api/users/${id}`, {
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json'
}
})
if (!res.ok) throw new Error('Failed to fetch user')
return res.json()
}Authentication Migration
Moving from Laravel Sanctum to Next.js Auth was challenging. Here's my approach using JWT verification in middleware.
Performance Wins
After migration, we saw significant improvements:
| Metric | PHP/Laravel | Next.js | Improvement |
|---|---|---|---|
| TTFB | 800ms | 150ms | 81% faster |
| LCP | 2.5s | 0.8s | 68% faster |
| Bundle Size | N/A | 85kb | Optimized |
Key Lessons
- Migrate incrementally - Don't try to rewrite everything at once
- Keep the API stable - Your PHP API can serve both old and new frontend
- Test thoroughly - Write tests before migrating each feature
- Monitor performance - Track metrics throughout the migration
- Train the team - Invest in React/Next.js training
Conclusion
Migrating from PHP to Next.js is a significant undertaking, but the benefits are worth it. The key is to plan carefully, migrate incrementally, and maintain both systems during the transition period.