Volume 2 Exercises: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Exercises: The Web Frontend

V2·24

Full-stack Frameworks

Exercises for Volume 2, chapter 24: where and when HTML is made (CSR, SSR, SSG, ISR and revalidation, streaming, partial prerendering, islands, Server Components, edge rendering) and choosing between them; Next.js, React Router framework mode, Astro, SvelteKit and Nuxt compared; and Next.js in production (App Router layouts and nested routes, loading and error UI, server and client components, server actions and route handlers, caching and revalidation, metadata, image and font optimisation, streaming and deployment runtimes). 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~14 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. The measured exercises use Next.js 16.4.6 with React 19.3.1, built with next build and served with next start on Node 22, probed with curl and Playwright. Every quoted output is real. Three are worth knowing before you start:

  • P1: a "static" page's new Date() showed the build time forever.
  • P5: a server action, called by a script outside the browser, ran with an id the script chose, while a request with a cross-site Origin header was rejected.
  • P6: the same photo was 10.7 KB as AVIF and 20.8 KB as JPEG at 640 px wide, and the first optimisation took 688 ms while the cached one took 3 ms.

The chapter's lab compared CSR, SSR, SSG and islands on one page: menu visible at 1,677, 428, 113 and 129 ms, and the Add button working at 1,724, 1,718, 1,395 and 132 ms. It also streamed a slow reviews section (34 ms vs 825 ms) and broke hydration. The exercises build on those.

Coverage map.

Chapter component Exercises
CSR, SSR, SSG: where and when HTML is made T1, P1
ISR and revalidation T2, P2
streaming, partial rendering and partial prerendering T3, P3
islands architecture T4, P7
Server Components as a rendering strategy T4
edge rendering T5
choosing a strategy T5, C1
Next.js, React Router, Astro, SvelteKit, Nuxt compared T6, P7
App Router: routing, layouts, nested routes, loading and error UI T7, P4
server/client components, server actions, route handlers T8, P5
caching and revalidation in Next.js T9, P2, P8
metadata T7, P9
image and font optimisation T9, P6
streaming and the deployment runtime T5, P3

Theory

T1. Where and when HTML is made

  1. Define CSR, SSR and SSG by where HTML is produced (browser, server per request, server at build) and when data is fetched. Using the lab's numbers, explain why SSR improved "menu visible" from 1,677 to 428 ms but not "Add button works" (1,718 ms).
  2. P1's build classified routes: / and /dishes as ○ Static, /kitchens/ammi and /kitchens/lakshmi as ● SSG (from generateStaticParams), /orders (reads cookies()) and /api/time as ƒ Dynamic, and /menu as static with revalidate 5s, expire 1y. What makes a Next.js route dynamic, and why did the home page show the build time on every request?
  3. What does each strategy cost in server compute, cache-friendliness, freshness and personalisation? Fill a table for CSR, SSR, SSG, ISR.

