Upload Middleware
Not every upload should be accepted as it is. You may want to cap the size, allow only images, convert everything to WebP or read an MP3's duration. Middlewares do exactly this. They are small functions that run one after another before a file is stored, and each can reject the upload or change the file and its metadata. This chapter lists the built-in ones in three groups: validators, transformers and name helpers.
Middlewares run in order before add() and replace(). Throw AttachmentValidationError to abort the upload.
type UploadMiddleware<TMeta = unknown> = ((
file: File,
meta: TMeta,
files: AttachmentData<TMeta>[],
) => Promise<{ file: File; meta: TMeta }>) & {
check?: (file: File, files: AttachmentData<TMeta>[]) => void;
};
Middlewares run in the order you list them. The diagram shows a typical chain: the cheap checks come first and can stop the upload early, then the transformers reshape the file.
flowchart LR
F[File + meta] --> V1[count] --> V2[mime] --> T1[toWebP] --> T2[imgstat] --> R[Stored file + meta]
V1 -. throws .-> X[AttachmentValidationError]
V2 -. throws .-> X
Middlewares are attached per category, in the middlewares array of the category object (every category also needs its two-character code, see Handler API):
import { defineAttachments, createLocalProvider, count, mime, toWebP, imgstat } from '@atom-forge/attachment';
const attachments = defineAttachments({
user: defineAttachments.entity({
avatar: { code: 'AV', middlewares: [count(1), mime('image/*'), toWebP(80, 400, 400), imgstat()] },
gallery: { code: 'GA', middlewares: [mime('image/*'), toWebP(80)] },
}),
}, { provider: createLocalProvider('./var/uploads') });
A middleware should return a new meta object instead of mutating the one it received: the caller may reuse one meta object for several uploads. The built-in transformers do so.
Limits that depend on other files: check
The files argument is the list the request loaded. In atomic mode (see Concurrent Writes) concurrent uploads may change that list before the upload is saved, so a limit that depends on the other files also needs a synchronous check part, which runs again on the fresh list when the upload is saved. count() and sumSize() have it. A custom limit adds it with Object.assign:
import { AttachmentValidationError, type AttachmentData, type UploadMiddleware } from '@atom-forge/attachment';
export function maxPdfs(max: number): UploadMiddleware {
const check = (file: File, files: AttachmentData[]) => {
const pdfs = files.filter((f) => f.filename.endsWith('.pdf')).length;
if (file.name.endsWith('.pdf') && pdfs >= max) {
throw new AttachmentValidationError(`At most ${max} PDF files.`);
}
};
return Object.assign(async (file: File, meta: unknown, files: AttachmentData[]) => {
check(file, files);
return { file, meta };
}, { check });
}
In the default mode check is not called separately; the middleware itself runs it.
Validators
count(max)
Rejects the upload when the category already has max or more files. In atomic mode the limit also holds for concurrent uploads.
count(1)
count(10)
size(maxBytes)
Rejects files larger than maxBytes.
size(2 * 1024 * 1024)
sumSize(maxBytes)
Rejects when total size of all existing files + the new file exceeds maxBytes. In atomic mode the limit also holds for concurrent uploads.
sumSize(50 * 1024 * 1024)
mime(pattern)
Allows only files whose MIME type matches. Supports wildcard subtypes.
mime('image/*')
mime(['image/jpeg', 'image/png', 'image/webp'])
ext(extensions)
Allows only files with a matching extension (case-insensitive, leading dot required).
ext(['.jpg', '.jpeg', '.png', '.webp'])
Require peer dependencies (sharp, music-metadata).
toWebP(lossy?, width?, height?)
Converts the uploaded image to WebP. EXIF orientation is applied (phone photos are not stored sideways), and animated GIF/WebP images keep all their frames.
| Param |
Type |
Default |
Description |
lossy |
false | number |
false |
false = lossless; 0–100 = lossy quality |
width |
number |
— |
Max width. One dimension → proportional resize (no enlarge). Both → contain. |
height |
number |
— |
Max height. |
toWebP()
toWebP(80)
toWebP(false, 1280)
toWebP(80, 800, 600)
Peer dependency: sharp
imgstat(cropMode?, focusHash?)
Reads image dimensions, dominant color, animated flag, and crop mode. Returns a new meta object with an ImgStat under meta.img (the caller's meta is not mutated). The dimensions are the displayed ones: for EXIF orientations 5–8 width and height are swapped.
| Param |
Type |
Default |
Description |
cropMode |
'e' | 'a' | 'c' | 'b' | Focus |
'e' |
Crop strategy stored for thumbnail URL building |
focusHash |
FocusHashFn |
— |
Required to store meta.img.ch for manual focus |
imgstat()
imgstat('a')
imgstat('c')
imgstat('b')
imgstat({ x: 500, y: 300, s: { x: 0, y: 0, w: 1000, h: 1000 } }, focusHash)
Manual focus. A focus URL is accepted by the image server only with a valid hash. Create the hash function with createFocusHash(secret) (server-only export) and use the same secret as createImageServer({ focusSecret }):
import { imgstat, createFocusHash } from '@atom-forge/attachment';
const focusHash = createFocusHash(process.env.FOCUS_SECRET!);
imgstat({ x: 500, y: 300, s: { x: 0, y: 0, w: 1000, h: 1000 } }, focusHash)
imgstat stores the hash in meta.img.ch; the client puts it into the URL. Without focusHash, meta.img.ch is missing and the client falls back to 'e' instead of the stored focus.
The stored ImgStat:
interface ImgStat {
w: number;
h: number;
d: string;
a: boolean;
c: 'e' | 'a' | 'c' | 'b' | Focus;
ch?: string;
}
const meta = attachment.meta as { img: ImgStat };
Peer dependency: sharp
Reads the duration of an MP3 and returns a new meta object with it under meta[metaKey] (seconds, number; the caller's meta is not mutated). Default metaKey: 'duration'.
getMp3Duration()
getMp3Duration('durationSeconds')
Peer dependency: music-metadata
Name helpers
randname()
Replaces the uploaded filename with a random UUID-based name, keeping the extension.
randname()
No extra dependency — uses crypto.randomUUID().
Upload Middleware
Not every upload should be accepted as it is. You may want to cap the size, allow only images, convert everything to WebP or read an MP3's duration. Middlewares do exactly this. They are small functions that run one after another before a file is stored, and each can reject the upload or change the file and its metadata. This chapter lists the built-in ones in three groups: validators, transformers and name helpers.
Middlewares run in order before
add()andreplace(). ThrowAttachmentValidationErrorto abort the upload.type UploadMiddleware<TMeta = unknown> = (( file: File, meta: TMeta, files: AttachmentData<TMeta>[], // existing files in the category ) => Promise<{ file: File; meta: TMeta }>) & { check?: (file: File, files: AttachmentData<TMeta>[]) => void; // optional, see below };Middlewares run in the order you list them. The diagram shows a typical chain: the cheap checks come first and can stop the upload early, then the transformers reshape the file.
Middlewares are attached per category, in the
middlewaresarray of the category object (every category also needs its two-charactercode, see Handler API):import { defineAttachments, createLocalProvider, count, mime, toWebP, imgstat } from '@atom-forge/attachment'; const attachments = defineAttachments({ user: defineAttachments.entity({ avatar: { code: 'AV', middlewares: [count(1), mime('image/*'), toWebP(80, 400, 400), imgstat()] }, gallery: { code: 'GA', middlewares: [mime('image/*'), toWebP(80)] }, }), }, { provider: createLocalProvider('./var/uploads') });A middleware should return a new
metaobject instead of mutating the one it received: the caller may reuse one meta object for several uploads. The built-in transformers do so.Limits that depend on other files:
checkThe
filesargument is the list the request loaded. In atomic mode (see Concurrent Writes) concurrent uploads may change that list before the upload is saved, so a limit that depends on the other files also needs a synchronouscheckpart, which runs again on the fresh list when the upload is saved.count()andsumSize()have it. A custom limit adds it withObject.assign:import { AttachmentValidationError, type AttachmentData, type UploadMiddleware } from '@atom-forge/attachment'; // At most `max` PDF files in the category. export function maxPdfs(max: number): UploadMiddleware { const check = (file: File, files: AttachmentData[]) => { const pdfs = files.filter((f) => f.filename.endsWith('.pdf')).length; if (file.name.endsWith('.pdf') && pdfs >= max) { throw new AttachmentValidationError(`At most ${max} PDF files.`); } }; return Object.assign(async (file: File, meta: unknown, files: AttachmentData[]) => { check(file, files); return { file, meta }; }, { check }); }In the default mode
checkis not called separately; the middleware itself runs it.Validators
count(max)Rejects the upload when the category already has
maxor more files. In atomic mode the limit also holds for concurrent uploads.count(1) // at most one file (avatar use case) count(10) // at most tensize(maxBytes)Rejects files larger than
maxBytes.size(2 * 1024 * 1024) // 2 MBsumSize(maxBytes)Rejects when total size of all existing files + the new file exceeds
maxBytes. In atomic mode the limit also holds for concurrent uploads.sumSize(50 * 1024 * 1024) // 50 MB total for the categorymime(pattern)Allows only files whose MIME type matches. Supports wildcard subtypes.
mime('image/*') mime(['image/jpeg', 'image/png', 'image/webp'])ext(extensions)Allows only files with a matching extension (case-insensitive, leading dot required).
ext(['.jpg', '.jpeg', '.png', '.webp'])Transformers
Require peer dependencies (
sharp,music-metadata).toWebP(lossy?, width?, height?)Converts the uploaded image to WebP. EXIF orientation is applied (phone photos are not stored sideways), and animated GIF/WebP images keep all their frames.
lossyfalse | numberfalsefalse= lossless;0–100= lossy qualitywidthnumberheightnumbertoWebP() // lossless, no resize toWebP(80) // lossy q80 toWebP(false, 1280) // lossless, max-width 1280 toWebP(80, 800, 600) // lossy q80, contain in 800×600Peer dependency:
sharpimgstat(cropMode?, focusHash?)Reads image dimensions, dominant color, animated flag, and crop mode. Returns a new meta object with an
ImgStatundermeta.img(the caller's meta is not mutated). The dimensions are the displayed ones: for EXIF orientations 5–8 width and height are swapped.cropMode'e' | 'a' | 'c' | 'b' | Focus'e'focusHashFocusHashFnmeta.img.chfor manual focusimgstat() // entropy crop (default) imgstat('a') // attention crop imgstat('c') // centre crop imgstat('b') // box: fit inside, no crop imgstat({ x: 500, y: 300, s: { x: 0, y: 0, w: 1000, h: 1000 } }, focusHash) // manual focus (see below)Manual focus. A focus URL is accepted by the image server only with a valid hash. Create the hash function with
createFocusHash(secret)(server-only export) and use the same secret ascreateImageServer({ focusSecret }):import { imgstat, createFocusHash } from '@atom-forge/attachment'; const focusHash = createFocusHash(process.env.FOCUS_SECRET!); // same secret as the image server imgstat({ x: 500, y: 300, s: { x: 0, y: 0, w: 1000, h: 1000 } }, focusHash)imgstatstores the hash inmeta.img.ch; the client puts it into the URL. WithoutfocusHash,meta.img.chis missing and the client falls back to'e'instead of the stored focus.The stored
ImgStat:interface ImgStat { w: number; // displayed width px h: number; // displayed height px d: string; // dominant color (#rrggbb) a: boolean; // animated (GIF / animated WebP) c: 'e' | 'a' | 'c' | 'b' | Focus; // stored crop mode ch?: string; // HMAC hash of focus12 (manual focus only) }const meta = attachment.meta as { img: ImgStat };Peer dependency:
sharpgetMp3Duration(metaKey?)Reads the duration of an MP3 and returns a new meta object with it under
meta[metaKey](seconds, number; the caller's meta is not mutated). DefaultmetaKey:'duration'.getMp3Duration() // → meta.duration getMp3Duration('durationSeconds') // → meta.durationSecondsPeer dependency:
music-metadataName helpers
randname()Replaces the uploaded filename with a random UUID-based name, keeping the extension.
randname() // 'photo.jpg' → 'f47ac10b-58cc-4372-a567-0e02b2c3d479.jpg'No extra dependency — uses
crypto.randomUUID().