CRA to Next.js Migration Guide
Comprehensive migration guide for converting Create React App projects to Next.js, covering routing, data fetching, components, styling, and deployment. Contains 148 rules across 17 categories, prioritized by migration impact. After a successful migration the application should work the same as it did before the migration.
When to Apply
Reference these guidelines when:
- Migrating an existing CRA application to Next.js
- Converting React Router routes to file-based routing
- Adopting Server Components in a client-heavy app
- Moving from client-side rendering to SSR/SSG
- Updating environment variables for Next.js
- Optimizing images and fonts with Next.js built-ins
Version Policy
Use Next.js 16.x or later. Do NOT use Next.js 14.x or 15.x.
Before starting migration, check the current latest version:
Use the latest version in your package.json with a caret for minor/patch updates. The minimum supported version for this migration guide is
.
Rule Categories by Priority
| Priority | Category | Impact | Prefix | Rules |
|---|
| 1 | Project Setup | CRITICAL | | 6 |
| 2 | Dependencies | CRITICAL | | 1 |
| 3 | Routing | CRITICAL | | 17 |
| 4 | Data Fetching | CRITICAL | | 11 |
| 5 | Components | HIGH | | 9 |
| 6 | Environment Variables | HIGH | | 6 |
| 7 | Styling | HIGH | | 12 |
| 8 | Public Assets | MEDIUM | | 5 |
| 9 | Images | MEDIUM | | 8 |
| 10 | Fonts | MEDIUM | | 6 |
| 11 | SEO & Metadata | MEDIUM | | 9 |
| 12 | API Routes | MEDIUM | | 9 |
| 13 | State Management | MEDIUM | | 8 |
| 14 | Integrations | MEDIUM | | 1 |
| 15 | Testing | LOW | | 9 |
| 16 | Build & Deploy | LOW | | 7 |
| 17 | Common Gotchas | HIGH | | 24 |
Quick Reference
1. Project Setup (CRITICAL)
- - Convert CRA folder structure to Next.js App Router
- - Update dependencies and scripts
- - Create and configure next.config.js
- - Migrate TypeScript configuration
- - Update ESLint for Next.js
- - Update .gitignore for Next.js
2. Dependencies (CRITICAL)
deps-react19-compatibility
- Upgrade dependencies for React 19 compatibility
3. Routing (CRITICAL)
- - Convert components to file-based routes
- - Use [param] syntax for dynamic segments
- - Use [...slug] for catch-all routes
routing-optional-catch-all
- Use [[...slug]] for optional catch-all
- - Use (group) folders for organization
- - Use @slot for parallel routes
routing-intercepting-routes
- Use (..) for intercepting routes
- - Replace react-router Link with next/link
routing-programmatic-navigation
- Replace useNavigate with useRouter
- - Replace useParams with Next.js params
routing-use-search-params
- Replace useSearchParams properly
- - Convert nested routes to layouts
- - Add loading.tsx for suspense
- - Add error.tsx for error handling
- - Add not-found.tsx for 404 pages
- - Handle hash-based routing for client-only apps
- - Implement protected route patterns
4. Data Fetching (CRITICAL)
- - Convert useEffect fetches to Server Components
- - Convert useEffect to getServerSideProps
- - Convert useEffect to getStaticProps
- - Keep client fetches with proper patterns
- - Use Server Actions for mutations
- - Configure data revalidation strategies
- - Use Suspense for streaming data
- - Fetch data in parallel on server
- - Handle sequential data dependencies
- - Configure fetch caching behavior
- - Initialize client-only libraries in useEffect
5. Components (HIGH)
- - Add 'use client' directive for client components
components-server-default
- Understand server components are default
components-boundary-placement
- Place client boundaries strategically
- - Use composition to minimize client JS
- - Interleave server and client components
components-props-serialization
- Ensure props are serializable
components-children-pattern
- Pass server components as children
components-context-providers
- Handle Context providers properly
- - Wrap third-party client components
6. Environment Variables (HIGH)
- - Change REACTAPP to NEXTPUBLIC
- - Use non-prefixed vars for server-only
- - Use runtime configuration when needed
- - Understand .env file loading order
- - Understand build-time vs runtime env vars
- - Validate required environment variables
7. Styling (HIGH)
- - Move global CSS to app/layout.tsx
- - CSS Modules work with minor changes
- - Configure Sass support
- - Configure Tailwind CSS
- - Handle CSS-in-JS libraries
styling-styled-components
- Configure styled-components for SSR
- - Configure Emotion for SSR
- - Import component styles properly
- - Configure PostCSS
styling-scss-global-syntax
- Use :global only in CSS Modules
- - Control CSS import order in layouts
styling-dark-mode-hydration
- Handle dark mode without hydration mismatch
8. Public Assets (MEDIUM)
- - Public folder works the same way
- - Use static imports for assets
- - Reference assets without public prefix
- - Place favicon in app directory
- - Configure web app manifest
9. Images (MEDIUM)
- - Replace img with next/image
images-required-dimensions
- Provide width and height
- - Use fill for responsive images
- - Use priority for LCP images
- - Configure blur placeholders
- - Configure remote image domains
- - Configure custom image loaders
- - Understand automatic optimization
10. Fonts (MEDIUM)
- - Use next/font for optimization
- - Load Google Fonts properly
- - Load local font files
- - Configure variable fonts
- - Configure font-display strategy
- - Understand automatic font preloading
11. SEO & Metadata (MEDIUM)
- - Use Metadata API instead of react-helmet
- - Generate dynamic metadata
- - Configure Open Graph metadata
- - Configure Twitter Card metadata
- - Add structured data (JSON-LD)
- - Set canonical URLs
- - Configure robots meta tags
- - Generate sitemap.xml
- - Migrate from next/head to Metadata
12. API Routes (MEDIUM)
- - Create Route Handlers in app/api
- - Export named functions for HTTP methods
- - Parse request body properly
- - Access query parameters
- - Access headers and cookies
- - Return proper response types
- - Implement middleware patterns
- - Configure CORS properly
- - Implement rate limiting
13. State Management (MEDIUM)
- - Context requires 'use client'
- - Zustand works with hydration care
- - Configure Redux with Next.js
- - Configure Jotai properly
- - Configure Recoil properly
- - Use URL for shareable state
- - Minimize client state with RSC
- - Handle state persistence
14. Integrations (MEDIUM)
- - Migrate Sentry error monitoring
15. Testing (LOW)
- - Update Jest configuration
testing-react-testing-library
- RTL works the same
testing-server-components
- Test Server Components
testing-client-components
- Test Client Components
- - Test async components
- - Mock Next.js modules
- - Configure Cypress for Next.js
- - Configure Playwright for Next.js
- - Test API Route Handlers
16. Build & Deployment (LOW)
- - Update build scripts
- - Understand build output
- - Configure standalone output
- - Configure static export
- - Analyze bundle size
- - Deploy to Vercel
- - Configure Docker deployment
17. Common Gotchas (HIGH)
- - Handle window/document in SSR
gotchas-hydration-mismatch
- Fix hydration mismatches
gotchas-use-effect-timing
- Understand useEffect in Next.js
- - Check router.isReady for query params
- - Use next/dynamic properly
- - Edge vs Node.js runtime
- - Middleware runs on edge
gotchas-static-generation
- Static vs dynamic rendering
- - Handle redirects properly
- - Set response headers
- - Handle cookies in RSC
- - Handle Turbopack compatibility issues
- - Fix empty module exports for isolatedModules
gotchas-nullish-coalescing
- Fix nullish coalescing runtime errors
gotchas-react19-class-components
- Fix React 19 class component this binding
- - Handle React 19 ref prop changes
gotchas-websocket-optional-deps
- Handle WebSocket native dependency bundling
gotchas-auth-race-conditions
- Guard against auth/API race conditions
gotchas-auth-state-gating
- Wait for auth state before checking roles
gotchas-configuration-idempotency
- Ensure configuration idempotency with useRef
gotchas-hydration-nested-interactive
- Avoid nested interactive elements
gotchas-router-push-timing
- Never call router.push during render
gotchas-infinite-rerender
- Prevent infinite re-render loops
gotchas-provider-hierarchy
- Configure provider hierarchy correctly
Pre-Migration Checklist
Before starting migration, scan the codebase for patterns that need special handling:
bash
# Check for WebSocket libraries (needs webpack fallback config)
grep -E "(socket\.io|\"ws\")" package.json
# Check for SCSS :export syntax (may need --webpack flag)
grep -r ":export" --include="*.scss" src/
# Check for SVG ReactComponent imports (needs SVGR config)
grep -r "ReactComponent" --include="*.ts" --include="*.tsx" src/
# List all REACT_APP_ environment variables
grep -roh "REACT_APP_[A-Z_]*" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" src/ | sort -u
# Check for Redux extraReducers using object notation (must convert to builder pattern for RTK v2)
grep -r "extraReducers:" --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx" src/
# Check for /app/ paths that need updating if using (app) route group
grep -rE "(href|to|push|replace|redirect).*['\"]\/app\/" --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx" src/
Scan Results to Rule Mapping:
| Scan Result | Rules to Read |
|---|
| socket.io or ws in package.json | gotchas-websocket-optional-deps
, |
| in SCSS files | |
| SVG imports | |
| variables found | |
| found | (RTK v2 builder callback required) |
| paths in navigation | (update paths for route groups) |
How to Use
Read individual rule files for detailed explanations and code examples:
rules/setup-initial-structure.md
rules/routing-basic-pages.md
rules/data-useeffect-to-rsc.md
Each rule file contains:
- Brief explanation of the migration step
- CRA "before" code example
- Next.js "after" code example
- Additional context and gotchas
Migration Order
For best results, migrate in this order:
- Setup - Initialize Next.js project structure
- Routing - Convert React Router to file-based routing
- Environment Variables - Update env var prefixes
- Components - Add 'use client' directives where needed
- Data Fetching - Convert useEffect to server patterns
- Styling - Move global CSS, configure CSS-in-JS
- Images & Fonts - Adopt Next.js optimizations
- SEO - Migrate to Metadata API
- API Routes - Create Route Handlers
- Testing - Update test configuration
Post-Migration Verification Checklist
After migration, verify the application works correctly:
Core Functionality:
Client-Side Features:
Routing (if applicable):
Real-Time Features (if applicable):
Integrations (if applicable):
PWA (if applicable):
Performance: