Sanitize Upload Filenames
Make untrusted upload names safe by stripping paths, control characters, reserved names and dangerous extensions.
Code
const RESERVED_NAMES = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
export interface SanitizeOptions {
maxLength?: number;
replacement?: string;
fallback?: string;
}
export function sanitizeFilename(input: string, options: SanitizeOptions = {}): string {
const { maxLength = 120, replacement = "_", fallback = "file" } = options;
if (!Number.isInteger(maxLength) || maxLength < 1) {
throw new RangeError("maxLength must be a positive integer");
}
if (!replacement || /[\\/:*?"<>|]/.test(replacement)) {
throw new TypeError("replacement contains forbidden characters");
}
const normalized = String(input).normalize("NFC").replace(/[\u0000-\u001f\u007f]/g, "");
const base = normalized.split(/[\\/]/).pop() ?? "";
let name = base
.replace(/[<>:"|?*]/g, replacement)
.replace(/\s+/g, " ")
.trim()
.replace(/^\.+/, "")
.replace(/\.+$/, "");
if (!name) return fallback;
const dot = name.lastIndexOf(".");
const extension = dot > 0 ? name.slice(dot).slice(0, 16) : "";
let stem = dot > 0 ? name.slice(0, dot) : name;
if (RESERVED_NAMES.test(stem)) stem = "_" + stem;
const budget = Math.max(1, maxLength - extension.length);
stem = stem.slice(0, budget).trim();
if (!stem) stem = fallback;
name = stem + extension;
return name;
}What the code does
The working surface is the function sanitizeFilename — everything else is wiring.
A guard precedes the RangeError and TypeError: bad state stops the flow there instead of continuing.
Caveats
- The guard
!nameshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The entry-point signature is export function sanitizeFilename(input: string, options: SanitizeOptions = {})
The surface worth importing is sanitizeFilename; the helpers around it are private to the snippet.
Statements that matter
throw new TypeError("replacement contains forbidden characters");
throw new RangeError("maxLength must be a positive integer");
const base = normalized.split(/[\\/]/).pop() ?? "";
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What happens if the preconditions do not hold?
- `RangeError` and `TypeError` is raised at the guard (`!name`), so invalid state never reaches the main logic.
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `sanitizeFilename` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.