T2. ISR and revalidation

  1. P2 served /menu with revalidate = 5: requests within 5 s got the same HTML (x-nextjs-cache: HIT); the first request after expiry got the old page (STALE, 12 s old) and triggered regeneration; the next request got the new one. Explain ISR as stale-while-revalidate (chapter 19's T3) at the page level.
  2. Compare time-based revalidation with on-demand revalidation (revalidatePath, revalidateTag/updateTag after a kitchen edits its menu). Which fits menus, prices, reviews and kitchen opening hours?
  3. P1's /kitchens/ravi (not in generateStaticParams) was rendered on the first request and then cached (HIT with the same timestamp). Explain dynamicParams, and the trade-offs of generating thousands of kitchen pages at build time vs on demand.

T3. Streaming and partial prerendering

  1. The lab streamed a page: name and price at +34 ms, reviews at +825 ms. What determines what can be in the first chunk, and why can't a "not found" or a redirect discovered later change the HTTP status?
  2. P3 asks you to measure a waterfall: a page awaiting the menu (300 ms) and then related dishes (300 ms) takes ~600 ms; with Promise.all, ~300 ms; with each in its own Suspense boundary, the shell arrives immediately and sections stream independently. Explain how to find and fix data waterfalls in server components.
  3. What is partial prerendering (a static shell prerendered at build, with dynamic "holes" streamed per request; in Next.js 16, Cache Components with 'use cache' and <Suspense> around dynamic parts), and why is it the best of SSG and SSR for a kitchen page with a personalised "your usual order" box?

T4. Islands and Server Components

  1. The lab's islands version made the Add button work at 132 ms (with a 203-byte island script) versus 1,395 ms for SSG with full hydration. Explain the islands architecture (Astro): static HTML by default, interactive components hydrated individually with directives (client:load, client:idle, client:visible).
  2. How do React Server Components reach a similar result (non-interactive components ship no JS), and how do they differ from islands (one React tree, client components can be nested, server components re-render on navigation)?
  3. When is each the better fit: a content-heavy kitchen profile and blog (mostly static, a few widgets), an interactive ordering app, and the kitchen dashboard?

T5. Edge rendering, runtimes and choosing a strategy

  1. What is edge rendering (running server code in CDN locations: Cloudflare Workers, Vercel Edge/Functions, Netlify Edge, Deno Deploy), and why does it often not speed up pages that query a database in one region (each query crosses the distance)?
  2. Node.js runtime vs edge runtimes (Web-standard APIs, limited Node APIs, size and CPU limits, cold starts). Which TiffinBox routes could run at the edge (redirects, A/B bucketing, geolocation-based kitchen lists from a cache, auth checks in middleware/proxy), and which shouldn't?
  3. Write a decision table for choosing a rendering strategy per route: public vs private, how often data changes, personalisation, SEO needs, interactivity. Apply it to: home, kitchen page, search results, cart, checkout, order tracking, partner portal, blog.

T6. Comparing the frameworks

  1. Summarise Next.js, React Router framework mode (formerly Remix), Astro, SvelteKit and Nuxt: UI library, data loading model, rendering modes, mutations, deployment targets, and what each is best at.
  2. React Router's loaders/actions vs Next.js's Server Components/server actions: what are the mental-model differences (route-level data and form-based mutations vs component-level async data)? What does each do about waterfalls?
  3. What lock-in risks come with a full-stack framework (hosting-specific features, caching semantics, upgrade churn), and how do you reduce them?

T7. App Router structure

  1. Explain the App Router's file conventions: page.tsx, layout.tsx (persistent across navigations), template.tsx, loading.tsx (a Suspense boundary), error.tsx (an error boundary, client component), not-found.tsx, route.ts, route groups (marketing), dynamic segments [slug], catch-all [...path], parallel routes @modal and intercepting routes (.)dish/[id].
  2. Design the file tree for TiffinBox's public site: home, /kitchens/[slug] with a dish modal that opens over the kitchen page but has its own URL, /search, /cart, /checkout (requires login), /orders/[id], and a marketing route group with its own layout.
  3. P9: generateMetadata produced the title "Kitchen ammi · TiffinBox" from a template. What metadata should a kitchen page have (title, description, canonical, Open Graph image, structured data), and how does streaming metadata work for slow data?

T8. Server components, server actions and route handlers

  1. In P5, writing export const deleted: string[] = … in a 'use server' file failed the build: "A 'use server' file can only export async functions, found object." Why does Next.js enforce this?
  2. P5's real security finding: the delete action's form contained a hidden $ACTION_ID_40124d73… field, and a script replaying the browser's request without an Origin header got 200 and the action ran with id 1, chosen by the script; the same request with Origin: https://evil.example was rejected ("x-forwarded-host … does not match origin … Aborting the action"). Explain what Next.js protects (CSRF from other sites) and what it doesn't (direct calls with arbitrary arguments), and write the action properly.
  3. When do you use a route handler (route.ts) instead of a server action: webhooks (Razorpay payment callbacks), a public API for the mobile app, file downloads, SSE streams, OAuth callbacks? How are route handlers cached?

T9. Caching, images and fonts in Next.js

  1. List the caches involved in a Next.js app (request memoisation with cache(), the data cache / 'use cache', the full route cache, the client router cache, the CDN, the browser HTTP cache) and how each is invalidated. Why is "my change doesn't show up" the most common Next.js support question?
  2. P6: next/image served the 340 KB 1600×1067 JPEG as AVIF 10,725 B at 640 px and 35,500 B at 1080 px, WebP 15,750/54,074 B, JPEG 20,827/69,318 B, chosen by the Accept header (Vary: Accept); widths not in the configured sizes (w=333) and remote URLs not allow-listed got 400; the first AVIF encode at 1920 px took 688 ms and the cached one 3 ms. Explain what next/image does (responsive srcset, formats, lazy loading, priority/preload for LCP, sizing to avoid CLS) and the operational costs.
  3. What does next/font do (self-hosting Google fonts at build time, size-adjust fallback metrics to avoid layout shift, preloading, subsetting), and why does it matter for CLS and privacy (chapter 14's fonts)?

Programming exercises

P1. Classify routes and read the build output

Create a Next.js app with: a home page with no dynamic APIs that renders new Date(); /kitchens/[slug] with generateStaticParams for two slugs; /orders that reads cookies(); a GET route handler returning the time; and /menu with revalidate = 5. Build, read the route table, start the server, and record each page's timestamp across requests and its Cache-Control.

P2. Watch ISR serve stale pages

On the /menu route with revalidate = 5 (and a 200 ms render delay), request it several times within 5 s, wait 6 s, and request again three times, recording the timestamp and x-nextjs-cache header. Then add on-demand revalidation: a server action that edits the menu and calls revalidatePath('/menu'), and show the next request gets fresh HTML immediately.

P3. Find and fix a server waterfall

Build a kitchen page whose server component awaits getKitchen (100 ms), then getMenu (300 ms), then getRelated (300 ms). Measure TTFB and total time with curl (-w '%{time_starttransfer} %{time_total}'). Fix it three ways: Promise.all, separate Suspense boundaries with streaming, and preloading with cache(). Add Server-Timing headers or logs to see each fetch.

P4. Layouts, loading and error boundaries

Implement kitchens/[slug] with a persistent layout.tsx (kitchen header with a search box whose text must survive navigating between menu and reviews tabs), loading.tsx, error.tsx with a reset button, and not-found.tsx. Verify: the search text persists across child navigations; a thrown error in the reviews page shows the error UI without breaking the header; notFound() for an unknown slug returns status 404.

P5. Attack your own server action

Write a "delete dish" server action used by a form. Find its action id in the page HTML, capture the browser's request, and replay it from a script: without an Origin header, with a modified dish id, and with a cross-site Origin. Record what happens. Then add authentication, validation and per-object authorisation, and repeat.

P6. Measure image optimisation

Put a large photo in public/ and request /_next/image?url=/dish.jpg&w=640&q=75 and w=1080 with Accept headers for AVIF, WebP and JPEG-only clients. Record format, bytes, Cache-Control and X-Nextjs-Cache. Try a width that isn't configured and a remote URL that isn't allowed. Time the first and second request for a large AVIF. Then render it with <Image> and sizes, and check which candidate the browser picks on a 390 px phone and a 1440 px desktop.

P7. The same page in Astro with islands

Rebuild the kitchen page in Astro: static HTML for the header, menu and reviews, with three islands: an Add-to-cart button (client:load), a reviews carousel (client:visible) and a search box (client:idle), sharing cart state through a small store (nanostores). Compare JS bytes, time to interactive for Add, and Lighthouse scores against the Next.js version, and decide which suits the public kitchen pages.

P8. Test caching behaviour end to end

Write a Playwright or Node test suite that pins your caching assumptions: static pages are cacheable (s-maxage), personal pages are private, no-store, the menu page regenerates after revalidate, editing a menu through the action makes the next request fresh, route handlers return fresh data, /_next/static/* assets are immutable, and images vary by Accept. Run it against a production build in CI.

P9. Metadata, sitemaps and structured data

Add generateMetadata to the kitchen page with a title template, description, canonical URL and Open Graph image; generate sitemap.ts from the kitchen list and robots.ts; add Restaurant JSON-LD safely escaped. Validate with a structured-data testing tool and check the rendered <head>.

Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–24)

C1. Choose and implement the rendering strategy for each TiffinBox route

Apply T5's decision table to the whole customer site and implement it in Next.js: SSG/ISR with on-demand revalidation for kitchen pages (with a dynamic "your usual" hole via partial prerendering), dynamic SSR for search, client state for the cart, a dynamic checkout behind a server-side session check, SSE-driven order tracking, metadata and sitemaps, image and font optimisation, CDN caching headers consistent with chapter 19's plan, and tests pinning caching (P8). Measure Core Web Vitals per route before and after on a throttled phone.

Combines: HTTP caching and CDNs (ch 19), Core Web Vitals (ch 18), accessibility (ch 20), React and Server Components (ch 22), UI architecture (ch 21) and this chapter.

C2. Port one route between frameworks

Port the kitchen page from Next.js to React Router framework mode (loader, action, <Form>, streaming with deferred data, headers export for caching), and to SvelteKit or Astro. Compare: lines of code, JS shipped, TTFB/LCP, how caching is expressed, how mutations and revalidation work, and how hard it was to deploy each to the same host (a Node container). Recommend one for a new public site.

Combines: React (ch 22), UI architecture (ch 21), HTTP caching (ch 19) and this chapter's framework comparison.

C3. Run the Next.js app in production

Deploy the app yourself (Docker image with output: 'standalone') behind a CDN: configure the shared cache handler for ISR across multiple instances (Redis or the filesystem on a shared volume), the image optimisation cache, health checks, graceful shutdown, environment variables and secrets, Server-Timing and OpenTelemetry tracing, log correlation by request id, and a rollout strategy (blue/green). Load-test kitchen pages and checkout, and find the first bottleneck.

Combines: Volume 1's operations, observability and load testing (ch 10, 11), HTTP and CDN behaviour (ch 19), performance (ch 18) and this chapter.

What the chapter leaves out

Authentication in full-stack frameworks

Full-stack apps need sessions or tokens handled on the server: libraries like Auth.js (NextAuth), Better Auth, Clerk, Lucia-style custom sessions, or the platform's identity service, with OAuth/OIDC providers (Google, phone OTP for Indian users). Key practices: check the session in every server action, route handler and data access function (not only in middleware/proxy, which can be bypassed by misconfiguration; a 2025 Next.js vulnerability let crafted headers skip middleware), HttpOnly SameSite=Lax Secure cookies, CSRF protections for non-action endpoints, and a data access layer that enforces authorisation. Volume 3 covers identity in depth.

Backend-for-frontend and where business logic lives

A full-stack framework can be a backend-for-frontend (BFF): it aggregates APIs, holds tokens server-side and shapes data for the UI. That doesn't make it the right home for core business logic (pricing, order state machines, payouts), which usually belongs in backend services with their own APIs, tests and data ownership (Volume 3), especially when mobile apps and partners use the same logic. Keep framework code thin: route → validate → call a service → render.

Deployment platforms and serverless constraints

Platforms (Vercel, Netlify, Cloudflare, AWS Amplify, Render, Fly.io, self-hosted containers) differ in how they run frameworks: serverless functions (cold starts, execution time limits, no long-lived connections, so SSE and WebSockets need special handling), edge functions (T5), ISR and image cache storage, streaming support, and pricing models (per invocation, bandwidth, image transformations). OpenNext adapts Next.js for AWS and Cloudflare. Chapter 31 covers frontend deployment.

Content management and data sources

Content-heavy sites pair frameworks with a headless CMS (Sanity, Contentful, Strapi, Payload, Directus) or Markdown/MDX in the repo, using webhooks for on-demand revalidation, draft/preview modes (draftMode()), and image pipelines. Astro's content collections and Next.js MDX support typed content. For TiffinBox, kitchen stories and the blog could live in a CMS while menus stay in the product database.

Testing and observability for server-rendered apps

Server components and actions need integration tests against a running build (Playwright, P8), unit tests for data functions, and contract tests for APIs. Observability needs server-side tracing (OpenTelemetry via instrumentation.ts), error tracking with source maps for both server and client bundles, RUM for Core Web Vitals per route and rendering mode, and logs that include cache status (x-nextjs-cache) so caching bugs show up in dashboards. Chapter 32 covers frontend observability.

Senior exercises

S1. Decide CSR, SSR or static for TiffinBox's next phase

The current customer app is a client-rendered SPA; marketing wants better SEO and LCP, engineering worries about server costs and complexity. Write a decision record covering the options (stay CSR and optimise, move public pages to SSG/ISR, full SSR with RSC), costs (servers, CDN, team skills), risks (caching bugs, security of server actions, vendor lock-in), a phased plan and success metrics.

S2. Review a Next.js pull request

A PR adds an admin page: app/admin/page.tsx is a server component reading cookies() to show the admin name; it imports db and passes the full user row (including passwordHash and phone) to a client component; a 'use server' file exports deleteKitchen(id: string) with no checks; export const revalidate = 3600 on the admin page; <img src={k.photo}> for 200 kitchen photos; and middleware checks request.cookies.has('admin') as the only admin protection. Write the review.

S3. Design caching and invalidation for kitchen pages

Design the end-to-end caching for kitchen pages: data cache tags, ISR/partial prerendering, CDN headers, browser caching, the client router cache, and the invalidation flow when a kitchen edits its menu, changes its hours, gets a new review, or is suspended for a food-safety issue (must disappear within 60 s). Include monitoring.

S4. Plan a migration from Pages Router to App Router

A large Next.js app on the Pages Router (getServerSideProps, getStaticProps with revalidate, API routes, _app with global providers, client-side data fetching with SWR, next/head) needs to move to the App Router. Plan the incremental migration, the mapping of each concept, risks (caching semantics, client/server boundaries, third-party libraries), testing and how to measure success.

S5. Teach rendering strategies with one page and five numbers

Prepare a 15-minute talk using the lab's four strategies (CSR, SSR, SSG, islands) and this chapter's measurements to explain to product managers and engineers why different TiffinBox pages are rendered differently. Use at most five numbers on the slides and end with five rules.