Next.js
Next.js App Router patterns including server actions, middleware, and API route handlers.
100 snippets
Showing 100 of 100 snippets
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Best for: CRUD API endpoints
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Best for: Dashboard access control
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Best for: Blog post creation
Dynamic OG Image Generation
Generate Open Graph images on-the-fly using Next.js ImageResponse with custom fonts and dynamic content.
Best for: Social media sharing
Edge Middleware Geolocation
Use Vercel Edge geolocation headers to personalize content based on the visitor's country and city.
Best for: GDPR consent flows
On-Demand ISR Revalidation
Trigger incremental static regeneration via API route with secret token validation for instant cache purge.
Best for: CMS content updates
Protected Page with Server Redirect
Server Component that checks auth status and redirects unauthenticated users before rendering any content.
Best for: Dashboard pages
Reusable Metadata Factory
Factory function to generate consistent SEO metadata across all pages with Open Graph and canonical URLs.
Best for: Consistent page SEO
Streaming API Response
Stream long-running API responses using ReadableStream and TransformStream for real-time data delivery.
Best for: AI response streaming
Parallel Routes Layout
Next.js parallel routes pattern to render multiple page slots simultaneously in a shared layout.
Best for: Dashboard multi-panel layouts
Edge Middleware Rate Limiter
Rate limit API requests at the edge using a sliding window counter with configurable thresholds.
Best for: API abuse prevention
Cached Fetch with Revalidation
Fetch external data in Server Components with time-based revalidation and error boundaries.
Best for: CMS content fetching
NextAuth Session Check Pattern
Check authentication status in Server Components and redirect unauthorized users with NextAuth.js.
Best for: Protected pages
Next.js Image Optimization Patterns
Use next/image with responsive sizes, blur placeholders, and priority loading for optimal Core Web Vitals.
Best for: Hero images
Environment Variable Validation
Validate required environment variables at build time with type-safe access and descriptive errors.
Best for: App startup checks
Redirect Matrix in next.config
Define URL redirect rules in next.config.ts for SEO migration, vanity URLs, and path normalization.
Best for: URL migration after redesign
Partial Prerendering with Suspense
Combine static shells with streamed dynamic content using React Suspense for instant page loads.
Best for: E-commerce product pages
Server Action with Revalidation
Mutate data with Server Actions and revalidate cached paths or tags for instant UI updates.
Best for: Form submissions
Intercepting Routes Modal
Show content in a modal on soft navigation while preserving the full page on hard navigation.
Best for: Photo gallery modals
Multi-Zone Application Setup
Compose multiple Next.js apps under one domain using rewrites for micro-frontend architecture.
Best for: Team-owned sub-apps
Next.js Parallel Routes Layout
Use parallel routes with named slots to render multiple pages simultaneously in a layout.
Best for: Dashboard layouts with independent loading states
Next.js Intercepting Routes for Modals
Implement modal patterns with intercepting routes that work with both soft and hard navigation.
Best for: Image gallery modals with shareable URLs
Next.js Server Actions with Forms
Use Server Actions for form handling with validation, optimistic updates, and error handling.
Best for: Form submissions without API routes
Next.js Streaming with Suspense
Stream server components with Suspense boundaries for progressive page loading and better TTFB.
Best for: Progressive loading for data-heavy dashboards
Next.js Image Optimization Patterns
Advanced next/image usage with responsive sizes, blur placeholders, and custom loaders.
Best for: Optimizing Core Web Vitals with proper image loading
Next.js Error Handling Patterns
Implement error.tsx, not-found.tsx, and global-error.tsx for comprehensive error handling.
Best for: Graceful error recovery in nested layouts
Next.js Route Handlers (API Routes)
Build RESTful API endpoints using Next.js App Router route handlers with typed responses.
Best for: Building REST APIs within a Next.js application
Next.js Dynamic OG Image Generation
Generate dynamic Open Graph images at build time using next/og for social media sharing.
Best for: Dynamic social media preview images
Next.js Middleware for Authentication
Protect routes with Next.js middleware using token verification and role-based redirects.
Best for: Protecting authenticated routes at the edge
Next.js ISR & On-Demand Revalidation
Configure Incremental Static Regeneration with time-based and on-demand revalidation strategies.
Best for: Caching CMS content with periodic refresh
Loading UI with Skeleton Screens
Create loading.tsx skeleton screens for instant navigation feedback with Next.js App Router.
Best for: Route transition loading states
Custom Not Found Page
Create a custom not-found.tsx with search suggestions, popular links, and a return home button.
Best for: Custom 404 error pages
Global Error Boundary Page
Handle uncaught errors gracefully with global-error.tsx including error logging and recovery.
Best for: Production error recovery
Route Groups for Layout Organization
Use route groups to share layouts across routes without affecting URL structure.
Best for: Marketing vs. dashboard layouts
Caching Strategies in Next.js
Master Next.js caching with fetch cache, unstable_cache, revalidatePath, and revalidateTag patterns.
Best for: ISR page caching
Middleware Chain Pattern
Compose multiple middleware functions for auth, rate limiting, and geolocation in Next.js middleware.
Best for: Auth guard middleware
SEO Metadata Patterns
Generate dynamic SEO metadata with Open Graph, Twitter cards, JSON-LD, and canonical URLs.
Best for: Dynamic page SEO
API Route Rate Limiting
Add rate limiting to Next.js API routes with sliding window, IP-based limits, and custom responses.
Best for: API abuse prevention
Dynamic Sitemap Generation
Generate dynamic XML sitemaps from data sources with priority, changefreq, and sitemap index support.
Best for: Automated sitemap generation
Server/Client Component Patterns
Correctly compose server and client components with data fetching, interactivity, and composition patterns.
Best for: RSC architecture planning
Dynamic Import and Code Splitting
Use next/dynamic for lazy loading components with custom loading states, SSR control, and named exports.
Best for: Reducing initial bundle size
Form with Server Action Validation
Build forms using Next.js server actions with server-side validation, error handling, and useActionState.
Best for: Contact form submissions
Parallel Data Fetching in Server Components
Fetch multiple data sources in parallel using Promise.all in Next.js server components for faster page loads.
Best for: dashboard pages
Redirect After Server Action
Use redirect() inside a server action to navigate after form submission in Next.js App Router.
Best for: form submissions
generateStaticParams for Dynamic Routes
Pre-render dynamic routes at build time using generateStaticParams with fallback handling.
Best for: blog pages
Middleware Geo-based Redirect
Redirect users based on their geographic location using Next.js edge middleware.
Best for: internationalization
Streaming with Loading UI and Suspense
Use loading.tsx and React Suspense to stream UI progressively in Next.js App Router.
Best for: dashboards
Catch-All and Optional Catch-All Routes
Handle dynamic nested routes with catch-all [...slug] and optional [[...slug]] segments.
Best for: documentation sites
Font Optimization with next/font
Use next/font for automatic self-hosted font optimization with zero layout shift.
Best for: custom typography
Route Handler Response Helpers
Common response patterns for Next.js route handlers with proper status codes and headers.
Best for: API route handlers
URL Rewrite Proxy Pattern
Use next.config.js rewrites to proxy API calls and avoid CORS issues in development and production.
Best for: API proxying
Server-Only Utility Functions
Ensure utility functions only run on the server using the server-only package to prevent client leakage.
Best for: protecting secrets
useFormStatus for Pending UI States
Use useFormStatus hook to show loading states during server action form submissions.
Best for: form submission UX
useOptimistic for Instant UI Updates
Use useOptimistic hook for instant UI feedback while server actions process in the background.
Best for: todo lists
Dynamic Metadata with generateMetadata
Generate dynamic SEO metadata based on page params using generateMetadata in Next.js App Router.
Best for: blog SEO
Next Image Responsive Patterns
Use next/image with responsive sizes, blur placeholders, and priority loading for optimal image delivery.
Best for: responsive images
Error Handling with error.tsx and not-found.tsx
Handle errors gracefully with error.tsx boundaries and not-found.tsx pages in App Router.
Best for: error boundaries
Template vs Layout for Re-rendering
Use template.tsx instead of layout.tsx when you need fresh state on every navigation.
Best for: page transitions
Search Params in Server and Client Components
Handle URL search params in both server and client components with type-safe parsing.
Best for: product filters
Cookies and Headers in Server Components
Read and set cookies and headers in Next.js server components and route handlers.
Best for: theme preferences
Cache Tags and On-Demand Revalidation
Tag cached data with identifiers and revalidate specific cache entries on demand.
Best for: CMS webhooks
Data Caching with unstable_cache
Cache database queries and expensive computations with unstable_cache for server-side memoization.
Best for: database query caching
Authentication Middleware with Session Check
Protect routes with middleware that validates session tokens and redirects unauthenticated users.
Best for: route protection
Streaming Response from Route Handler
Stream large responses from Next.js route handlers using ReadableStream for real-time data.
Best for: real-time updates
Server Action Validation with Zod
Validate form data in server actions using Zod schemas with type-safe error handling.
Best for: contact forms
Parallel Routes for Modal Pattern
Implement modal dialogs using parallel routes and route interception for shareable modal URLs.
Best for: photo galleries
File Upload with Server Action
Handle file uploads using server actions with validation, size limits, and storage.
Best for: image uploads
Internationalization (i18n) Routing
Implement locale-based routing with middleware detection and dictionary loading.
Best for: multi-language websites
Rate Limiter for Edge Functions
Implement sliding window rate limiting in Next.js middleware using in-memory or KV store.
Best for: API protection
Infinite Scroll with Server Actions
Implement infinite scroll using server actions with cursor-based pagination.
Best for: social feeds
Active Navigation Link Component
Build a navigation component that highlights the active route using usePathname.
Best for: navigation menus
Draft Mode for CMS Preview
Enable draft mode to preview unpublished CMS content in production with cookie-based toggling.
Best for: CMS preview
Multi-Tenant App with Subdomains
Build a multi-tenant application using middleware to resolve tenant from subdomain.
Best for: SaaS platforms
Script Component Loading Strategies
Load third-party scripts efficiently with next/script using different loading strategies.
Best for: analytics
Environment Variable Validation with Zod
Validate environment variables at build time using Zod to catch misconfigurations early.
Best for: build-time validation
Link Prefetching Strategies
Control route prefetching behavior with next/link for optimal navigation performance.
Best for: navigation optimization
Content Security Policy Headers
Configure strict CSP and security headers in Next.js for production-grade security.
Best for: production security
OG Image Generation at the Edge
Generate dynamic Open Graph images using @vercel/og with custom layouts and fonts.
Best for: social media cards
Server to Client Component Data Passing
Pass data from server components to client components using props and serialization patterns.
Best for: data hydration
Route Handler with CORS Support
Add CORS headers to Next.js route handlers for cross-origin API access.
Best for: external API consumers
Testing Server Components
Test Next.js server components and server actions using testing-library and mocks.
Best for: unit testing
Server Component Composition Patterns
Compose server and client components effectively with the donut pattern and children pass-through.
Best for: interactive layouts
MDX Blog with Next.js
Set up MDX support for a blog with custom components, frontmatter, and syntax highlighting.
Best for: technical blogs
Dynamic Sitemap Generation
Generate a comprehensive sitemap.xml from dynamic routes and database content.
Best for: SEO optimization
Webhook Handler with Signature Verification
Handle incoming webhooks with signature verification and idempotent processing.
Best for: payment webhooks
Static Export Configuration
Configure Next.js for static export with output: 'export' for deployment to static hosts.
Best for: Cloudflare Pages
NextJS Technique 37
Advanced NextJS pattern 37
Best for: performance
NextJS Technique 38
Advanced NextJS pattern 38
Best for: performance
NextJS Technique 39
Advanced NextJS pattern 39
Best for: performance
NextJS Technique 40
Advanced NextJS pattern 40
Best for: performance
NextJS Technique 41
Advanced NextJS pattern 41
Best for: performance
NextJS Technique 42
Advanced NextJS pattern 42
Best for: performance
NextJS Technique 43
Advanced NextJS pattern 43
Best for: performance
NextJS Technique 44
Advanced NextJS pattern 44
Best for: performance
NextJS Technique 45
Advanced NextJS pattern 45
Best for: performance
NextJS Technique 46
Advanced NextJS pattern 46
Best for: performance
NextJS Technique 47
Advanced NextJS pattern 47
Best for: performance
NextJS Technique 48
Advanced NextJS pattern 48
Best for: performance
NextJS Technique 49
Advanced NextJS pattern 49
Best for: performance
NextJS Technique 50
Advanced NextJS pattern 50
Best for: performance