Route Handlers, streams, and the BFF
Design explicit HTTP contracts, bounded uploads and cancellable event streams at the server boundary.
What you will be able to do
- Design predictable request, status and response schemas.
- Keep credentials and upstream adaptation in a server-only BFF.
- Frame and clean up SSE streams correctly.
- Explain upload limits, validation and durable processing.
Before this lesson
Start with a caller and a protocol
A Route Handler exposes an HTTP endpoint. Unlike a Server Action, it is naturally consumable by tools, mobile clients, webhooks and browser fetch. Begin with its method, path, accepted content type, authentication requirement, input bounds, success schema and failure schema. A GET should read data without relying on a hidden state-changing side effect.
Use an endpoint such as /api/catalog?q=pen&page=2 to practice normalization. A malformed page value should not reach the database as an unbounded offset. Decide whether invalid input is rejected or normalized, document that decision and keep the client consistent. Status codes distinguish invalid input, missing identity, forbidden access, missing records and server failure; a JSON error object alone is not the complete contract.
Adapt upstream services without leaking authority
A backend for frontend can combine upstream data and return only the fields the interface needs. Keep service credentials in server-only modules. Validate an upstream response at runtime because TypeScript cannot ensure another service obeys its contract. Apply timeouts and bounded retries to safe operations, and translate internal failure details into a stable client error.
A Server Component generally can call its data-access function directly instead of requesting its own Route Handler over HTTP. The extra self-request adds a network boundary and can fail during prerendering when no application server is listening. Share the domain function between the handler and the Server Component; retain the handler when an actual external or browser caller needs HTTP.
SSE is a framed stream with a lifecycle
Server-sent events use text/event-stream framing: fields such as id, event and data end with a blank line. Network chunks are arbitrary byte boundaries, so a client parser cannot assume one chunk equals one JSON record. EventSource provides the protocol for browser GET streams; a fetch stream is useful when you need a custom request but requires your own framing and retry behavior.
The complete short handler below sends one event and closes. For a continuing stream, also wire request abort and stream cancellation to clear timers, unsubscribe from brokers and stop upstream work. Reconnection can replay events, so assign stable IDs and make the receiving reducer tolerate duplicates. Never let a disconnected tab leave an unbounded background producer running.
Server execution
export async function GET() {
const encoder = new TextEncoder();
const body = new ReadableStream<Uint8Array>({
start(controller) {
const data = JSON.stringify({ status: "ready" });
controller.enqueue(encoder.encode(`id: 1
event: update
data: ${data}
`));
controller.close();
},
});
return new Response(body, {
headers: {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
},
});
}Bound work before reading a large body
An upload task is more than accepting FormData. Define maximum bytes, supported formats, filename handling, authorization and where durable bytes live. A browser-supplied MIME type or filename is not proof of content. For large uploads, a signed object-storage upload flow can avoid buffering the entire file through the application, but the signing endpoint still needs permission and size/type policy.
After upload, persist metadata only when the object is available under the expected ownership. Processing such as thumbnails or document extraction may belong in a durable job queue. A response followed by arbitrary fire-and-forget work is fragile on short-lived compute. Discuss duplicate callbacks, cleanup of abandoned objects and how the UI learns processing failed.
Verify the actual server behavior
Route Handlers use Web Request and Response APIs, but their available libraries depend on the runtime and deployment adapter. Do not move a native Node dependency into an Edge runtime without checking support. Under Cache Components, deterministic GET output may be prerendered; request-specific or uncached work changes that behavior. Cache expensive helpers explicitly instead of placing a cache directive directly in the handler.
For an interview, inspect the network response rather than proving only that a component rendered a list. Confirm status, content type, pagination bounds, authentication and cancellation. If streaming works locally but arrives all at once behind a proxy, investigate buffering and platform time limits. A correct handler cannot force infrastructure to preserve streaming semantics it does not support.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGEA successful JSON body makes the HTTP status irrelevant.
- A more accurate model
Status and content type are part of the contract used by clients, retries and monitoring.
- How to check it
Inspect /api/catalog with malformed input and compare body with status.
- CLAIM TO CHALLENGEA disconnected stream can leave its producer running indefinitely.
- A more accurate model
Release per-subscriber timers, upstream work and subscriptions through abort/cancel cleanup.
- How to check it
The HTML SSE standard and the route lifecycle exercise.
Mistakes to catch in your own code
- Returning 200 for every failure.
- Treating each network chunk as a complete event.
- Fetching the application's own API from every Server Component.
- Accepting unlimited uploads based only on a claimed MIME type.
Write it by hand
JavaScript logic playground
Normalize a bounded pagination request
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Input is {page,pageSize,total}; page and pageSize are strings, total is a nonnegative integer.
- Accept only positive decimal integer strings. Default invalid page to 1 and invalid pageSize to 10. Cap pageSize at 50.
- Clamp page to the last available page; an empty result still uses page 1. Return {page,pageSize,offset,totalPages}.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 4 test cases
- Bound a valid page
Input
{ "page": "2", "pageSize": "20", "total": 45 }Expected
{ "page": 2, "pageSize": 20, "offset": 20, "totalPages": 3 } - Normalize invalid strings
Input
{ "page": "-1", "pageSize": "3oops", "total": 0 }Expected
{ "page": 1, "pageSize": 10, "offset": 0, "totalPages": 1 } - Cap size and page
Input
{ "page": "99", "pageSize": "500", "total": 70 }Expected
{ "page": 2, "pageSize": 50, "offset": 50, "totalPages": 2 } - Do not accept partial numeric text
Input
{ "page": "2.5", "pageSize": "10", "total": 35 }Expected
{ "page": 1, "pageSize": 10, "offset": 0, "totalPages": 4 }
Reveal the worked solution and reasoning
function solve(input) {
const positive = (value, fallback) => {
if (typeof value !== "string" || !/^[1-9]\d*$/.test(value)) return fallback;
const parsed = Number(value);
return Number.isSafeInteger(parsed) ? parsed : fallback;
};
const pageSize = Math.min(50, positive(input.pageSize, 10));
const totalPages = Math.max(1, Math.ceil(input.total / pageSize));
const page = Math.min(totalPages, positive(input.page, 1));
return { page, pageSize, offset: (page - 1) * pageSize, totalPages };
}Validate the entire string rather than accepting a numeric prefix with parseInt.
Bounds protect both the interface and downstream query cost.
This normalization policy is deliberately explicit; rejecting invalid input with 400 is another valid API contract.
Verify it in a real Next.js application
Next.js application lab
Inspect JSON, streaming and cancellation contracts
Open the local application route /stream after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Call /api/catalog?q=desk&sort=price&page=99 in the running lab. Compare queryCatalog in lib/domain.ts with the returned normalized page, fixed four-item page size and no-store HTTP header. Invalid page values are normalized rather than returned as 400 errors.
- Open /stream and use Start stream, Stop stream and Start stream again. Inspect components/stream-client.tsx and app/api/stream/route.ts: the shipped implementation already frames SSE events, clears its timer, handles request abort and stream cancellation, and ignores events from an old client generation.
- Use curl -N against /api/stream to observe event framing. Supply a topic longer than 100 characters and verify the handler returns its explicit 400 response.
- Implementation extension: instrument subscriber setup and cleanup, then repeatedly disconnect clients to verify that producer resources are released. A stopped browser view alone is not evidence that the server timer was cleaned up.
- Implementation extension: add an authenticated upload Route Handler with bounded size, validated content, safe object naming and cancellation. Upload handling is not included in the shipped project.
Check the behavior
- The existing catalogue response contains no more than four products per page; callers cannot request an arbitrary page size.
- The SSE endpoint emits blank-line-delimited events and a done event. Event boundaries do not depend on transport chunk boundaries.
- Stopping or restarting the browser stream prevents an older connection from appending output to the new run.
- The cleanup instrumentation and upload acceptance checks are extensions to implement and execute separately.
Review the application reasoning
The source explorer and JSON project manifest are source delivery surfaces. These HTTP observations require the separate running Next.js server. The existing SSE text is deterministic training data, not an AI service or a catalogue change feed.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01What is the difference between a Route Handler and a Server Action?
A Route Handler defines an HTTP contract using Request and Response. A Server Action integrates a mutation with the React action and rendering model.
I use the intended callers to decide: a webhook or external API client needs a stable HTTP interface; a React form can benefit from an action. Both require authorization and validation.
Follow-up questions
- Where does status-code design matter?
- Can a Server Component call the underlying DAL directly?
- Route HandlersOfficial documentation
- Mutating dataOfficial documentation
02When is SSE a reasonable choice instead of a WebSocket?
SSE suits server-to-browser updates such as job progress when client commands can use ordinary HTTP. A bidirectional high-frequency protocol may justify WebSockets instead.
With SSE I still design reconnection, event identity, authorization, buffering and disconnection cleanup. The transport does not guarantee that an event is processed exactly once.
Follow-up questions
- How would you resume after a lost connection?
- What changes when several application instances publish events?
- HTML server-sent events standardOfficial documentation
- Self-hosting Next.jsOfficial documentation
03Why is accepting image/png in FormData not enough?
The media type and filename are client assertions. I enforce byte limits and supported content through the upload pipeline, restrict storage ownership and validate metadata before exposing the object.
For large files I consider signed direct uploads, then verify completion and process asynchronously through a durable job system. I also define cleanup for abandoned uploads.
Follow-up questions
- Where are limits enforced before memory is exhausted?
- How do you prevent overwriting another user's file?
- Route HandlersOfficial documentation
- Data securityOfficial documentation
04What must happen when a streaming client disconnects?
The producer should stop work that exists only for that subscriber. Clear its timers, release broker subscriptions and abort upstream reads when the platform delivers cancellation or request abort.
I also make cleanup idempotent because more than one lifecycle path can attempt it. Shared producers need reference-aware cleanup so one disconnect does not stop every subscriber.
Follow-up questions
- What if cancellation arrives before setup finishes?
- How can you detect a subscription leak in a test?
- HTML server-sent events standardOfficial documentation
- Self-hosting Next.jsOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- Route HandlersOfficial documentation
- Data securityOfficial documentation
- HTML server-sent events standardOfficial documentation
- Self-hosting Next.jsOfficial documentation