javascript / expert
Snippet
Streaming Response Modification via TransformStream
TransformStream allows you to process and modify data chunks as they stream from the server to the client. This is extremely memory-efficient for large payloads because the entire response never needs to be held in memory.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
export async function middleware(req) {const response = await fetch(req.url);const { readable, writable } = new TransformStream({transform(chunk, controller) {const text = new TextDecoder().decode(chunk);const modified = text.replace(/CLIENT_ID/g, 'REDACTED');controller.enqueue(new TextEncoder().encode(modified));}});response.body.pipeTo(writable);return new Response(readable, response);}
nextjs
Breakdown
1
new TransformStream({ transform(chunk, ... ) })
Defines the logic to intercept and modify streaming data chunks on the fly.
2
const modified = text.replace(...);
Performs a string substitution on the current chunk, such as masking sensitive identifiers.
3
response.body.pipeTo(writable);
Connects the original response stream to the transformer's input for processing.