nextjs_batch2 12 Q&As

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 questions
A

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={}>. Multiple Suspense boundaries enable independent streaming - fast content shows immediately, slow content streams in. Benefits: faster First Contentful Paint (FCP) - users see content sooner even if data fetching slow, reduced Time to Interactive (TTI) - page becomes interactive before all content loads, progressive enhancement - works without JavaScript. Server Component streaming: RSCs naturally support streaming, fetch data in components and wrap slow fetches in Suspense. Route segments load independently - /dashboard/analytics can stream separately from /dashboard/users. Parallel data fetching: fetch multiple data sources simultaneously, stream each as ready. Loading patterns: skeleton UI (shows content structure), spinner (simple loading indicator), progress bar (for known duration), shimmer effect (animated placeholder). Production implementation: loading.tsx for instant route-level feedback, Suspense for component-level granular control, parallel data fetching with Promise.all for simultaneous requests. Error handling: error.tsx boundary works with streaming - errors in streamed content trigger nearest error boundary. Real-world example: e-commerce product page - show product details immediately (cached), stream reviews/recommendations as they load. Performance metrics: streaming can reduce perceived load time by 40-60% vs blocking render. Best practices: always provide loading states for async operations, use skeleton UI that matches final content shape, stream non-critical content (reviews, comments, related items), keep critical content (product details, article text) in initial render. Common mistake: wrapping entire page in single Suspense (loses granular streaming benefit) - instead wrap individual slow components.

99% confidence
A

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 { const post = await getPost(params.slug); return { title: post.title, description: post.excerpt, openGraph: { images: [post.image] } }; }. Metadata fields: title (string or template - { template: '%s | Site Name', default: 'Site Name' }), description, keywords, authors, creator, publisher, openGraph (og:title, og:image, og:type), twitter (card, site, creator), robots (index, follow, noindex, nofollow), viewport, themeColor, manifest. File-based metadata: opengraph-image.tsx (dynamic OG images), twitter-image.tsx, favicon.ico, icon.png, apple-icon.png, robots.txt, sitemap.xml, sitemap.ts (dynamic sitemap generation). Nested metadata: merges with parent - child overrides parent fields. Title templates: layout sets template: '%s | Site', page provides title: 'Blog Post' → result: 'Blog Post | Site'. JSON-LD structured data: export default function Page() { const jsonLd = { '@context': 'https://schema.org', '@type': 'Article', headline: 'Title', datePublished: '2025-01-01' }; return <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />; }. Canonical URLs: metadata.alternates.canonical for duplicate content. Multi-language: metadata.alternates.languages for hreflang tags. Image optimization: metadata.openGraph.images accepts width, height, alt for better social sharing. Verification: metadata.verification for Google Search Console, Bing, etc. Dynamic OG images: create opengraph-image.tsx with ImageResponse API - generates images at build or request time with custom text/branding. Production best practices: always set title and description (critical for SEO), use title templates for consistency, implement JSON-LD for rich snippets, generate dynamic OG images for social sharing, set canonical URLs for duplicate content, use metadata.robots to control indexing, monitor in Google Search Console. Performance: static metadata adds no runtime cost, dynamic generateMetadata runs on server only. Common mistake: forgetting title templates (inconsistent titles), not setting OG images (poor social shares), missing JSON-LD (no rich snippets in search).

99% confidence
A

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.

99% confidence
A

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.

99% confidence
A

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.

99% confidence
A

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: {children}{analytics}{dashboard}. Each slot has independent navigation, loading states, error boundaries. Use cases: dashboards with multiple widgets updating independently, split views (inbox + message content), A/B testing (show different content to different users), conditional layouts (authenticated vs guest). Slot props received in layout: children (default slot), plus named slots. Not found handling: default.tsx provides fallback when slot route doesn't match current URL. Parallel routes enable complex UI patterns: sidebar + main content navigating independently, modal overlays with preserved background content, multi-section dashboards. Intercepting routes modify navigation to show different content without changing URL. Syntax: (.) intercepts same level, (..) intercepts one level up, (..)(..) two levels up, (...) intercepts from app root. Modal pattern (most common): clicking product in list shows modal (intercepted route), refreshing page shows full product page. Implementation: app/@modal/(.)product/[id]/page.tsx intercepts, shows modal overlay, app/product/[id]/page.tsx is actual full page. Benefits: better UX (faster perceived navigation with modals), preserved context (background content stays visible), shareable URLs (refresh shows full page). Use cases: photo galleries (lightbox on click, full page on refresh), product quick views (modal preview, full page on refresh), authentication modals (intercepted login, full page fallback), preview panels (document preview modal, full editor on refresh). Advanced patterns: combine parallel + intercepting for complex workflows - e.g., dashboard with multiple sections (@stats, @charts) plus intercepting routes for modals. Production considerations: intercepting only works during navigation (not on direct URL access), refresh always shows non-intercepted full page, ensure full page handles all states (modal might not show server-side props). Performance: parallel routes increase initial bundle but enable better code splitting per slot. Common mistake: relying on intercepting routes for critical functionality (breaks on refresh) - always provide full page fallback.

