React to Next.js Conversion: A Complete Migration Guide for Solo Developers
A practical guide to converting React apps to Next.js, based on migrating 10+ production sites — covering routing, data fetching, caching, and common pitfalls.
React to Next.js Conversion: A Complete Migration Guide for Solo Developers
Published: July 2026 Reading time: 8 minutes Tags: react, nextjs, migration, conversion, web-development, solo-dev
I've migrated 10+ production sites from Create React App and Vite to Next.js App Router. This is the practical guide I wish I'd had — real migration patterns, not theoretical fluff.
If you're a solo developer running a React SPA and wondering whether the Next.js migration is worth the effort, the short answer is yes. But the how matters more than the why. Bad migrations can take weeks. A good one, using the patterns below, takes 2–3 days for your first app and 2–3 hours for subsequent ones.
Let me walk you through exactly how I do it — file by file, gotcha by gotcha.
1. File-Based Routing#
The first and most visible change: moving from React Router to Next.js App Router.
Before: React Router#
// App.tsx
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/blog/:slug" element={<BlogPost />} />
</Routes>
</BrowserRouter>
After: Next.js App Router#
app/
page.tsx → /
about/
page.tsx → /about
blog/
[slug]/
page.tsx → /blog/:slug
loading.tsx → streaming loading state
error.tsx → granular error boundary
layout.tsx → shared shell (header, footer)
Key rules:
- Pages become folders. Each route segment is a directory containing a
page.tsxfile. No more router configuration — the file system is the router. - Dynamic routes use
[slug]. The bracket syntax is Next.js's equivalent of:slugin React Router. Access it viaparams.slugin your page component. - Layouts are built-in. Create a
layout.tsxin any folder and it wraps all pages nested under it. This replaces the wrapper pattern you'd use with React Router's<Outlet />. - Loading states are free. Drop a
loading.tsxfile in any route segment and Next.js shows it while the page's data loads. No more manualisLoadingflags in every component. - Error boundaries per route. An
error.tsxfile catches errors in that segment and its children. One buggy blog post doesn't crash the whole site.
Migration Strategy#
Don't rewrite your routing in one shot. Here's the order I use:
- Create the
app/directory alongside your existingsrc/ - Copy
layout.tsxfrom your existing shell component - Migrate the homepage first (it's usually the simplest page)
- Move one non-critical route at a time
- Keep React Router running in parallel until you're done
Next.js supports both App Router and Pages Router in the same project. You can run app/ and pages/ concurrently during migration. This is a lifesaver.
2. Data Fetching: From useEffect to RSC#
This is where the biggest mental shift happens. Server Components change how you think about data.
Before: useEffect + React Query#
function BlogList() {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('/api/posts')
.then(res => res.json())
.then(data => { setPosts(data); setLoading(false); });
}, []);
if (loading) return <Spinner />;
return posts.map(post => <PostCard key={post.id} {...post} />);
}
After: Server Component#
// app/blog/page.tsx — this is a Server Component by default
async function BlogList() {
const posts = await db.posts.findMany(); // direct database call
return posts.map(post => <PostCard key={post.id} {...post} />);
}
No useEffect, no useState, no loading state boilerplate. The component is async, it fetches data directly, and it renders on the server. The HTML is sent to the client fully populated.
When to Reach for Server Components#
Use Server Components for data that doesn't need real-time updates: blog posts, product listings, user profiles, static content. These are the vast majority of your pages.
When to Use Client Components#
Use "use client" for interactive data that changes during the session: search autocomplete, real-time dashboards, forms with validation, anything with useState or useEffect.
The Hybrid Approach#
This is the pattern I use on most pages:
// app/posts/page.tsx — Server Component
import { PostList } from './post-list';
async function PostsPage() {
const initialPosts = await getPosts({ limit: 20 });
return (
<div>
<h1>Posts</h1>
<PostList initialData={initialPosts} />
</div>
);
}
// app/posts/post-list.tsx — Client Component
"use client";
import { useQuery } from '@tanstack/react-query';
export function PostList({ initialData }) {
const { data } = useQuery({
queryKey: ['posts'],
queryFn: () => fetch('/api/posts').then(r => r.json()),
initialData,
});
// Client-side refetching for freshness
return data.map(post => <PostCard key={post.id} {...post} />);
}
The server sends the initial HTML (fast first paint), and React Query keeps it fresh on the client (interactive updates). Best of both worlds.
3. Caching: The Biggest Mental Shift#
Next.js caches aggressively. This is a feature, not a bug — but it will surprise you the first time you update data and see stale content on the page.
The Default: fetch() Is Cached#
// This is cached by default
const data = await fetch('https://api.example.com/posts');
Next.js caches the response and reuses it for subsequent requests within the same render cycle. This is great for performance but confusing if you expect every request to hit the network.
ISR: Incremental Static Regeneration#
// app/posts/page.tsx
export const revalidate = 3600; // Revalidate every hour
async function PostsPage() {
const posts = await fetch('https://api.example.com/posts').then(r => r.json());
return <PostList posts={posts} />;
}
ISR is the killer feature. The page is rendered at build time (fast), then re-rendered in the background when the revalidation window expires. Users never wait — they always get a cached page, and the next visit after expiry triggers a background rebuild.
force-dynamic vs force-static#
// Forces dynamic rendering — no caching
export const dynamic = 'force-dynamic';
// Forces static rendering — cached at build time
export const dynamic = 'force-static';
My rule of thumb:
- Content pages (blog, docs, landing):
force-staticwithrevalidate - Dashboard / user-specific pages:
force-dynamic - Everything else: let Next.js decide (it's smart about it)
The unstable_noStore Escape Hatch#
import { unstable_noStore as noStore } from 'next/cache';
async function getData() {
noStore(); // Never cache this function
return await db.query('SELECT * FROM posts');
}
Use this when you need to opt out of caching at the function level rather than the page level. It's stable enough to use in production despite the unstable_ prefix — it's just not in the final API yet.
One Real-World Example#
I had a blog where comments would appear for some users but not others. Turns out the page was cached at build time, and the revalidate was set to 24 hours. New comments were invisible for a full day. The fix:
export const revalidate = 60; // Revalidate every minute
Now comments appear within 60 seconds of posting. ISR handles the background rebuild, users never see a loading state, and the database isn't hit on every request.
4. API Routes: Replace Your Express Server#
If you're running a separate Express server alongside your React app, you can fold those endpoints into Next.js.
Before: Express Route#
// server.js
app.get('/api/posts', async (req, res) => {
const posts = await db.posts.findMany();
res.json(posts);
});
After: Next.js Route Handler#
// app/api/posts/route.ts
export async function GET() {
const posts = await db.posts.findMany();
return Response.json(posts);
}
What you gain:
- No separate server process. One
npm run dev, one deployment. - Automatic type safety. Route handlers share types with your frontend.
- Edge runtime support. Deploy to Vercel's edge network for zero cold starts.
- Middleware for free. Use
middleware.tsfor auth, redirects, headers — no more Express middleware config.
Middleware Example#
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('session')?.value;
if (!token) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: '/dashboard/:path*',
};
This replaces wherever you were handling auth middleware in Express. Less boilerplate, same patterns.
5. Image Optimization#
The Next.js Image component is a free performance upgrade. You get WebP/AVIF conversion, lazy loading, and responsive images without any configuration.
Before#
<img src="/hero.jpg" alt="Hero" />
After#
import Image from 'next/image';
<Image
src="/hero.jpg"
alt="Hero"
width={1200}
height={600}
sizes="(max-width: 768px) 100vw, 1200px"
/>
What this does for you:
- Automatic format conversion. Next.js serves WebP or AVIF depending on browser support. Your users get smaller images, you do nothing.
- Lazy loading by default. Images below the fold don't load until the user scrolls near them. Zero configuration.
- Responsive images. The
sizesprop tells Next.js which image size to serve at each breakpoint. No more manualsrcSetcreation. - CLS prevention. The
widthandheightattributes reserve space during loading, preventing layout shift.
Remote Images#
For external images (CMS, S3, etc.), add the hostname to your next.config.js:
// next.config.js
module.exports = {
images: {
remotePatterns: [
{ protocol: 'https', hostname: 'cdn.example.com' },
],
},
}
Common Pitfalls (From Real Experience)#
I've hit every one of these. Here's how to avoid them.
"Window is not defined"#
Server Components don't have access to browser APIs. If you try to reference window, document, localStorage, or anything browser-specific, you'll get this error.
Fix: Either add "use client" to the component, or wrap the browser-specific code in a useEffect:
"use client";
import { useEffect } from 'react';
function ClientOnly() {
useEffect(() => {
const width = window.innerWidth; // This works now
}, []);
}
Database Queries in Components#
You can't use the browser-side Supabase or Firebase client in a Server Component. The server-side client doesn't use cookies — it uses service roles or API keys.
Fix: Use the server client for Server Components and the browser client for Client Components. Don't mix them.
// app/lib/server-client.ts
import { createClient } from '@supabase/supabase-js';
export const supabase = createClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!
);
Caching Surprises#
Data appears stale because Next.js cached it. You refresh the page — still stale. You clear the browser cache — still stale.
Fix: Check your fetch options. Add { cache: 'no-store' } for data that changes frequently, or use revalidate for data that changes periodically.
const data = await fetch(url, { cache: 'no-store' });
Build Time Blowup#
You use generateStaticParams for a blog with 10,000 posts, and your build time goes from 30 seconds to 30 minutes.
Fix: Use dynamicParams or revalidate instead of pre-rendering everything.
export const dynamicParams = true; // Generate on demand
export async function generateStaticParams() {
const posts = await getPopularPosts({ limit: 50 }); // Only pre-render popular ones
return posts.map(post => ({ slug: post.slug }));
}
The remaining 9,950 posts are generated on first visit and cached thereafter. Users wait milliseconds, and your builds finish in seconds.
Verdict: Is It Worth It?#
After 10+ migrations, here's my honest assessment.
Yes, the migration is worth it. Here's what you get:
- Better performance. Server Components, ISR, and automatic image optimization make your site faster with zero extra effort.
- Simpler code. No more
useEffectfor data fetching, no more router configuration, no more separate API server. - Free SEO. SSR and ISR mean search engines see fully rendered HTML. Your Google rankings will thank you.
- One codebase. No more CRA for frontend + Express for backend + separate image optimizer. Next.js handles everything.
But don't migrate everything at once. Start with one page — the one that would benefit most from SSR or ISR. Migrate it, ship it, verify it works. Then do the next one. The first migration takes 2–3 days. Subsequent ones take 2–3 hours because you've already built the patterns and infrastructure.
The App Router is production-ready for solo developers. I run 10+ sites on it, including this blog. The migration is a weekend project that pays dividends for years.
Have questions about migrating a specific pattern? I've been through most of them. Drop a comment below or reach out on Twitter.
Freelance
Besoin d'aide sur ce sujet ?
Je peux aider sur les migrations, nouveaux produits et performances web.
Me contacter →