Skip to content

Next.js Development Patterns

Build production-ready Next.js applications with Cursor IDE and Claude Code. These patterns cover App Router, Server Components, API routes, deployment strategies, and the cutting-edge features that make Next.js the go-to framework for React applications.

  1. Open Cursor and create a new directory
  2. Configure Figma MCP: Settings > MCP > Add Server > http://127.0.0.1:3845/sse
  3. Launch Agent mode (Cmd/Ctrl + I)
  4. Prompt: “Create a Next.js 14 app with App Router, TypeScript, Tailwind CSS, Prisma, and testing setup. Include shadcn/ui components”
  5. Enable YOLO mode for automatic execution
  6. Review the generated next.config.js and project structure
.mcp.json
{
"mcpServers": {
"figma": {
"type": "sse",
"url": "http://127.0.0.1:3845/sse"
}
}
}
.cursor/rules/nextjs-patterns.md
# Next.js Development Rules
## Framework Conventions
- Use App Router (app/ directory)
- Server Components by default
- Client Components only when needed ('use client')
- Colocate components with routes
- Use route groups for organization
## Performance Guidelines
- Implement streaming SSR
- Use dynamic imports for code splitting
- Optimize images with next/image
- Implement proper caching strategies
- Use Partial Prerendering where applicable
## TypeScript Standards
- Strict mode enabled
- Use proper type inference
- Avoid any types
- Implement proper error boundaries
Terminal window
# PRD: Convert Figma designs to Next.js components
# Plan: Use Figma MCP for Server/Client components
"Using Figma MCP, generate Next.js components from the selected design:
1. Determine if it should be Server or Client component
2. Use App Router conventions
3. Apply shadcn/ui components where applicable
4. Extract design tokens for theme"
# Example workflow
"Select the Hero section in Figma and:
- Generate as Server Component (no interactions)
- Use next/image for optimized images
- Apply responsive design with Tailwind
- Extract color and spacing tokens"
// Extract Figma tokens to Next.js theme
"Using Figma MCP get_variable_defs:
1. Get all design system variables
2. Generate tailwind.config.js extensions
3. Create CSS variables for dynamic theming
4. Set up dark mode support"
// Example output: tailwind.config.js
export default {
theme: {
extend: {
colors: {
primary: {
DEFAULT: '#1D4ED8', // Figma: Primary/Blue
dark: '#1E40AF', // Figma: Primary/Dark
light: '#3B82F6' // Figma: Primary/Light
}
},
spacing: {
'section': '5rem', // Figma: Spacing/Section
'component': '2rem' // Figma: Spacing/Component
}
}
}
}

Advanced Routing Structure:

Create a complex routing structure:
1. Marketing pages with (marketing) route group
2. Dashboard with (dashboard) route group and layout
3. API routes in app/api/
4. Parallel routes for modals
5. Intercepting routes for photo gallery
6. Dynamic segments with [...slug]
7. Implement proper loading.tsx and error.tsx
Create server components that:
- Fetch data directly in components
- Use React cache() for deduplication
- Implement streaming with Suspense
- Handle errors with error boundaries
- Use generateStaticParams for SSG
- Implement revalidation strategies
Server Action Example
Implement a complete form system:
1. Server Action for form submission
2. Zod validation on server
3. useFormState for client state
4. useFormStatus for pending states
5. Optimistic updates
6. Error handling with useActionState
7. Revalidation after mutation

File Uploads

Create file upload with Server Actions:
- Handle multipart form data
- Stream to S3/Cloudinary
- Show upload progress
- Generate thumbnails
- Update database

Real-time Updates

Implement real-time features:
- Server-Sent Events setup
- WebSocket integration
- Optimistic UI updates
- Conflict resolution
- Presence indicators

RESTful API Pattern:

Create a complete REST API:
1. CRUD endpoints in app/api/resources/
2. Middleware for authentication
3. Rate limiting with Upstash
4. OpenAPI documentation
5. Type-safe responses
6. Error handling middleware
7. CORS configuration
Set up tRPC with App Router:
1. Create tRPC router
2. App Router integration
3. Type-safe API calls
4. React Query integration
5. WebSocket subscriptions
6. Error handling
7. Authentication context
  1. Provider Configuration

    Set up NextAuth with:
    - Multiple providers (Google, GitHub, Email)
    - Database sessions with Prisma
    - Custom signin/signout pages
    - Role-based access control
    - JWT with refresh tokens
  2. Middleware Protection

    Implement auth middleware:
    - Protect API routes
    - Redirect logic
    - Role checking
    - Session validation
    - Custom headers
Configure Prisma for production:
1. Set up connection pooling
2. Implement soft deletes
3. Add audit fields (createdAt, updatedAt)
4. Create seed scripts
5. Optimize queries with include/select
6. Implement transactions
7. Add database indexes
Create a data access layer:
- Repository pattern for models
- Cached queries with unstable_cache
- Type-safe database calls
- Transaction helpers
- Query builders
- Migration strategies
Optimize static images:
- Use next/image with sizing
- Implement blur placeholders from Figma
- Configure image domains
- Use responsive images
- WebP generation
- CDN integration
# With Figma MCP:
"Extract images from Figma design and:
- Generate optimized next/image components
- Create blur data URLs
- Set proper width/height ratios"
Analyze and optimize bundles:
1. Run bundle analyzer
2. Implement dynamic imports
3. Optimize third-party scripts
4. Tree shake unused code
5. Configure SWC minification
6. Implement route-based chunking
7. Monitor with SpeedCurve
Testing Pattern
Write comprehensive tests:
1. Unit tests with Jest
2. Component tests with React Testing Library
3. Integration tests for API routes
4. E2E tests with Playwright
5. Visual regression with Percy
6. Performance tests
7. Accessibility tests
Create E2E test suite:
- Test critical user flows
- API integration tests
- Authentication flows
- Payment processes
- Error scenarios
- Mobile responsiveness
- Performance benchmarks
Configure for Vercel:
1. Environment variables
2. Preview deployments
3. Edge functions
4. Analytics integration
5. Speed insights
6. Custom domains
7. ISR configuration
Create production Docker setup:
- Multi-stage build
- Standalone output
- Health checks
- Graceful shutdown
- Environment injection
- Security scanning
- Compose configuration
Implement i18n:
1. Set up next-intl
2. Route-based locales
3. Content translation
4. Date/number formatting
5. SEO hreflang tags
6. Language switcher
7. Static generation per locale
Build multi-tenant app:
1. Subdomain detection
2. Database isolation
3. Theme customization
4. Feature flags
5. Tenant-specific middleware
6. Billing integration
7. Admin portal
Implement comprehensive SEO:
- Dynamic metadata API
- Structured data
- Sitemap generation
- robots.txt
- Open Graph images
- Twitter cards
- Schema markup
Set up analytics:
- Vercel Analytics
- Google Analytics 4
- Custom events
- Conversion tracking
- Error tracking with Sentry
- Performance monitoring
- User behavior tracking
Implement error handling:
1. Global error boundary
2. Route-level error.tsx
3. API error responses
4. Logging with winston
5. Sentry integration
6. User-friendly messages
7. Error recovery strategies
Configure caching:
- Route segment config
- Revalidate on demand
- Time-based revalidation
- Cache headers
- CDN caching
- Database query caching
- Redis integration
Migrate from Pages Router:
1. Analyze current routes
2. Convert layouts
3. Update data fetching
4. Migrate API routes
5. Update middleware
6. Test thoroughly
7. Gradual migration strategy