99% confidence
A

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={}>. Multiple Suspense boundaries enable independent streaming - fast content shows immediately, slow content streams in. Benefits: faster First Contentful Paint (FCP) - users see content sooner even if data fetching slow, reduced Time to Interactive (TTI) - page becomes interactive before all content loads, progressive enhancement - works without JavaScript. Server Component streaming: RSCs naturally support streaming, fetch data in components and wrap slow fetches in Suspense. Route segments load independently - /dashboard/analytics can stream separately from /dashboard/users. Parallel data fetching: fetch multiple data sources simultaneously, stream each as ready. Loading patterns: skeleton UI (shows content structure), spinner (simple loading indicator), progress bar (for known duration), shimmer effect (animated placeholder). Production implementation: loading.tsx for instant route-level feedback, Suspense for component-level granular control, parallel data fetching with Promise.all for simultaneous requests. Error handling: error.tsx boundary works with streaming - errors in streamed content trigger nearest error boundary. Real-world example: e-commerce product page - show product details immediately (cached), stream reviews/recommendations as they load. Performance metrics: streaming can reduce perceived load time by 40-60% vs blocking render. Best practices: always provide loading states for async operations, use skeleton UI that matches final content shape, stream non-critical content (reviews, comments, related items), keep critical content (product details, article text) in initial render. Common mistake: wrapping entire page in single Suspense (loses granular streaming benefit) - instead wrap individual slow components.

99% confidence
A

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 { const post = await getPost(params.slug); return { title: post.title, description: post.excerpt, openGraph: { images: [post.image] } }; }. Metadata fields: title (string or template - { template: '%s | Site Name', default: 'Site Name' }), description, keywords, authors, creator, publisher, openGraph (og:title, og:image, og:type), twitter (card, site, creator), robots (index, follow, noindex, nofollow), viewport, themeColor, manifest. File-based metadata: opengraph-image.tsx (dynamic OG images), twitter-image.tsx, favicon.ico, icon.png, apple-icon.png, robots.txt, sitemap.xml, sitemap.ts (dynamic sitemap generation). Nested metadata: merges with parent - child overrides parent fields. Title templates: layout sets template: '%s | Site', page provides title: 'Blog Post' → result: 'Blog Post | Site'. JSON-LD structured data: export default function Page() { const jsonLd = { '@context': 'https://schema.org', '@type': 'Article', headline: 'Title', datePublished: '2025-01-01' }; return <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />; }. Canonical URLs: metadata.alternates.canonical for duplicate content. Multi-language: metadata.alternates.languages for hreflang tags. Image optimization: metadata.openGraph.images accepts width, height, alt for better social sharing. Verification: metadata.verification for Google Search Console, Bing, etc. Dynamic OG images: create opengraph-image.tsx with ImageResponse API - generates images at build or request time with custom text/branding. Production best practices: always set title and description (critical for SEO), use title templates for consistency, implement JSON-LD for rich snippets, generate dynamic OG images for social sharing, set canonical URLs for duplicate content, use metadata.robots to control indexing, monitor in Google Search Console. Performance: static metadata adds no runtime cost, dynamic generateMetadata runs on server only. Common mistake: forgetting title templates (inconsistent titles), not setting OG images (poor social shares), missing JSON-LD (no rich snippets in search).

99% confidence
A

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.

99% confidence
A

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.

99% confidence
A

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.

99% confidence
A

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: {children}{analytics}{dashboard}. Each slot has independent navigation, loading states, error boundaries. Use cases: dashboards with multiple widgets updating independently, split views (inbox + message content), A/B testing (show different content to different users), conditional layouts (authenticated vs guest). Slot props received in layout: children (default slot), plus named slots. Not found handling: default.tsx provides fallback when slot route doesn't match current URL. Parallel routes enable complex UI patterns: sidebar + main content navigating independently, modal overlays with preserved background content, multi-section dashboards. Intercepting routes modify navigation to show different content without changing URL. Syntax: (.) intercepts same level, (..) intercepts one level up, (..)(..) two levels up, (...) intercepts from app root. Modal pattern (most common): clicking product in list shows modal (intercepted route), refreshing page shows full product page. Implementation: app/@modal/(.)product/[id]/page.tsx intercepts, shows modal overlay, app/product/[id]/page.tsx is actual full page. Benefits: better UX (faster perceived navigation with modals), preserved context (background content stays visible), shareable URLs (refresh shows full page). Use cases: photo galleries (lightbox on click, full page on refresh), product quick views (modal preview, full page on refresh), authentication modals (intercepted login, full page fallback), preview panels (document preview modal, full editor on refresh). Advanced patterns: combine parallel + intercepting for complex workflows - e.g., dashboard with multiple sections (@stats, @charts) plus intercepting routes for modals. Production considerations: intercepting only works during navigation (not on direct URL access), refresh always shows non-intercepted full page, ensure full page handles all states (modal might not show server-side props). Performance: parallel routes increase initial bundle but enable better code splitting per slot. Common mistake: relying on intercepting routes for critical functionality (breaks on refresh) - always provide full page fallback.

99% confidence