🌍 NextJS · subject
NextJS Advanced Features Syllabus
The Advanced Features syllabus for NextJS in full: 3 chapters and 10 topics, every one listed below, plus 50 Advanced Features flashcards with answers.
Advanced Features syllabus: all 3 chapters
Expand any chapter to see its topics and sub-topics.
-
Data Fetching
4 topics- getStaticProps
- getServerSideProps
- getStaticPaths
- Client-side Data Fetching
-
API Routes
3 topics- Creating API Endpoints
- Middleware
- Handling Requests and Responses
-
Dynamic Routing
3 topics- Dynamic Routes with getStaticPaths
- Catch-All Routes
- Optional Catch-All Routes
NextJS Advanced Features flashcards — 50 questions with answers
What is getStaticProps in Next.js and when does it run?
getStaticProps is a function you export from a page to fetch data at build time (Static Site Generation). It runs only on the server at build time, never on the client, and its returned props are used to pre-render the page into static HTML.
What must getStaticProps return, and in what shape?
It must return an object with a props key (a serializable object passed to the page component), e.g. return { props: { data } }. It may also optionally include revalidate, notFound, or redirect keys.
How does Incremental Static Regeneration (ISR) work with getStaticProps?
You add a revalidate key (in seconds) to the returned object, e.g. return { props, revalidate: 60 }. Next.js re-generates the page in the background at most once every 60 seconds when a request comes in, keeping static content fresh without a full rebuild.
Can getStaticProps access the incoming request (req/res) or query parameters?
No. Because it runs at build time, it has no access to the incoming request, response, or query string. It receives a context object with params, preview, previewData, locale, etc., but not req/res or query.
What is getServerSideProps and when does it run?
getServerSideProps is a function exported from a page that fetches data on every request (Server-Side Rendering). It runs on the server for each request at request time, and the page is rendered fresh with the returned props.
What context properties are available in getServerSideProps that are NOT in getStaticProps?
getServerSideProps receives req and res (the HTTP request/response objects) and query (the query string parameters), in addition to params, resolvedUrl, and locale. These enable request-specific data like cookies, headers, and authentication.
Compare getStaticProps vs getServerSideProps in terms of when they run and caching.
getStaticProps runs at build time, producing cacheable static HTML (optionally revalidated via ISR). getServerSideProps runs on every request at request time, producing fresh but non-CDN-cacheable HTML by default. Static is faster/cheaper; server-side is for per-request/personalized data.
What is getStaticPaths and why is it required for dynamic SSG pages?
getStaticPaths is exported from a dynamic route page (e.g. [id].js) that uses getStaticProps. It tells Next.js which dynamic path values to pre-render at build time, since Next.js cannot otherwise know which paths exist for a dynamic segment.
What two keys must getStaticPaths return?
It must return an object with paths (an array of path objects, each like { params: { id: '1' } }) and fallback (a boolean, 'blocking', or false).
What does fallback: false mean in getStaticPaths?
Only the paths returned by getStaticPaths are pre-rendered. Any path not in that list returns a 404 page. Use it when you know all possible paths at build time.
What does fallback: true mean in getStaticPaths?
Paths not generated at build time are NOT 404. On first request Next.js serves a fallback (loading) version of the page, runs getStaticProps in the background, then serves and caches the fully rendered page for subsequent requests. The page must handle router.isFallback.
What does fallback: 'blocking' mean in getStaticPaths?
Paths not pre-rendered are server-rendered on first request (like SSR) with no loading/fallback state; the user waits for the HTML, which is then cached for future requests. No router.isFallback handling is needed.
How do you detect and handle a fallback page while it is being generated (fallback: true)?
Use const router = useRouter(); if (router.isFallback) { return <div>Loading...</div>; }. This renders a placeholder until getStaticProps completes and provides the real props.
What is the params shape inside a paths entry in getStaticPaths?
Each entry is { params: { <segmentName>: <stringValue> } }, e.g. for pages/posts/[id].js you return { params: { id: '1' } }. Param values must be strings (matching the file name of the dynamic segment).
What is client-side data fetching and when is it preferred over getStaticProps/getServerSideProps?
Client-side data fetching loads data in the browser after the page renders (e.g. in useEffect or with SWR/React Query). It is preferred for user-specific, frequently-updating, or non-SEO-critical data such as dashboards, where the data need not be pre-rendered.
What is SWR and what does its name stand for?
SWR is a React data-fetching hook library from Vercel. The name comes from stale-while-revalidate: it returns cached (stale) data first, then revalidates in the background, then updates with fresh data.
Show a basic SWR usage pattern for client-side fetching.
const fetcher = url => fetch(url).then(r => r.json()); const { data, error, isLoading } = useSWR('/api/user', fetcher); Then render loading, error, or data states accordingly.
What are the trade-offs of client-side fetching regarding SEO and initial load?
Client-side fetching sends an initial page without the data, so search engines may not index the data and users see a loading state first (worse perceived performance / SEO). Pre-rendering (SSG/SSR) includes data in the HTML for better SEO and first paint.
How do you create an API endpoint in the Next.js Pages Router?
Create a file inside the pages/api directory that exports a default handler function, e.g. pages/api/hello.js exporting function handler(req, res) { res.status(200).json({ name: 'John' }) }. It becomes accessible at /api/hello.
What is the signature of a Next.js API route handler?
export default function handler(req, res) { ... }, where req is an extended http.IncomingMessage and res is an extended http.ServerResponse (NextApiRequest and NextApiResponse in TypeScript).
Show the other 30 Advanced Features flashcards
Do Next.js API routes run on the client bundle?
No. API routes are server-side only; their code is never included in the client-side JavaScript bundle. This makes them safe for secrets, database access, and sensitive logic.
What helper properties does the req object expose in a Next.js API route?
req.query (query string params and dynamic route params), req.body (parsed request body), req.cookies (an object of cookies), and req.method (HTTP method).
What helper methods does the res object expose in a Next.js API route?
res.status(code) sets the status code; res.json(body) sends a JSON response; res.send(body) sends a response; res.redirect([status,] path) redirects; and res.setHeader(name, value) sets headers.
How do you handle different HTTP methods in a single API route?
Inspect req.method and branch, e.g. if (req.method === 'POST') { ... } else if (req.method === 'GET') { ... } else { res.setHeader('Allow', ['GET','POST']); res.status(405).end(`Method ${req.method} Not Allowed`); }.
What is Middleware in Next.js and where does it run in the request lifecycle?
Middleware is code that runs BEFORE a request is completed, allowing you to modify the response by rewriting, redirecting, adding headers, or setting cookies. It runs on the Edge Runtime before the cached content and routes are matched.
What file defines Middleware in a Next.js project and what does it export?
A single middleware.js (or middleware.ts) file at the project root (or src/). It exports a function named middleware(request) and optionally a config object with a matcher.
How do you limit which paths Middleware runs on?
Export a config object with a matcher, e.g. export const config = { matcher: '/about/:path*' } or an array of paths. Only matching requests invoke the middleware.
What are the common actions Middleware can perform on a request?
Rewrite (NextResponse.rewrite), redirect (NextResponse.redirect), continue with modifications (NextResponse.next), set request/response headers, and read/set cookies. It is commonly used for auth, A/B testing, i18n, and geolocation.
Why must Next.js Middleware avoid heavy computation or Node-specific APIs?
Middleware runs on the Edge Runtime, a lightweight environment that does not support all Node.js APIs and is optimized for low latency. Heavy or Node-only operations can fail or slow every request, so keep middleware fast and lean.
How do you return a redirect from Middleware?
Import NextResponse and return NextResponse.redirect(new URL('/login', request.url)). This sends the client to a new URL before the request reaches the destination route.
What is the difference between NextResponse.rewrite and NextResponse.redirect in Middleware?
redirect changes the URL the browser navigates to (client sees the new URL, extra round trip). rewrite serves content from a different path while keeping the original URL in the address bar (proxy-like, transparent to the user).
In an API route, how do you read the request body and query parameters?
Use req.body for the parsed body (JSON/form data auto-parsed by the built-in body parser) and req.query for query string plus dynamic route parameters. Both are objects.
How do you send a JSON response with a specific status code in a Next.js API route?
Chain the methods: res.status(201).json({ message: 'Created' }). res.status sets the HTTP status and returns res, so json can be chained to serialize and send the body.
How do you disable or configure the built-in body parser in a Next.js API route?
Export a config object from the route, e.g. export const config = { api: { bodyParser: false } } to handle raw bodies (like webhooks/file uploads), or set bodyParser: { sizeLimit: '1mb' } to change the limit.
What is a dynamic route in Next.js and how is it created?
A dynamic route matches variable path segments using square brackets in the filename, e.g. pages/posts/[id].js matches /posts/1, /posts/2, etc. The bracketed name becomes a param available in query and getStaticPaths/getServerSideProps params.
How do dynamic routes with getStaticPaths work together for pre-rendering?
For pages/posts/[id].js you export getStaticPaths returning the list of ids to pre-render (paths) and a fallback strategy, and getStaticProps which receives context.params.id to fetch that post's data at build time.
How do you access the dynamic route parameter inside getStaticProps?
Read it from the context params object: export async function getStaticProps({ params }) { const id = params.id; ... }. The param name matches the bracketed segment in the filename.
What is a catch-all route in Next.js and how is it written?
A catch-all route uses three dots inside brackets, e.g. pages/posts/[...slug].js. It matches any number of path segments after /posts/, such as /posts/a, /posts/a/b, /posts/a/b/c.
What form does the param take for a catch-all route [...slug]?
The param becomes an array of the matched segments. For /posts/a/b/c, params.slug is ['a', 'b', 'c']. Even a single segment /posts/a yields params.slug = ['a'].
Does a catch-all route [...slug] match the base path /posts (with no segments)?
No. A standard catch-all route requires at least one segment, so /posts (the parent path) is NOT matched and returns 404. Use an optional catch-all route to match the base path too.
What is an optional catch-all route and how is it written?
An optional catch-all route uses double brackets with three dots, e.g. pages/posts/[[...slug]].js. It behaves like a catch-all but ALSO matches the base route /posts with no parameters.
What is params.slug for an optional catch-all route [[...slug]] when the base path /posts is requested?
When no segments are present (i.e. /posts), params is empty and params.slug is undefined. With segments it is an array like ['a', 'b'], identical to a normal catch-all.
Summarize the difference between [id], [...slug], and [[...slug]] routes.
[id] matches exactly one segment (param is a string). [...slug] matches one or more segments (param is an array), but not the base path. [[...slug]] matches zero or more segments (param array or undefined), including the base path.
How do you build getStaticPaths paths for a catch-all route [...slug]?
Each params value must be an array of strings, e.g. paths: [ { params: { slug: ['a', 'b'] } }, { params: { slug: ['a'] } } ]. The array elements correspond to the path segments.
Can you use getServerSideProps with dynamic and catch-all routes?
Yes. getServerSideProps receives context.params where the dynamic segment is a string (for [id]) or an array (for [...slug] / [[...slug]]). getStaticPaths is not used with getServerSideProps since paths are resolved per request.
What is the return option 'notFound' used for in getStaticProps/getServerSideProps?
Returning { notFound: true } makes the page return a 404 status and render the 404 page, even if the route matched. It is used when requested data does not exist.
What is the 'redirect' return option in getStaticProps/getServerSideProps?
Returning { redirect: { destination: '/login', permanent: false } } sends the user to another route. permanent: true uses a 308 (permanent) redirect; false uses a 307 (temporary) redirect for SEO signaling.
For which routing/data method is the client informed of a loading state, and how is it checked?
With getStaticPaths fallback: true, a not-yet-generated page shows a loading fallback. It is checked via useRouter().isFallback, which is true while getStaticProps runs in the background and false once real props arrive.
Why can't you import getStaticProps or getServerSideProps data-fetching code that uses server-only modules into client components?
getStaticProps and getServerSideProps run only on the server and are stripped from the client bundle by Next.js. You can safely use server-only modules (fs, database drivers, secrets) inside them, but that code must not be imported into client-rendered components.
Which advanced feature would you choose for a blog with thousands of posts that update occasionally: SSG with fallback, pure SSR, or client-side fetching, and why?
SSG with getStaticPaths (fallback: true or 'blocking') plus ISR (revalidate). It pre-renders popular posts at build time, generates others on demand, and periodically revalidates content, giving fast static delivery with fresh data and good SEO without rebuilding for every post.
NextJS Advanced Features FAQ
What is in the NextJS Advanced Features syllabus?
NextJS Advanced Features is split into 3 chapters: Data Fetching, API Routes and Dynamic Routing. Together they contain 10 topics.
How many chapters are in NextJS Advanced Features?
3 chapters, containing 10 topics. The largest chapter is Data Fetching, with 4 topics.
Are there flashcards for NextJS Advanced Features?
Yes — a 50-card Advanced Features deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.