Harry Gutierrez

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 backend

Setting 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:

MetricPHP/LaravelNext.jsImprovement
TTFB800ms150ms81% faster
LCP2.5s0.8s68% faster
Bundle SizeN/A85kbOptimized

Key Lessons

  1. Migrate incrementally - Don't try to rewrite everything at once
  2. Keep the API stable - Your PHP API can serve both old and new frontend
  3. Test thoroughly - Write tests before migrating each feature
  4. Monitor performance - Track metrics throughout the migration
  5. 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.