Skip to content

Nextjs Framework

100 companion flashcards · AI-assisted study content · Open the deck →

This deck is a focused walkthrough of the Next.js framework, with an emphasis on the modern App Router. The cards cover foundational concepts like routing, layouts, and rendering strategies, and they also dig into the practical differences between Server Components and Client Components. By the end of the deck, you should have a clear mental model of how a Next.js application is structured and how it serves pages to users.

It's a great fit if you are new to Next.js, transitioning from the older Pages Router, or looking to refresh your knowledge before starting a new project. If you already build with React and want to understand how Next.js layers on top of it with features like SSR, SSG, ISR, and file-based routing, you'll find these cards especially useful as a quick reference.

To get the most out of these flashcards, try working through them in short sessions rather than cramming everything at once. Because the topics build on each other, like understanding Server Components before choosing between rendering strategies, spacing your reviews over a few days will help the concepts stick. When a card asks about a comparison, like "Client vs Server Component," take a moment to think of a small example before flipping the answer over.

Pair the deck with a small hands-on project, such as building a simple multi-page app with layouts and dynamic routes, to reinforce what you learn. Even a few lines of code alongside each review session will turn these definitions into lasting familiarity with the framework.

Foundations of Next.js and the App Router

Next.js is a React framework created by Vercel that provides a complete toolkit for building production-ready web applications. It bundles together features that React alone does not offer out of the box, including server-side rendering, static site generation, file-based routing, and API routes. Since version 13, the recommended way to build Next.js applications is through the App Router, which uses an app/ directory and replaces the older Pages Router that relied on pages/. The App Router enables React Server Components, nested layouts, streaming, and the ability to colocate related files such as components, styles, and tests alongside the routes that use them.

The App Router uses the file system as the source of truth for routing. A route is created whenever a folder inside app/ contains a file named page.tsx. For instance, creating app/about/page.tsx exposes the path /about to visitors. This convention removes the need for an explicit routing configuration file and keeps the URL structure visually aligned with the project structure. As you build more complex applications, you can add dynamic segments, layouts, loading states, and error boundaries simply by placing the appropriate special files next to page.tsx in any folder.

To support this file-based approach, Next.js relies on several special filenames that each carry a specific role. Beyond page.tsx, files like layout.tsx, loading.tsx, error.tsx, and not-found.tsx give developers fine-grained control over the user experience at every route segment. Together, these files and the folder structure form a coherent system that lets you build everything from a simple marketing site to a complex dashboard without ever leaving the framework.

Server and Client Components

In the App Router, every component is a Server Component by default. Server Components render on the server and send the resulting HTML to the browser, which means they can directly read files, query databases, and call internal services without ever exposing secrets or backend logic to the client. Because they execute on the server, they do not support React hooks, browser-only APIs, or event listeners; they are intended for fetching data and producing static markup that can be cached and streamed efficiently.

When interactivity is required, you can opt into a Client Component by adding the directive "use client" at the top of the file. Client Components run in the browser and unlock the full React toolkit, including state via useState, side effects via useEffect, event handlers like onClick and onChange, and any browser API such as localStorage or window. The rule of thumb is to keep components as Server Components whenever possible, and only cross the boundary into a Client Component when the feature truly demands interactivity or browser access.

Because Server and Client Components live in the same tree, it is helpful to think of the App Router as a layered system. A Server Component can import and render a Client Component, but the reverse is not possible without careful handling: passing non-serializable values such as functions across the boundary is not allowed. Understanding this mental model helps you decide where to draw the line between server and client logic, and it explains why many common patterns, such as forms wired to Server Actions, can remain largely server-driven while still feeling fully interactive to the user.

Rendering Strategies

Next.js supports several rendering strategies, and the App Router chooses one automatically based on how a page uses dynamic data. Server-Side Rendering, or SSR, generates the HTML on the server for each incoming request. This mode is triggered when a page calls dynamic functions like cookies() or headers(), and it is appropriate when content must reflect per-user state or change frequently. Because every request triggers a fresh render, SSR is the most flexible but also the most expensive option, since the server must do work on every visit.

Static Site Generation, or SSG, generates HTML at build time. Pages without dynamic data are automatically pre-rendered and served as static files from a CDN, which makes them extremely fast and cheap to host. This is the default mode whenever the framework can prove that no request-scoped data is being read. For content that needs the speed of static delivery but also needs to stay reasonably fresh, Next.js offers Incremental Static Regeneration, or ISR.

With ISR, you can set a revalidate interval so that a previously generated page is regenerated in the background after a certain number of seconds. The example fetch(url, { next: { revalidate: 60 } }) instructs Next.js to serve cached content but refresh it every minute. The framework inspects the data access patterns inside your Server Components and picks the strategy that fits, so you can focus on writing the right code and let Next.js optimize delivery behind the scenes.

