Skip to content
Attachment
Language:en Author:AtomForge

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>[],   // 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.

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';

// 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 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)   // at most one file (avatar use case)
count(10)  // at most ten

size(maxBytes)

Rejects files larger than maxBytes.

size(2 * 1024 * 1024)   // 2 MB

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)   // 50 MB total for the category

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'])

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.

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()              // lossless, no resize
toWebP(80)            // lossy q80
toWebP(false, 1280)   // lossless, max-width 1280
toWebP(80, 800, 600)  // lossy q80, contain in 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()        // 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 as createImageServer({ 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)

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;                    // 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: sharp

getMp3Duration(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). Default metaKey: 'duration'.

getMp3Duration()                  // → meta.duration
getMp3Duration('durationSeconds') // → meta.durationSeconds

Peer dependency: music-metadata


Name 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().