Unlock seamless workflows and faster delivery with our latest releases – get the details

Schema validation rules to enforce maximum file size

By Simeon Griggs

Prevent references to large files to reduce the chances of high bandwidth usage

schema.ts

defineField({
  name: "file",
  type: "file",
  validation: (rule) =>
    rule.custom(async (value, { getClient }) => {
      // Remove this condition if the field is optional
      if (!value) {
        return "File is required";
      } 

      // If the field has a value
      if (value?.asset?._ref) {
        // Query the asset's metadata document
        const client = getClient({ apiVersion: `2025-01-01` });
        // Filesize is returned in bytes
        const size = await client.fetch(`*[_id == $id][0].size`, {
          id: value.asset._ref,
        });
        // Cannot be more than 20MB
        // (adjust this number as required)
        if (size > 20000000) {
          return "File size must be less than 20MB";
        }
      }
      
      return true;
    }),
}),

The custom validation rule in this snippet will mark this file field type invalid if the uploaded file is greater than 20MB.

You could adjust this logic to either change the maximum file size, or enforce a minimum file size.

Note that this rule will not prevent larger files from being uploaded, only prevent a document from referencing a file greater than the enforced size.

If your concern is having too-large files stored in your project's dataset, you may additionally like to create a Migration script to periodically remove files over a certain size.

Contributor

Other schemas by author