Advanced Routing Patterns

Beyond the basic folder-to-route mapping, Next.js offers several routing patterns that handle common real-world needs. A dynamic route uses square brackets in the folder name, like app/blog/[slug]/page.tsx. The captured segment is then available on the page component through its params prop, typed as { slug: string }. This is the standard way to build URLs such as /blog/my-first-post where the final segment is determined at request time.

When you need to match an unknown number of segments, you can use a catch-all route by naming the folder [...slug]. A file at app/docs/[...slug]/page.tsx will match /docs/a, /docs/a/b, and /docs/a/b/c, returning the captured segments as an array on params.slug. If you also want the route to match the parent itself, you can wrap the brackets in another pair to make an optional catch-all, written as [[...slug]]. With that syntax, app/docs/[[...slug]]/page.tsx matches both /docs and /docs/anything/here.

For organizing code without affecting URLs, Next.js provides Route Groups, which are folders whose names are wrapped in parentheses such as (marketing). The parentheses are stripped from the URL, so app/(shop)/products/page.tsx is reachable as /products, but you can attach a different layout to the (shop) group than to the rest of the app. Parallel Routes go further by letting a single layout render multiple pages at once using named slots prefixed with the @ symbol, such as @dashboard and @analytics. Closely related are Intercepting Routes, written with parentheses and dots like (..), which intercept a navigation and render a different page in context, typically used to show a photo in a modal when clicked, while preserving the full page when the URL is opened directly.

Layouts, Templates, and Special Files

Layouts are one of the App Router's most powerful features. A layout.tsx file in any folder defines the chrome that wraps every page beneath that segment, such as a navigation bar, footer, or sidebar. Because layouts persist across navigations between their child routes, React state inside a layout survives route changes, providing a snappy and uninterrupted experience. The root layout located at app/layout.tsx is mandatory and wraps the entire application; it is also where you typically set up the <html> and <body> tags.

Templates look similar to layouts but behave very differently. A template.tsx file creates a new instance on every navigation, which means its effects re-run, its local state resets, and the entire component remounts. This is useful when you want each route to start with fresh state, for example an animation that should replay on each page transition or a form that should clear when the user navigates away and back. Choosing between a layout and a template therefore comes down to whether you want state continuity or fresh state.

Beyond layouts and templates, Next.js recognizes a handful of other special files that improve the user experience. Adding a loading.tsx to a route segment automatically wraps the page in a React Suspense boundary, so Next.js can stream the loading UI while the actual content is still being fetched. An error.tsx file, which must be a Client Component, acts as an error boundary that catches errors in its segment and its children, exposing both the error and a reset function so the user can retry. Finally, not-found.tsx provides a custom 404 page that renders when notFound() is called from a Server Component or when no route matches the requested URL. Streaming ties all of this together: the server can send UI in chunks as it becomes ready, rather than waiting for all data to be available, and Suspense boundaries mark where streamed content can be revealed progressively, improving both Time to First Byte and First Contentful Paint.

Data Fetching, Mutations, and Middleware

Data fetching in the App Router is one of the most pleasant developer experiences in modern web frameworks. Server Components can declare themselves async and use await directly on fetch calls or database queries, with no need for useEffect or third-party data libraries. Because the fetch happens on the server, secrets like API keys never leave the machine. Next.js also deduplicates identical fetch requests made during a single render pass: if two components fetch the same URL with the same options, only one network call is made and the result is shared.

Caching behavior can be tuned per request. The default cache: 'force-cache' keeps responses cached indefinitely and applies to GET requests by default. Setting cache: 'no-store' disables caching for fully dynamic data, while the option next: { revalidate: 60 } enables time-based revalidation every sixty seconds. For more precise invalidation, you can tag a fetch with next: { tags: ['posts'] } and later call revalidateTag('posts') from a Server Action or Route Handler to purge every entry that shares that label.

Server Actions provide a way to handle mutations without writing API endpoints. They are async functions annotated with the "use server" directive, either inline at the top of a function or at the top of an entire module, and they can be invoked directly from forms. Passing a Server Action as the action prop of a <form> element lets the form submit even when JavaScript is disabled, making applications progressively enhanced by default.

When you do need a traditional HTTP endpoint, Route Handlers fill that role: a route.ts file exports named functions such as GET, POST, PUT, and DELETE, each receiving a standard Request object. A route segment cannot contain both route.ts and page.tsx simultaneously, so API endpoints are typically grouped under app/api/. Middleware, declared in middleware.ts at the project root, runs before a request is completed and can rewrite URLs, redirect, modify headers, or set cookies. It runs on the Edge runtime and is scoped to specific paths via the matcher configuration option, making it ideal for authentication checks and lightweight rewrites.

