Title: Nextjs Framework — LearnCoachAssist

Q: What is Next.js?
A: Next.js is a React framework created by Vercel that provides features like server-side rendering, static site generation, file-based routing, and API routes out of the box. It simplifies building production-ready React applications.

Q: What is the App Router in Next.js?
A: The App Router (introduced in Next.js 13) uses the app/ directory and supports React Server Components, nested layouts, streaming, and colocation of files. It replaces the older Pages Router (pages/ directory).

Q: How does file-based routing work in the App Router?
A: Routes are defined by the folder structure inside app/. A route is created by adding a page.tsx file inside a folder. For example, app/about/page.tsx maps to the /about route.

Q: What is a Server Component in Next.js?
A: A Server Component renders on the server and sends HTML to the client. It is the default in the App Router. Server Components can directly access databases, read files, and fetch data without exposing secrets to the client.

Q: What is a Client Component in Next.js?
A: A Client Component is declared with "use client" at the top of the file. It runs in the browser and supports interactivity: event handlers, state (useState), effects (useEffect), and browser APIs.

Q: When should you use a Client Component vs a Server Component?
A: Use Client Components when you need:
- Event listeners (onClick, onChange)
- React hooks (useState, useEffect)
- Browser-only APIs
Use Server Components for everything else — data fetching, static content, and accessing backend resources.

Q: What is SSR (Server-Side Rendering) in Next.js?
A: SSR generates HTML on the server at request time. Each incoming request triggers a fresh render. In the App Router, this is the default behavior when a page uses dynamic functions like cookies() or headers().

Q: What is SSG (Static Site Generation) in Next.js?
A: SSG generates HTML at build time. Pages are pre-rendered and served as static files from a CDN. In the App Router, pages without dynamic data are automatically statically generated.

Q: What is ISR (Incremental Static Regeneration)?
A: ISR allows you to update static pages after the site has been built. You set a revalidate time (in seconds) so that stale pages are regenerated in the background. Example: fetch(url, { next: { revalidate: 60 } }).

Q: How do you create a dynamic route in the App Router?
A: Use square brackets in the folder name: app/blog/[slug]/page.tsx. The dynamic segment is available via params:
export default function Page({ params }: { params: { slug: string } })

Q: What is a catch-all route in Next.js?
A: A catch-all route uses [...slug] syntax, e.g., app/docs/[...slug]/page.tsx. It matches /docs/a, /docs/a/b, etc. The params are returned as an array: params.slug = ['a', 'b'].

Q: What is an optional catch-all route?
A: An optional catch-all uses [[...slug]] syntax. It matches the parent route as well, e.g., app/docs/[[...slug]]/page.tsx matches both /docs and /docs/a/b.

Q: What is a layout in the Next.js App Router?
A: A layout.tsx file defines UI that is shared across child routes. Layouts preserve state and do not re-render when navigating between sibling routes. The root layout (app/layout.tsx) is required and wraps the entire app.

Q: What is the difference between layout.tsx and template.tsx?
A: A layout persists across navigations and preserves state. A template (template.tsx) creates a new instance on each navigation — it remounts, re-runs effects, and resets state. Use templates when you need fresh state per route.

Q: How do you handle loading states in the App Router?
A: Create a loading.tsx file in a route segment. Next.js automatically wraps the page in a React Suspense boundary and shows the loading component while the page content is being fetched or streamed.

Q: How do you handle errors in the App Router?
A: Create an error.tsx file (must be a Client Component). It acts as a React Error Boundary and catches errors in its route segment and children. It receives error and reset props to display a fallback and retry.

Q: What is the not-found.tsx file used for?
A: not-found.tsx renders a custom 404 page for a route segment. It is triggered when notFound() is called or when no matching route is found. Place it in app/ for a global 404 page.

Q: How does data fetching work in Server Components?
A: Server Components can use async/await directly:
async function Page() {
  const data = await fetch('https://api.example.com/data');
  return <div>{data}</div>;
}
No need for useEffect or client-side fetching libraries.

Q: What is fetch request deduplication in Next.js?
A: Next.js automatically deduplicates identical fetch requests made during a single render pass. If multiple components fetch the same URL with the same options, only one network request is made and the result is shared.

Q: How do you control caching with fetch in the App Router?
A: Use the cache and next.revalidate options:
- fetch(url, { cache: 'force-cache' }) — cached (default for GET)
- fetch(url, { cache: 'no-store' }) — no caching
- fetch(url, { next: { revalidate: 60 } }) — revalidate every 60s

Q: What are Server Actions in Next.js?
A: Server Actions are async functions that run on the server, defined with "use server". They can be called directly from Client or Server Components to handle form submissions and data mutations without creating API endpoints.

Q: How do you define a Server Action?
A: Add "use server" at the top of an async function or at the top of a module:
async function createUser(formData: FormData) {
  "use server";
  // insert into database
}

Q: How do you use a Server Action with a form?
A: Pass the Server Action as the action prop on a <form>:
<form action={createUser}>
  <input name="email" />
  <button type="submit">Submit</button>
</form>
The form works even without JavaScript enabled.

Q: What are Route Handlers in Next.js?
A: Route Handlers are the App Router equivalent of API routes. Define them in route.ts files (e.g., app/api/users/route.ts). Export named functions like GET, POST, PUT, DELETE that receive a Request object.

Q: How do you create a GET API endpoint in the App Router?
A: Create app/api/hello/route.ts:
export async function GET(request: Request) {
  return Response.json({ message: 'Hello' });
}
This handles GET /api/hello.

Q: Can a route.ts and page.tsx exist in the same folder?
A: No. A route segment cannot have both route.ts and page.tsx. The Route Handler would conflict with the page. Place API routes in a separate folder like app/api/.

