MIME Types in JavaScript and Node.js
How to detect and handle MIME types in browser JavaScript, Node.js, and Express.
Published:
Tags: MIME types JavaScript Node.js, content-type detection Node, JavaScript file MIME type
MIME Types in JavaScript and Node.js MIME types control how browsers and servers interpret file content. Handling them correctly in JavaScript — detecting the type before upload, setting the right Content-Type on responses, and validating on the server — prevents rendering failures, upload vulnerabilities, and API integration bugs. --- All the tools discussed here are available for free at theproductguy.in — client-side, no sign-up required. Part of the HTTP Debugging Tools Guide — a complete toolkit for diagnosing web requests. --- What about Browser: Reading MIME Type from File Input? When a user selects a file via , the browser provides a object with a property: The same applies to drag-and-drop: Limitation: is determined by the browser based on file extension (on most platforms) and…
Frequently Asked Questions
How do I detect a file's MIME type in JavaScript?
In the browser, read file.type from a File object — it contains the browser-detected MIME type based on file extension. For server-side Node.js, use the file-type package which reads file magic bytes (the first few bytes that identify the format) for accurate detection regardless of file extension.
How do I set content-type in Express.js?
Use res.type('json') as shorthand for application/json, res.type('html') for text/html, etc. For exact types, use res.setHeader('Content-Type', 'application/json; charset=utf-8'). Express's res.json() automatically sets Content-Type to application/json.
What is the mime npm package?
The mime package maps file extensions to MIME types and vice versa. Use mime.getType('file.pdf') to get 'application/pdf', or mime.getExtension('image/png') to get 'png'. It's useful for Express static file servers, file upload handlers, and anywhere you need to determine Content-Type from a filename.
How do I check MIME type before file upload?
Read file.type from the File object in an onChange handler before calling fetch. Validate against an allowlist: const allowed = ['image/jpeg', 'image/png', 'image/webp']; if (!allowed.includes(file.type)) { showError(); return; }. Always also validate on the server — file.type is trivially spoofable by the client.
How do I detect an image MIME type from bytes?
Use the file-type npm package server-side: const {fileTypeFromBuffer} = await import('file-type'); const type = await fileTypeFromBuffer(buffer); which returns {ext: 'jpg', mime: 'image/jpeg'}. It checks magic bytes — the actual binary signature of the file format — making it reliable even when file extensions are missing or wrong.
All articles · theproductguy.in