Navigation Hooks and Components

Navigation is a first-class concern in Next.js, and the framework provides both declarative and programmatic ways to move between routes. The <Link> component from next/link is the preferred way to navigate. It performs client-side transitions without a full page reload and, by default, prefetches the destination when the link enters the viewport, so the next page is essentially instant.

Static routes are fully prefetched, while dynamic routes are prefetched only up to the nearest loading.tsx boundary, which keeps prefetching costs bounded. You can opt out of prefetching on a per-link basis with prefetch={false} when the destination is unlikely to be visited or is expensive to load.

For programmatic navigation in Client Components, the useRouter hook from next/navigation exposes methods like router.push('/path') to navigate, router.replace('/path') to swap the current history entry, router.refresh() to re-fetch the current route's Server Components, and router.back() to move to the previous page. Two companion hooks are also worth knowing. The usePathname hook returns the current URL pathname as a string, which is handy for highlighting the active link in a navigation menu. The useSearchParams hook returns a read-only URLSearchParams object representing the query string, allowing you to read parameters like ?q=hello through searchParams.get('q'). Together with <Link>, they cover virtually every navigation pattern a typical application requires.

Configuration, Metadata, and Optimization

The main configuration file for a Next.js project is next.config.js, also available as .mjs or .ts. It centralizes many important settings, including allowed image domains, declarative redirects and rewrites, environment variable exposure, webpack customization, and experimental features. SEO is handled through metadata APIs: exporting a metadata object from layout.tsx or page.tsx sets static metadata such as the page title and description, while exporting an async generateMetadata function lets you fetch data dynamically and return metadata based on params or other inputs. Next.js automatically merges metadata from parent layouts with metadata defined deeper in the tree. For dynamic routes that should be statically generated at build time, the generateStaticParams function returns the list of parameter combinations to pre-render.

Images are optimized through the built-in <Image> component from next/image. It handles lazy loading by default, generates responsive sizes automatically, converts images to modern formats like WebP and AVIF, and reserves layout space using the width and height props, or the fill prop when dimensions are unknown, to prevent layout shift. The priority prop disables lazy loading for above-the-fold images that should load immediately.

Environment variables are managed through files like .env.local. Variables without a prefix are only available on the server, which keeps secrets safe. To expose a variable to the browser, prefix it with NEXT_PUBLIC_, after which it becomes accessible in client code as well. For runtime selection, Next.js supports both the default Node.js runtime and the Edge runtime, which is a lightweight JavaScript environment optimized for low latency at CDN edge locations. Middleware and Route Handlers can opt into the Edge runtime with export const runtime = 'edge', trading some Node.js API support for faster cold starts.

Finally, the framework offers multiple ways to redirect users. Inside Server Components and Server Actions you can call redirect('/path') or permanentRedirect('/path'). In next.config.js you can declare redirects declaratively, while Middleware is the right tool for conditional redirects based on the request. After a mutation, calling revalidatePath('/blog') purges the cached data for that route, and revalidateTag('posts') invalidates every cached fetch tagged with 'posts', ensuring the next render reflects the most recent state without waiting for the next timed revalidation.

Frequently asked questions

What is Next.js?

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.

What is a catch-all route in Next.js?

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'].

What are Server Actions in Next.js?

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.

How do you use the Next.js Image component?

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.

What are Route Groups in the App Router?

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.

What is the difference between the App Router and the Pages Router in Next.js?

The Pages Router uses pages/ with getServerSideProps/getStaticProps. The App Router uses app/ with React Server Components, layouts, and the file convention system. The App Router is the modern recommended approach.

What are rewrites in next.config.js?

Rewrites map an incoming URL to another URL server-side without changing the browser URL. They are useful for proxying API requests, masking URLs, and A/B testing. Defined under the rewrites key in config.

What is app/sitemap.ts used for?

app/sitemap.ts generates sitemap.xml for SEO. Export a function returning URL entries with url, lastModified, changeFrequency, and priority. Helps search engines discover and index pages.

What is the proxy.ts file in Next.js 15?

proxy.ts at the project root is an alternative name for middleware.ts in Next.js 15. It runs on the Edge runtime before requests are handled, enabling rewrites, redirects, and header manipulation.

What is the compiler option in next.config.js?

The compiler option allows configuring SWC compiler features. For example, compiler: { removeConsole: true } strips console.log from production builds, or styledComponents: true enables SWC-based styled-components compilation.

Drill this topic

100 flashcards on Nextjs Framework — free, no signup needed to start.

Study Nextjs Framework flashcards

LearnWiki pages are generated with AI assistance from LearnCoachAssist's reviewed study catalog and may contain errors — verify anything critical against your course materials.