Q: What is Next.js Middleware?
A: Middleware runs before a request is completed. Defined in middleware.ts at the project root, it can rewrite URLs, redirect, modify headers, or set cookies. It runs on the Edge runtime for low latency.

Q: How do you define Middleware in Next.js?
A: Create middleware.ts in the project root:
import { NextResponse } from 'next/server';
export function middleware(request) {
  return NextResponse.next();
}
export const config = { matcher: '/dashboard/:path*' };

Q: What is the matcher config in Middleware?
A: The matcher property in the exported config object specifies which routes the middleware applies to. Example: matcher: ['/dashboard/:path*', '/api/:path*'] runs middleware only on those paths.

Q: What is the Next.js Image component?
A: next/image provides an optimized <Image> component that automatically handles lazy loading, responsive sizing, format conversion (WebP/AVIF), and preventing layout shift with required width/height or fill props.

Q: How do you use the Next.js Image component?
A: import Image from 'next/image';
<Image src="/hero.jpg" alt="Hero" width={800} height={600} priority />
The priority prop disables lazy loading for above-the-fold images. Use fill prop for images with unknown dimensions.

Q: What is the purpose of next.config.js?
A: next.config.js (or .mjs/.ts) is the main configuration file for Next.js. It controls settings like image domains, redirects, rewrites, environment variables, webpack customization, and experimental features.

Q: How do you set metadata in the App Router?
A: Export a metadata object or a generateMetadata function from layout.tsx or page.tsx:
export const metadata = {
  title: 'My App',
  description: 'A Next.js app',
};
Next.js merges metadata from parent layouts.

Q: What is generateMetadata used for?
A: generateMetadata is an async function for dynamic metadata. It receives params and can fetch data:
export async function generateMetadata({ params }) {
  const post = await getPost(params.id);
  return { title: post.title };
}

Q: What is generateStaticParams in Next.js?
A: generateStaticParams is used with dynamic routes to define which paths should be statically generated at build time:
export async function generateStaticParams() {
  return [{ slug: 'post-1' }, { slug: 'post-2' }];
}

Q: What is the Link component in Next.js?
A: next/link provides a <Link> component for client-side navigation between routes. It prefetches linked pages in the background for faster transitions:
<Link href="/about">About</Link>

Q: How does prefetching work with the Link component?
A: By default, Next.js prefetches routes linked with <Link> when they enter the viewport. Static routes are fully prefetched; dynamic routes prefetch up to the nearest loading.tsx boundary. Disable with prefetch={false}.

Q: What is the useRouter hook in Next.js App Router?
A: useRouter from next/navigation provides programmatic navigation in Client Components:
- router.push('/path') — navigate
- router.replace('/path') — replace history
- router.refresh() — re-fetch server components
- router.back() — go back

Q: What is the usePathname hook?
A: usePathname from next/navigation returns the current URL pathname as a string (e.g., /dashboard/settings). It is a Client Component hook useful for highlighting active navigation links.

Q: What is the useSearchParams hook?
A: useSearchParams from next/navigation returns a read-only URLSearchParams object for the current URL's query string. Example: const searchParams = useSearchParams(); const q = searchParams.get('q');

Q: What are Route Groups in the App Router?
A: Route Groups use parentheses in folder names, e.g., (marketing). They organize routes without affecting the URL. Useful for applying different layouts to different sections: app/(shop)/layout.tsx vs app/(blog)/layout.tsx.

Q: What are Parallel Routes in Next.js?
A: Parallel Routes use named slots with @folder convention (e.g., @dashboard, @analytics). They allow rendering multiple pages simultaneously in the same layout, useful for dashboards, modals, and split views.

Q: What are Intercepting Routes?
A: Intercepting Routes use (..) convention to intercept a route and display it in a different context — commonly used for modals. For example, clicking a photo shows a modal, but navigating directly shows the full page.

Q: What is streaming in Next.js?
A: Streaming allows the server to send UI in chunks as it becomes ready, rather than waiting for all data. Next.js uses React Suspense boundaries to progressively stream content, improving Time to First Byte (TTFB) and First Contentful Paint (FCP).

Q: How do environment variables work in Next.js?
A: Variables in .env.local are available on the server. To expose a variable to the browser, prefix it with NEXT_PUBLIC_:
- DB_SECRET=xyz — server only
- NEXT_PUBLIC_API_URL=https://... — available in client code

Q: What is the Edge Runtime in Next.js?
A: The Edge Runtime is a lightweight JavaScript runtime for Middleware and Route Handlers. It starts faster than Node.js and runs at CDN edge locations for low latency. Opt in with export const runtime = 'edge';. It has limited Node.js API support.

Q: What is the difference between the Edge and Node.js runtimes?
A: Node.js runtime (default): full Node.js APIs, no cold start limits, runs on the server.
Edge runtime: subset of APIs, faster cold starts, runs at edge locations. Use Edge for simple, latency-sensitive logic; Node.js for complex processing.

Q: How do you redirect in Next.js?
A: Several methods:
- redirect('/path') — in Server Components/Actions (throws internally)
- permanentRedirect('/path') — 308 redirect
- next.config.js redirects — declarative redirects
- Middleware — conditional redirects
- router.push() — client-side redirect

Q: What is revalidatePath in Next.js?
A: revalidatePath('/blog') purges the cached data for a specific path on demand. Use it inside Server Actions or Route Handlers after a mutation to ensure users see fresh content without waiting for the timed revalidation.

Q: What is revalidateTag in Next.js?
A: revalidateTag('posts') purges all cached fetch requests tagged with that label. Tag a fetch with fetch(url, { next: { tags: ['posts'] } }). This enables fine-grained, on-demand cache invalidation across multiple routes.