Skip to article content
FrontendXLesson 19 / 20

Testing and Debugging Next.js Applications

A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.

intermediate · about 50 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Choose the right test layer for server components, route handlers, server actions and client interactions.
  • Test a route handler by calling its exported function directly with a constructed Request.
  • Diagnose hydration mismatches and debug effectively under the Next.js 16 toolchain.

Overview

#

Test the layers you actually ship

A Next.js app has four testable layers, and each has a natural tool. Pure logic (parsing, validation, formatting) should be extracted into functions and unit tested with Vitest; the extraction is the hard part, the test is easy. Route handlers are plain async functions that take a Request and return a Response, so you can call them directly without starting a server:

snippet.ts
// app/api/items/route.ts
export async function GET(request: Request) {
  const id = new URL(request.url).searchParams.get("id");
  if (!id) return Response.json({ error: "id required" }, { status: 400 });
  return Response.json({ id });
}

// route.test.ts
import { GET } from "./route";

const res = await GET(new Request("http://localhost/api/items?id=7"));

Server actions are the same shape: async functions you can import and call, with cookies() and headers() mocked at the module boundary. React Testing Library covers component behavior for client components; server components are async and render on the server, so the pragmatic pattern is to keep them thin and push their logic into tested functions. Playwright e2e tests run against a real build and catch the bug class unit tests cannot see: hydration failures, routing regressions and broken streaming.

Lint and the Next.js 16 toolchain

Next.js 16 removed the next lint command; run the ESLint CLI directly (npx eslint .) with your own flat config. Turbopack is the default bundler for next dev and next build in Next.js 16, so error messages, source maps and incremental rebuild behavior come from Turbopack; when a build issue appears, read the Turbopack trace before assuming a code bug.

Debugging hydration mismatches

The server renders HTML once; the browser's first client render must match it exactly or React reports a hydration mismatch. The usual suspects are nondeterminism during render: Date.now(), Math.random(), reading window or localStorage in the render path, or locale-dependent formatting that differs between server and client. Fix by computing such values in an effect after mount, or by rendering a stable placeholder on the server. The dev overlay surfaces the mismatch with a diff; read it before guessing.

Debugging data and caching

