Loading states and streaming provide instant feedback and progressive rendering for better perceived performance. loading.tsx creates instant loading UI using React Suspense - automatically wraps page.tsx in Suspense boundary. File structure: app/dashboard/loading.tsx shows while dashboard page loads. Streaming: progressively render UI chunks as they become ready, sending HTML incrementally to client. Suspense boundaries: wrap slow components: <Suspense fallback={
Next.js Batch2 FAQ & Answers
12 expert Next.js Batch2 answers researched from official documentation. Every answer cites authoritative sources you can verify.
unknown
12 questionsMetadata API provides type-safe, static and dynamic SEO control. Static metadata: export const metadata: Metadata = { title: 'Page Title', description: 'Page description', keywords: ['next.js', 'seo'] } in layout.tsx or page.tsx. Dynamic metadata: export async function generateMetadata({ params }): Promise
next/image component provides automatic image optimization with built-in features: lazy loading (defers off-screen images until scrolled into view), responsive images (auto-generates multiple sizes via srcset), automatic format selection (WebP/AVIF based on browser support), size optimization (compresses images), blur placeholder for better UX. Required props: src, alt (accessibility/SEO), width/height (or fill for dynamic containers). Priority prop: add priority to above-the-fold images to preload them (disables lazy loading). Sizes attribute for responsive layouts: sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw" ensures correct image size delivered per viewport - dramatically reduces bandwidth. Fill mode: for dynamic containers, use fill with parent having position: relative. Placeholder options: blur with blurDataURL for smooth loading experience. Remote images: configure domains in next.config.js under images.remotePatterns. Quality: default 75 (good balance), use quality={90} for hero images. Loading strategies: lazy (default, best for most), eager (immediate load), priority (preload for LCP). Modern formats: Next.js automatically serves WebP (25-35% smaller than JPEG) and AVIF (50% smaller) when browser supports. Performance impact: properly configured images improve Core Web Vitals significantly - can improve LCP by 20-40%. Production best practices: always set explicit width/height to prevent layout shift (CLS), use sizes for responsive images to avoid serving oversized images on mobile, enable blur placeholders for perceived performance, configure CDN for image optimization at scale. Common mistake: not setting sizes attribute causes browser to download full-size image on mobile (wastes bandwidth). Image component is essential for production Next.js apps - can reduce image bandwidth by 60-80% vs standard img tags.
ISR updates static pages after build without rebuilding entire site, combining static performance with dynamic data freshness. Two revalidation strategies: (1) Time-based revalidation: export const revalidate = 3600 (seconds) at page/layout level, or per-request: fetch(url, { next: { revalidate: 3600 } }). First request serves cached page, triggers background regeneration, subsequent requests get fresh page. Choose interval based on content: blogs (1 hour), e-commerce (5-10 minutes), news (1 minute). (2) On-demand revalidation (recommended for event-driven updates): revalidatePath('/blog/post-1') after CMS update, or revalidateTag('posts') for tagged cache invalidation. On-demand enables instant cache updates without waiting for time interval. Multiple fetch requests: lowest revalidate time applies to ISR, but individual Data Cache respects each fetch's revalidate setting. Path accuracy critical: revalidate exact path (/post/1 not /post-1) - middleware won't run for ISR requests. Error handling: if regeneration fails, last successful data continues serving, Next.js retries on next request. Benefits: static speed (CDN cacheable), fresh content (background updates), scalable (no server load spike), cost-effective (fewer builds). Use cases: blogs (update post after CMS change), e-commerce (price/inventory updates), marketing pages (A/B test updates), documentation (publish updates). Performance: 200ms average response (cached) vs 1-2s (SSR). Avoid very short intervals (<60s) - floods server, consider SSR for time-sensitive data (stock prices, live scores). Production pattern: combine time-based baseline (1 hour) with on-demand revalidation for instant updates when content changes. ISR is Next.js's unique feature - not available in other frameworks, provides best balance of static performance and dynamic freshness.
Middleware runs before request completes on Edge Runtime (fast, globally distributed). Create middleware.ts in project root, export default function or middleware function. Use for: redirects, rewrites, headers modification, cookies, A/B testing, internationalization routing, bot protection. CRITICAL 2025 UPDATE: Due to CVE-2025-29927 security vulnerability, middleware is NO LONGER recommended for authentication or business logic. New pattern: use Data Access Layer for auth checks close to data access, or verify auth in API routes/Server Actions. Middleware should be lightweight - only routing decisions (redirects/rewrites). Matcher pattern: export const config = { matcher: ['/dashboard/:path*', '/api/:path*'] } - scopes middleware to specific routes (critical for performance, prevents running on every request). Edge Runtime limitations: no Node.js core modules, no database queries (use for routing only), can't do heavy computation (increases latency for all requests). NextResponse API: NextResponse.redirect(url) for redirects, NextResponse.rewrite(url) for internal rewrites, response.cookies.set() for cookie manipulation. Execution order: runs before caching, before authentication, before API routes. Auth.js edge pattern: use lazy initialization with standalone client (no adapter) for edge middleware, separate full client with database adapter for API routes. Performance: keep middleware fast (<50ms execution), use matcher to limit scope, avoid database calls, minimize external API calls. Production best practices 2025: (1) Use middleware ONLY for routing/redirects, (2) Move authentication to Data Access Layer or API routes, (3) Always use matcher to scope properly, (4) Monitor middleware latency in production, (5) Keep middleware code minimal and fast. Common mistake: putting authentication logic in middleware (no longer safe), doing database queries in middleware (not supported in Edge Runtime). Next.js 15.5: Node.js Middleware runtime now stable but still recommended to keep middleware lightweight. Migration path: if using middleware for auth, move checks to layout.tsx Server Component or create Data Access Layer function called from Server Components.
Parallel routes render multiple pages simultaneously in same layout using slot syntax (@folder). Create slots: app/@analytics/page.tsx, app/@dashboard/page.tsx, then reference in layout:
Loading states and streaming provide instant feedback and progressive rendering for better perceived performance. loading.tsx creates instant loading UI using React Suspense - automatically wraps page.tsx in Suspense boundary. File structure: app/dashboard/loading.tsx shows while dashboard page loads. Streaming: progressively render UI chunks as they become ready, sending HTML incrementally to client. Suspense boundaries: wrap slow components: <Suspense fallback={
Metadata API provides type-safe, static and dynamic SEO control. Static metadata: export const metadata: Metadata = { title: 'Page Title', description: 'Page description', keywords: ['next.js', 'seo'] } in layout.tsx or page.tsx. Dynamic metadata: export async function generateMetadata({ params }): Promise
next/image component provides automatic image optimization with built-in features: lazy loading (defers off-screen images until scrolled into view), responsive images (auto-generates multiple sizes via srcset), automatic format selection (WebP/AVIF based on browser support), size optimization (compresses images), blur placeholder for better UX. Required props: src, alt (accessibility/SEO), width/height (or fill for dynamic containers). Priority prop: add priority to above-the-fold images to preload them (disables lazy loading). Sizes attribute for responsive layouts: sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw" ensures correct image size delivered per viewport - dramatically reduces bandwidth. Fill mode: for dynamic containers, use fill with parent having position: relative. Placeholder options: blur with blurDataURL for smooth loading experience. Remote images: configure domains in next.config.js under images.remotePatterns. Quality: default 75 (good balance), use quality={90} for hero images. Loading strategies: lazy (default, best for most), eager (immediate load), priority (preload for LCP). Modern formats: Next.js automatically serves WebP (25-35% smaller than JPEG) and AVIF (50% smaller) when browser supports. Performance impact: properly configured images improve Core Web Vitals significantly - can improve LCP by 20-40%. Production best practices: always set explicit width/height to prevent layout shift (CLS), use sizes for responsive images to avoid serving oversized images on mobile, enable blur placeholders for perceived performance, configure CDN for image optimization at scale. Common mistake: not setting sizes attribute causes browser to download full-size image on mobile (wastes bandwidth). Image component is essential for production Next.js apps - can reduce image bandwidth by 60-80% vs standard img tags.
ISR updates static pages after build without rebuilding entire site, combining static performance with dynamic data freshness. Two revalidation strategies: (1) Time-based revalidation: export const revalidate = 3600 (seconds) at page/layout level, or per-request: fetch(url, { next: { revalidate: 3600 } }). First request serves cached page, triggers background regeneration, subsequent requests get fresh page. Choose interval based on content: blogs (1 hour), e-commerce (5-10 minutes), news (1 minute). (2) On-demand revalidation (recommended for event-driven updates): revalidatePath('/blog/post-1') after CMS update, or revalidateTag('posts') for tagged cache invalidation. On-demand enables instant cache updates without waiting for time interval. Multiple fetch requests: lowest revalidate time applies to ISR, but individual Data Cache respects each fetch's revalidate setting. Path accuracy critical: revalidate exact path (/post/1 not /post-1) - middleware won't run for ISR requests. Error handling: if regeneration fails, last successful data continues serving, Next.js retries on next request. Benefits: static speed (CDN cacheable), fresh content (background updates), scalable (no server load spike), cost-effective (fewer builds). Use cases: blogs (update post after CMS change), e-commerce (price/inventory updates), marketing pages (A/B test updates), documentation (publish updates). Performance: 200ms average response (cached) vs 1-2s (SSR). Avoid very short intervals (<60s) - floods server, consider SSR for time-sensitive data (stock prices, live scores). Production pattern: combine time-based baseline (1 hour) with on-demand revalidation for instant updates when content changes. ISR is Next.js's unique feature - not available in other frameworks, provides best balance of static performance and dynamic freshness.
Middleware runs before request completes on Edge Runtime (fast, globally distributed). Create middleware.ts in project root, export default function or middleware function. Use for: redirects, rewrites, headers modification, cookies, A/B testing, internationalization routing, bot protection. CRITICAL 2025 UPDATE: Due to CVE-2025-29927 security vulnerability, middleware is NO LONGER recommended for authentication or business logic. New pattern: use Data Access Layer for auth checks close to data access, or verify auth in API routes/Server Actions. Middleware should be lightweight - only routing decisions (redirects/rewrites). Matcher pattern: export const config = { matcher: ['/dashboard/:path*', '/api/:path*'] } - scopes middleware to specific routes (critical for performance, prevents running on every request). Edge Runtime limitations: no Node.js core modules, no database queries (use for routing only), can't do heavy computation (increases latency for all requests). NextResponse API: NextResponse.redirect(url) for redirects, NextResponse.rewrite(url) for internal rewrites, response.cookies.set() for cookie manipulation. Execution order: runs before caching, before authentication, before API routes. Auth.js edge pattern: use lazy initialization with standalone client (no adapter) for edge middleware, separate full client with database adapter for API routes. Performance: keep middleware fast (<50ms execution), use matcher to limit scope, avoid database calls, minimize external API calls. Production best practices 2025: (1) Use middleware ONLY for routing/redirects, (2) Move authentication to Data Access Layer or API routes, (3) Always use matcher to scope properly, (4) Monitor middleware latency in production, (5) Keep middleware code minimal and fast. Common mistake: putting authentication logic in middleware (no longer safe), doing database queries in middleware (not supported in Edge Runtime). Next.js 15.5: Node.js Middleware runtime now stable but still recommended to keep middleware lightweight. Migration path: if using middleware for auth, move checks to layout.tsx Server Component or create Data Access Layer function called from Server Components.
Parallel routes render multiple pages simultaneously in same layout using slot syntax (@folder). Create slots: app/@analytics/page.tsx, app/@dashboard/page.tsx, then reference in layout: