Simeon Griggs
Customer Education at Sanity
Prevent references to large files to reduce the chances of high bandwidth usage
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.
Customer Education at Sanity
Uses @sanity/asset-utils to validate an uploaded image by its ID
Go to Schema validation rules to enforce image size or file typeNot all Unpublished Documents are created equal
Go to GROQ Query for new and unpublished DocumentsGet details of the currently logged in Sanity user
Go to useCurrentUser Custom React Hook