Skip to main content

Command Palette

Search for a command to run...

Handling Uploaded Files in Node.js

Updated
5 min read
Handling Uploaded Files in Node.js

A Deep Dive into Storage, Static Serving, and Security in Express


Introduction

File uploads are a common feature in modern applications, whether it is uploading profile images, documents, or media files. However, uploading a file is only part of the process. Once uploaded, the file must be stored, accessed, and served securely.

Understanding where files are stored, how they are accessed, and how to serve them efficiently is essential for building production-ready backend systems.

This blog explores file storage strategies, serving static files in Express, accessing uploaded files via URLs, and important security considerations.


Where Uploaded Files Are Stored

When a file is uploaded using middleware like Multer, it is typically stored on the server’s file system.

Default Behavior

If configured with disk storage, files are saved in a specific folder:

/uploads
   ├── image1.jpg
   ├── document.pdf
   └── avatar.png

Example Configuration

const upload = multer({ dest: "uploads/" });

What Happens

  • File is received from client

  • Stored in the uploads folder

  • Metadata is attached to req.file


Folder-Based Storage Structure

project-root/
  ├── uploads/
  │     ├── users/
  │     ├── documents/
  │     └── temp/
  ├── src/
  └── app.js

Why Structure Matters

  • Organizes files logically

  • Prevents clutter

  • Makes file management easier


Local Storage vs External Storage

Choosing where to store files is an important architectural decision.


Local Storage

Files are stored directly on the server.

Advantages

  • Simple to implement

  • Fast access

  • No external dependency

Disadvantages

  • Limited storage

  • Not scalable

  • Risk of data loss


External Storage (Cloud)

Files are stored on services like:

  • AWS S3

  • Cloudinary

  • ImageKit

Advantages

  • Highly scalable

  • CDN support (fast delivery)

  • Reliable and secure

Disadvantages

  • Requires setup

  • Additional cost


Key Insight

  • Local storage → good for development

  • External storage → best for production


Serving Static Files in Express

Once files are stored, they need to be accessible. This is done using static file serving.


What is Static File Serving?

It allows files stored on the server to be accessed directly via a URL.


Example

app.use("/uploads", express.static("uploads"));

What This Does

  • Maps /uploads URL to uploads folder

  • Makes files publicly accessible


Example URL

http://localhost:3000/uploads/image1.jpg

Static File Serving Flow

Client → Request File URL → Express Static Middleware → File System → Response

Accessing Uploaded Files via URL

After enabling static serving, accessing files becomes straightforward.


Example

If file is stored as:

/uploads/profile.png

You can access it via:

http://localhost:3000/uploads/profile.png

Real-World Use Cases

  • Displaying user avatars

  • Showing uploaded documents

  • Serving media files


Example in Frontend

<img src="http://localhost:3000/uploads/profile.png" />

Upload Storage Structure Diagram

Client Upload
     ↓
Server (Express)
     ↓
Multer Middleware
     ↓
uploads/ folder
     ↓
File stored on disk

Static File Serving Flow Diagram

Client Request (/uploads/file.jpg)
        ↓
Express Static Middleware
        ↓
Locate File in Folder
        ↓
Send File as Response

Security Considerations for File Uploads

Handling file uploads without proper security can lead to serious vulnerabilities.


1. Validate File Types

Only allow specific MIME types.

if (!["image/png", "image/jpeg"].includes(file.mimetype)) {
  return cb(new Error("Invalid file type"));
}

2. Limit File Size

Prevent large file uploads.

limits: { fileSize: 5 * 1024 * 1024 }

3. Use Unique File Names

Avoid overwriting files.

Date.now() + "-" + file.originalname

4. Avoid Public Access to Sensitive Files

Do not expose:

  • Private documents

  • Confidential data


5. Store Files Outside Root (Optional Advanced Practice)

Prevents direct access unless explicitly served.


6. Clean Up Temporary Files

Delete unused or failed uploads.

fs.unlinkSync(file.path);

Safe File Handling Practices

  • Always validate input

  • Sanitize file names

  • Restrict upload locations

  • Monitor storage usage

  • Use cloud storage for production


Key Takeaways

  • Uploaded files are stored in server directories

  • Static middleware allows file access via URL

  • Local storage is simple but limited

  • Cloud storage is scalable and production-ready

  • Security is critical in file handling


Conclusion

Handling uploaded files involves more than just receiving them. Proper storage, efficient access, and strong security practices are essential for building reliable applications.

By understanding how files are stored and served, and by implementing best practices, you can build robust systems that handle user uploads safely and efficiently.

The next step is to integrate cloud storage solutions and optimize file delivery using CDNs for production-grade applications.