When data looks stale or missing, work down the caching layers in order: is the fetch itself cached, is the route statically prerendered, is a revalidation tag being called, and is the CDN in front of everything serving an old asset? Adding a temporary timestamp log at the data source tells you instantly whether the data never changed or changed but was served from a cache.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    A server component renders <span>{new Date().getFullYear()}</span> and the component is also a client component (it has 'use client'). A user loads the page at 23:59:59.9 UTC on December 31 and hydration completes after midnight. What happens and why?

    Choose the best answer
  2. Exercise 2Explain

    Explain which bug classes a Playwright e2e suite catches that a Vitest unit suite cannot, and give one concrete App Router example of each.

    Reveal the reference answer
    reference.text
    Unit tests verify logic in isolation with a fake environment, so they cannot observe integration between the framework, the bundler and the browser. Playwright runs a real build in a real browser and catches: hydration mismatches (server HTML disagreeing with the first client render), routing regressions (a broken link or a layout that fails to wrap a segment), streaming failures (a Suspense fallback that never resolves) and asset problems (a font or image that 404s only in the built output). A concrete pair: a Vitest test passes on a pure formatCurrency function while the page using it crashes in e2e because the component reads window during render and breaks hydration.

    Authored expected output: A statement about integration versus isolation plus at least one App Router-specific e2e-only bug class such as hydration or streaming.

    The layers are complementary: unit tests pin logic, e2e tests pin the composed system.

  3. Exercise 3Implement

    Write a Vitest test for this route handler without starting a server: GET returns 400 with an error body when the id query parameter is missing and 200 with the parsed numeric id when present. // app/api/items/route.ts export async function GET(request: Request) { const raw = new URL(request.url).searchParams.get('id'); if (!raw) return Response.json({ error: 'id required' }, { status: 400 }); const id = Number(raw); if (!Number.isInteger(id)) return Response.json({ error: 'id must be an integer' }, { status: 400 }); return Response.json({ id }); }

    starter.ts
    import { describe, expect, it } from 'vitest';
    import { GET } from './route';
    
    // TODO: three cases: missing id, non-integer id, valid id

    Reveal the reference answer
    reference.ts
    import { describe, expect, it } from 'vitest';
    import { GET } from './route';
    
    function get(query: string) {
      return GET(new Request(`http://localhost/api/items${query}`));
    }
    
    describe('GET /api/items', () => {
      it('returns 400 when id is missing', async () => {
        const res = await get('');
        expect(res.status).toBe(400);
        expect(await res.json()).toEqual({ error: 'id required' });
      });
    
      it('returns 400 when id is not an integer', async () => {
        const res = await get('?id=abc');
        expect(res.status).toBe(400);
        expect(await res.json()).toEqual({ error: 'id must be an integer' });
      });
    
      it('returns 200 with the parsed id', async () => {
        const res = await get('?id=7');
        expect(res.status).toBe(200);
        expect(await res.json()).toEqual({ id: 7 });
      });
    });

    Authored expected output: All three tests pass: two 400 responses with their error bodies and one 200 with { id: 7 }.

    The handler is a pure-ish function of its Request, so constructing Request objects exercises the full status and JSON contract in milliseconds.

  4. Exercise 4Debug

    This client component logs a hydration mismatch in production but not in local tests. Find the cause and fix it. "use client"; export function Greeting() { const hour = new Date().getHours(); const label = hour < 12 ? 'Good morning' : 'Good afternoon'; return <p>{label}, welcome back</p>; }

    starter.tsx
    "use client";
    export function Greeting() {
      const hour = new Date().getHours();
      const label = hour < 12 ? 'Good morning' : 'Good afternoon';
      return <p>{label}, welcome back</p>;
    }

    Reveal the reference answer
    reference.tsx
    The component reads the clock during render, so the server's HTML and the client's first render can disagree whenever they execute in different hours (or time zones, since the server runs in its own zone and tests run at a fixed moment). Fix by rendering a stable value first and reading the clock after mount:
    
    "use client";
    import { useEffect, useState } from 'react';
    
    export function Greeting() {
      const [label, setLabel] = useState<string | null>(null);
      useEffect(() => {
        const hour = new Date().getHours();
        setLabel(hour < 12 ? 'Good morning' : 'Good afternoon');
      }, []);
      return <p>{label ?? 'Welcome back'}</p>;
    }

    Authored expected output: The server and the first client render both output the stable fallback; the time-aware label appears after mount without a mismatch.

    Any render-path value that can differ between server and client must be deferred to an effect or supplied deterministically from the server.

  5. Exercise 5Test

    Extract the validation from a server action into a pure function validateSignup(input: { email: string, password: string }): { ok: true } | { ok: false, field: 'email' | 'password', reason: string }, with rules: email must contain '@', password must be at least 8 characters. Write assertions for a valid input, a bad email, and a short password, checking which field fails first when both are invalid.

    starter.ts
    export function validateSignup(input: { email: string, password: string }) {
      // TODO
    }
    
    // assertions
    // expect(validateSignup({ email: 'a@b.co', password: 'longenough' })).toEqual({ ok: true })
    // expect(validateSignup({ email: 'nope', password: 'longenough' })).toEqual({ ok: false, field: 'email', reason: '...' })
    // expect(validateSignup({ email: 'nope', password: 'short' })).toEqual({ ok: false, field: 'email', reason: '...' })

    Reveal the reference answer
    reference.ts
    export function validateSignup(input: { email: string, password: string }) {
      if (!input.email.includes('@')) {
        return { ok: false as const, field: 'email' as const, reason: 'Email must contain @' };
      }
      if (input.password.length < 8) {
        return { ok: false as const, field: 'password' as const, reason: 'Password must be at least 8 characters' };
      }
      return { ok: true as const };
    }
    
    // Email is checked first, so an input failing both rules reports the email field.

    Authored expected output: All three assertions pass, with the third proving email errors take precedence.

    Extracting validation from the action makes the ordering of checks explicit and testable without touching cookies or the database.

  6. Exercise 6Interview

    Interview question: design the testing strategy for a Next.js App Router product with server components, server actions, route handlers and rich client interactions. What do you test at each layer, and where do you deliberately not test?

    Reveal the reference answer
    reference.text
    Unit layer (Vitest): all extracted pure logic, route handlers called directly with constructed Requests, and server actions with mocked cookies and headers; this is fast and pins behavior contracts. Component layer (React Testing Library): client component interactions, state transitions and accessibility of interactive widgets. E2E layer (Playwright against a built app): the critical user journeys, hydration-sensitive pages, streaming and loading behavior, and routing. Deliberately not tested: framework internals (do not test that Suspense suspends), trivial markup snapshots that break on every redesign, and server component rendering in isolation when the logic is already extracted. The strategy buys confidence where bugs actually live: boundaries between server and client, and the composed system.

    Authored expected output: A layered strategy with concrete App Router targets per layer and an explicit statement of what is intentionally left untested.

    Strong answers name the server/client boundary as the highest-risk area and match each layer to the bug class it can actually observe.

Common misconceptions

#
  • Route handlers need a running dev server to test. They are plain Request-in, Response-out functions you can invoke directly in a unit test.
  • next lint is still available in Next.js 16. The command was removed; run the ESLint CLI directly with your own configuration.

Follow-up practice

#
  • nextjs-deployment-capstone
  • nextjs-error-handling

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.