Tutorial

File Type Sniffing

Sniff the real file type from magic bytes instead of trusting the extension or Content-Type, and reject mismatches before storing the upload.

On this page

  1. Introduction
  2. Read the magic bytes
  3. Do not trust the header
  4. Reject before storage
  5. Stream the sniff
  6. Test the rename
  7. Sources

Introduction

This guide covers file type sniffing from magic bytes, a recurring concern in the file-upload scenario. A client can name a script photo.jpg and set Content-Type image/jpeg, and if you trust either you store an executable as an image. Reading the first bytes and matching the magic number tells you the real type, and rejecting a mismatch before storage closes the hole.

Read the magic bytes

Pull the first 8 to 16 bytes and match them against the known magic numbers for your allowed types, which is what the OS does to open a file regardless of extension.

The trade-off worth naming is that pull the first 8 to 16 bytes and match them against the known magic numbers for your allowed types, which is what the os does to open a file regardless of extension adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.

import { fileTypeFromBuffer } from 'file-type';
const head = new Uint8Array(await file.slice(0, 4100).arrayBuffer());
const type = await fileTypeFromBuffer(head);
if (!type || !['png','jpg','webp'].includes(type.ext)) throw new Error('unsupported');

Do not trust the header

The Content-Type and the extension are both client-controlled, so use the sniffed type as the truth and treat a mismatch as a rejection, not a correction.

The trade-off worth naming is that the content-type and the extension are both client-controlled, so use the sniffed type as the truth and treat a mismatch as a rejection, not a correction adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.

const allowed = { png: 'image/png', jpg: 'image/jpeg', webp: 'image/webp' };
const ext = file.name.split('.').pop()?.toLowerCase();
if (type && allowed[type.ext] && type.ext !== ext) {
  throw new Error(`extension "${ext}" does not match sniffed "${type.ext}"`);
}

Reject before storage

Run the sniff before you write to storage so a mislabeled executable never lands, which is cheaper than scanning after the fact and safer for any later serving.

The trade-off worth naming is that run the sniff before you write to storage so a mislabeled executable never lands, which is cheaper than scanning after the fact and safer for any later serving adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.

Stream the sniff

For a streaming upload, sniff from the first chunk and only then pipe the rest to storage, so you do not buffer the whole file to check its type.

The trade-off worth naming is that for a streaming upload, sniff from the first chunk and only then pipe the rest to storage, so you do not buffer the whole file to check its type adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.

Test the rename

Upload a renamed executable and assert it is rejected, then upload a real image and assert it passes, so the sniff is the gate, not the name.

The trade-off worth naming is that upload a renamed executable and assert it is rejected, then upload a real image and assert it passes, so the sniff is the gate, not the name adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.

Sources

Sources: file-type library, magic numbers.

FAQ

Is sniffing the first bytes enough?
For common formats like PNG, JPEG, and PDF the magic number is in the first few bytes, so yes; for formats that need more context, read a small buffer and use a library like file-type that knows the offsets.
Should I still check the extension?
Use the sniffed type as the truth and the extension as a hint; reject when they disagree, because the sniffed type is what the bytes actually are.

Related Examples