Responses, Streaming, Files & Downloads
A Route Handler can return any HTTP response your runtime can produce.
That includes:
JSON
plain text
HTML
XML
CSV
images
binary files
downloads
redirects
streams
empty responses
The core primitive is the Web Response API.
JSONβ
export async function GET() {
return Response.json({
ok: true,
version: 1,
})
}
With status and headers:
return Response.json(
{ project },
{
status: 200,
headers: {
'X-Request-Id': requestId,
},
},
)
Plain textβ
return new Response('OK', {
status: 200,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
},
})
XMLβ
return new Response(xml, {
headers: {
'Content-Type': 'application/xml; charset=utf-8',
},
})
Custom XML endpoints might include:
/rss.xml
/feed.xml
/.well-known/*
But remember that Next.js has built-in metadata conventions for several common files such as sitemap, robots, icons, and Open Graph images.
CSVβ
return new Response(csv, {
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': 'attachment; filename="report.csv"',
},
})
For very large exports, prefer streaming generation rather than constructing a huge string in memory.
Downloadsβ
A download response typically needs:
Content-Type
Content-Disposition
Content-Length (when known)
Cache-Control (when appropriate)
Example:
return new Response(bytes, {
status: 200,
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="invoice.pdf"',
},
})
Safe filenamesβ
Do not insert raw user input into Content-Disposition.
Dangerous:
`attachment; filename="${request.nextUrl.searchParams.get('name')}"`
Normalize or generate server-owned filenames.
Header injection and malformed filenames should not become part of the public response.
Browser display vs forced downloadβ
Inline:
Content-Disposition: inline
Download:
Content-Disposition: attachment
The browser can still apply its own behaviour depending on type and security policy.
Streaming mental modelβ
A stream allows the server to send data progressively:
producer
β chunk
Response stream
β chunk
client begins consuming
β chunk
producer continues
This can improve:
- time to first byte
- memory usage
- perceived latency
- long generated responses
It does not make slow work disappear.
Web ReadableStreamβ
Example:
const encoder = new TextEncoder()
const stream = new ReadableStream({
async start(controller) {
controller.enqueue(encoder.encode('first\n'))
controller.enqueue(encoder.encode('second\n'))
controller.close()
},
})
return new Response(stream, {
headers: {
'Content-Type': 'text/plain; charset=utf-8',
},
})
This is standard Web Streams behaviour.
Streaming from an upstream responseβ
Often the best approach is to avoid buffering:
const upstream = await fetch(upstreamUrl)
if (!upstream.ok || !upstream.body) {
return Response.json(
{ error: 'UPSTREAM_FAILED' },
{ status: 502 },
)
}
return new Response(upstream.body, {
status: 200,
headers: {
'Content-Type': upstream.headers.get('content-type') ?? 'application/octet-stream',
},
})
Do not blindly copy every upstream header.
Build an allow-list.
Why not copy all upstream headers?β
Upstream headers may include:
- hop-by-hop values
- internal server metadata
- cookies you do not intend to expose
- cache policy unsuitable for your public endpoint
- private infrastructure information
Treat proxy response headers as a deliberate API contract.
Streaming AI or generated outputβ
LLM and other generated-content endpoints often return incrementally.
Architecture:
client
β request
Route Handler
β upstream/model
stream chunks
β
client renders incrementally
Use maintained streaming libraries when they correctly model cancellation, backpressure, provider errors, and framing.
The important Next.js concept is that Route Handlers can return Web streams.
Framing streamed dataβ
Raw chunks need a protocol.
Possible formats:
newline-delimited JSON
Server-Sent Events
plain text chunks
binary framing
vendor SDK protocol
Do not invent ambiguous chunk boundaries.
Server-Sent Eventsβ
An SSE response typically uses headers such as:
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
But deployment environment matters. Some serverless platforms have execution-duration limits that make long-lived streams unsuitable.
Evaluate the host before choosing SSE/WebSocket-like architectures.
WebSockets are not equivalent to Route Handler streamingβ
Streaming an HTTP response is:
one request
β one response stream
WebSockets are:
long-lived bidirectional connection
Some Next.js hosting models cannot keep arbitrary WebSocket connections alive through Route Handler compute.
Use dedicated realtime infrastructure when needed.
Stream failure after headers commitβ
Before response starts:
error
β choose 500/502/etc
After bytes are sent:
status already committed
You cannot suddenly change the HTTP status to 500 after streaming has begun.
Therefore your stream protocol needs an application-level error strategy when late failures are possible.
Cookies and streamingβ
HTTP headers, including Set-Cookie, must be established before body streaming starts.
Do not attempt to modify cookies after chunks have already been sent.
Backpressureβ
A producer can generate data faster than the client can consume it.
A correct streaming design should respect the stream abstraction instead of accumulating unlimited pending chunks in memory.
Libraries and platform adapters may handle some details, but you still need to measure memory behaviour under slow clients.
Abort/cancellationβ
If the client disconnects, use request/stream cancellation signals where your upstream supports them.
Conceptually:
client aborts
β
request.signal aborts
β
upstream fetch/model work cancelled
This protects wasted compute.
Range requestsβ
Large media/file systems may require HTTP Range semantics.
That involves:
Range
Accept-Ranges
Content-Range
206 Partial Content
Do not implement partial-content semantics casually. Prefer object storage/CDN features when serving large media.
Object storage for large downloadsβ
Instead of proxying every byte through Next.js:
client
β authenticated request
Next.js
β short-lived signed URL
object storage/CDN
β file bytes
client
This can reduce app compute and improve global delivery.
Response cachingβ
A response body and a server data cache are different layers.
HTTP headers such as:
Cache-Control
ETag
Last-Modified
Vary
control HTTP/proxy/browser/CDN semantics.
Next.js server caching/prerendering is a separate concern.
Phase 6 covers the broader cache layer model.
Varyβ
If a response representation changes based on a request header, caches need to know.
Example:
Vary: Accept-Encoding
For custom negotiation, choose Vary carefully because high-cardinality headers can destroy cache efficiency.
Never vary on arbitrary identifiers unless that is truly part of the cache design.
ETags and conditional requestsβ
For stable resources, HTTP conditional requests may use:
ETag
If-None-Match
304 Not Modified
Whether you implement this yourself depends on the hosting/CDN layer and content type.
Do not duplicate platform caching logic without a concrete need.
Empty responsesβ
return new Response(null, { status: 204 })
Good for operations where no response body is needed.
Error downloads/streamsβ
Do not return an HTML framework error page from an API that promises JSON or binary data.
Catch known boundary failures and map them to the endpoint contract.
Example:
try {
const file = await loadFile(id)
return new Response(file.bytes, {
headers: { 'Content-Type': file.type },
})
} catch (error) {
if (error instanceof MissingFileError) {
return Response.json(
{ error: 'NOT_FOUND' },
{ status: 404 },
)
}
throw error
}
Unexpected failures should still reach observability.
Common mistakesβ
Buffering huge exportsβ
Stream or offload them.
Reflecting user-controlled filenamesβ
Normalize server-side.
Copying all upstream headersβ
Use an allow-list.
Treating HTTP streaming as WebSocket transportβ
They solve different problems.
Assuming status can change after streaming startsβ
Headers/status are already committed.
Proxying large static files through app compute unnecessarilyβ
Use storage/CDN/signed URLs where appropriate.
Debugging checklistβ
- Inspect
Content-Type. - Inspect
Content-Disposition. - Verify status before body consumption.
- Confirm streamed chunks use a clear framing protocol.
- Test slow-client/backpressure behaviour.
- Test client cancellation.
- Check late-stream error handling.
- Check cookie/header mutations happen before streaming.
- Compare local vs deployed buffering behaviour.
- Measure memory for large exports/downloads.
Interview questionsβ
Can a Route Handler return non-JSON data?
Yes. It can return any HTTP content type supported by the runtime, including text, XML, binary files, and streams.
Why canβt you set a cookie after streaming begins?
Because cookies are response headers and HTTP headers are committed before body bytes are sent.
Why use signed object-storage URLs for large files?
They avoid routing large byte transfers through application compute and usually provide better scalability/CDN integration.
What happens if a stream fails after the first chunk?
The HTTP status is already committed, so the stream protocol needs a late-error strategy.
Exerciseβ
Build two endpoints:
GET /api/reports/:id.csv
GET /api/reports/:id/download
The first streams CSV rows. The second returns a short-lived storage download URL after authorization. Document headers, error contract, cancellation, and why the two transfer strategies differ.