javascript / expert
Snippet
Subclassing Web Standard TransformStream for Encrypted Server-Sent Streaming
Demonstrates object-oriented subclassing of the Web API TransformStream class for custom streaming response handlers in Next.js Server Actions or Route Handlers. It uses private class fields (#secretKey), robust constructor validation, custom chunk encryption logic, and explicit stream controller error propagation.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
export class EncryptedTextTransformer extends TransformStream {#secretKey;constructor(secretKey) {if (typeof secretKey !== 'string' || secretKey.length === 0) {throw new Error('Encryption key must be a non-empty string');}let key = secretKey;super({transform(chunk, controller) {try {const encrypted = Array.from(String(chunk)).map((char, i) => String.fromCharCode(char.charCodeAt(0) ^ key.charCodeAt(i % key.length))).join('');controller.enqueue(Buffer.from(encrypted).toString('base64') + '\n');} catch (err) {controller.error(new Error(`Encryption transform failed: ${err.message}`));}}});this.#secretKey = secretKey;}}
nextjs
Breakdown
1
export class EncryptedTextTransformer extends TransformStream {
Extends the native Web API TransformStream to inherit web-standard readable and writable stream interfaces.
2
#secretKey;
Declares a private class field preventing external inspection or tampering of the encryption secret key.
3
controller.error(new Error(`Encryption transform failed: ${err.message}`));
Signals an unrecoverable failure to the consumer stream pipeline using the controller error handle.