Skip to content
jshacks.dev
Security

Validate content types on uploads

Check an uploaded file's real type by reading its magic bytes, and compare the declared Content-Type against an allowlist, not the file name.

1 min read
Summarize in AI

The Content-Type of an upload is whatever the client says, and so is the extension. Both are only hints. Check them against an allowlist, then verify the content as the next snippet shows.

upload.jsJavaScript
const ALLOWED = new Set(['image/png', 'image/jpeg', 'image/webp']);

export function checkUpload(file) {
  if (!ALLOWED.has(file.mimetype)) {
    return { ok: false, reason: `type ${file.mimetype} is not allowed` };
  }
  if (file.size > 2 * 1024 * 1024) {
    return { ok: false, reason: 'file is larger than 2 MB' };
  }
  return { ok: true };
}

console.log(checkUpload({ mimetype: 'image/png', size: 1024 }));
console.log(checkUpload({ mimetype: 'text/html', size: 200 }));
Text
{ ok: true }
{ ok: false, reason: 'type text/html is not allowed' }

An allowlist names what you accept and rejects everything else, including types you have never heard of, which a denylist of .exe and .php cannot do. Serve uploads from a separate domain or with Content-Disposition: attachment and X-Content-Type-Options: nosniff, so a browser never runs one as a page. See the OWASP file upload cheat sheet.

An allowlist on the declared type stops honest mistakes only. A script can claim image/png, so confirm the content too.

Share

More snippets

Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.