Guide
Middleware
Transform streams and hook into upload lifecycle
Middleware lets you intercept and transform file uploads before they reach the driver, and trigger actions after uploads complete.
Interface
interface BeforeUploadResult {
stream?: ReadableStream<Uint8Array>; // replacement stream
options?: UploadOptions; // replacement options
size?: number; // byte length of the replacement stream
}
interface MiddlewareHook<TMeta extends Record<string, unknown> = Record<string, unknown>> {
beforeUpload?: (
stream: ReadableStream<Uint8Array>,
options: UploadOptions,
) => Promise<BeforeUploadResult | void>;
afterUpload?: (
result: UploadResult<TMeta>,
options: UploadOptions,
) => Promise<void>;
}beforeUpload
Runs before the driver receives the stream. You can replace the stream (e.g. compress, encrypt, validate) or modify upload options (e.g. inject metadata, rewrite filenames).
Return { stream }, { options }, both, or undefined to pass through unchanged.
import { FilewayClient, MiddlewareHook } from "@fileway/core";
// Fails the upload once more than 10 MB has flowed through, without
// holding the file in memory.
const sizeLimit: MiddlewareHook = {
async beforeUpload(stream, options) {
let total = 0;
const limited = stream.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
total += chunk.byteLength;
if (total > 10 * 1024 * 1024) {
controller.error(new Error("File exceeds 10MB limit"));
return;
}
controller.enqueue(chunk);
},
}),
);
// Bytes pass through unchanged, so the known size still holds.
return { stream: limited, size: options.size };
},
};Keeping options.size correct
options.size lets drivers stream without buffering (S3 uses it to sign the body chunk by chunk) and gives progress events a total. A replacement stream may not be the same length (compression, encryption, added headers), so when beforeUpload returns a stream, Fileway drops the known size unless the middleware vouches for it:
- Return
sizewith the new stream's byte length (orsize: options.sizewhen the length does not change), or - return
optionswith a differentsize.
Spreading the incoming options ({ ...options }) does not count, because it copies the old size whether or not it still applies. Without a size the upload still works: S3 falls back to a multipart upload and progress events report bytes without a total.
afterUpload
Runs after the driver returns a successful upload result, with the options the driver received (after beforeUpload). Useful for logging, webhook calls, database indexing, or cache invalidation.
const logger: MiddlewareHook = {
async afterUpload(result, options) {
console.log(`Uploaded ${options.filename} to ${result.path} (${result.size} bytes)`);
},
};Written inline, afterUpload knows the driver's metadata type:
const client = new FilewayClient({
driver: new S3Driver({ bucket: "uploads", credentials }),
middlewares: [
{
async afterUpload(result) {
await db.files.insert({ key: result.path, etag: result.meta.etag }); // typed as S3Meta
},
},
],
});Usage
Pass middleware via the middlewares array in the client config:
const client = new FilewayClient({
driver: new LocalDriver({ directory: "./uploads" }),
middlewares: [sizeLimit, logger],
});
await client.upload(stream, { filename: "report.pdf" });
// → beforeUpload runs first (size check)
// → driver uploads
// → afterUpload runs (log)Middleware runs in the order they are defined. All beforeUpload hooks execute first (in order), then the driver upload, then all afterUpload hooks (in order).
Example: Metadata Injection
const injectMeta: MiddlewareHook = {
async beforeUpload(_stream, options) {
const timestamp = Date.now().toString();
return {
options: {
...options,
metadata: {
...options.metadata,
uploadedAt: timestamp,
},
},
};
},
};Example: Stream Compression
import { FilewayClient, MiddlewareHook } from "@fileway/core";
const compressor: MiddlewareHook = {
async beforeUpload(stream, options) {
const compressed = stream.pipeThrough(new CompressionStream("gzip"));
// The compressed length is unknown, so no `size` is returned and the
// original one is dropped.
return {
stream: compressed,
options: { ...options, filename: `${options.filename}.gz`, mimeType: "application/gzip" },
};
},
};Was this page helpful?