Managing image upload in MERN web app using firebase. Two ways to do!
Tags: firebase, react, webdev, fullstack
Published: 2024-03-10 10:18:50

### What We Will Cover in This Blog?
We will discuss concepts for image uploads in web applications. To aid understanding, we'll use image illustrations instead of code to avoid unnecessary complexity.

### Why Do We Need Image Uploads in Our Application?
In many projects, you might find the need for users to upload profile pictures or share image posts, especially in social media platforms like Instagram or Facebook. Image uploads are essential for various functionalities within web applications, such as personalization, content sharing, and enhancing user engagement. Understanding the optimized way of handling image uploads could help you build improved and optimized scalable applications.


### Basic Structure of a Full-Stack Web Application
A typical full-stack web application consists of three main components: the Frontend, Backend, and Database. This architecture is often referred to as the 3-tier architecture.

![Illustration of 3 tier architecture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0qerzxre8ihzqnrcxbzt.png)

- **Frontend**: This component handles the user interface and interacts with users directly through web browsers. It's responsible for rendering the user interface, handling user input, and making requests to the backend. Popular frameworks or libraries such as React, Angular, and Vue are commonly used for frontend development.

- **Backend**: The backend component serves as the server-side of the application, handling business logic, data processing, and communication with the database. It receives requests from the frontend, processes them, and sends back appropriate responses.

- **Database**: The database component stores and manages the application's data. It provides persistent storage for user information, content, and other relevant data. In MERN applications, MongoDB is commonly used as the database due to its flexibility and compatibility with JavaScript.

Here we will understand concepts using **React.js** for frontend, **Node.js** for backend, and **MongoDB** for database.

### Types of Databases

![Types of database](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1r041fngarixyz1f0u8g.png)

Databases play a crucial role in storing data for web applications. There are various types of databases tailored for different data types.

- **Text-based Databases**: These databases are designed for storing text-related data. However, using them for media files like images and videos isn't ideal due to the need for complex conversions, leading to increased bandwidth usage.

- **Media-based Databases**: Dedicated to storing media files such as images, videos, and audios, media-based databases provide efficient storage and management of such content without the need for complex conversions.

For our project, we've chosen MongoDB as our text-based database for storing structured data in JSON-like documents. Additionally, Firebase, particularly Firebase Storage, serves as our media-based database, offering scalable and efficient storage solutions for images.


### Two Ways of Uploading Images
The two approaches differ in how images are uploaded, either from the client or the server. Understanding them fully can be aided by visual representation.

#### 1. Image Upload Through Server

![Illustration showing image upload via node.js server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hr39rp2kskny2yxwtep8.png)

In this approach, the image file is sent from the client to the server, and then from the server to Firebase using Multer(used to manage file uploads on the server-side) and the Firebase Node.js SDK. Once Firebase returns a link URL, it's saved to the database. However, there are some issues with this approach:

- **Server Load** : The server may experience a heavy load as it handles multiple tasks simultaneously.
      - Larger Image size (multiplied with no of user interactions)
      - Making API calls to firebase & mongoDB.
- **Bandwidth Increase** : Bandwidth usage increases as API calls are made with image files.
3. **Possible Errors** : Errors may occur while uploading images to Firebase, leading to the failure of API calls. Although this incurs the cost of an API call, the action does not perform as expected, limiting your API calls.

With this understanding, let's explore another approach.

#### 2.Image Upload from Client

![Image upload from from client side application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mq5fcv0jr1g52g1i84gg.png)

In this approach, images are sent directly from our client to Firebase using the Firebase SDK. If the file upload is successful, Firebase returns the upload URL, which is then used to call an API on the server to save the image to the database. Let's see if this approach has addressed the issues encountered in the previous approach: 

- The load on the server has decreased. In the first approach, the server handled 3 requests (3 responses), whereas in the second approach, it handles only 2 requests (2 responses), thus reducing the load on the server.

- Since we are not sending images with API calls to the server, our bandwidth usage will also not increase significantly.

- With fewer tasks handled by the server, the likelihood of errors occurring also decreases.

### Delete Operation of Image

To perform the delete operation, we have two approaches: deleting from the server or deleting from the client after removal from the database. Each method has its own set of pros and cons.

#### Approach 1: Delete Operation Through the Server

![Delete operation through server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2f4ul0k51fcfmpoz4ao1.png)

#### Pros :
 - Eliminates the need for an additional API call to Firebase on the client.
 - Ensures reliable deletion of the image as all operations are performed through a single API call to the server.

#### Cons :
 - Increases server load due to the addition of the Firebase Node.js SDK.
 - Introduces complexity as Firebase configurations must be managed within the Node.js server application in addition to the client side.

#### Approach 2: Delete Operation Through the Client

![Delete operation through client](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9byntej8y4o6zl29258c.png)

#### Pros :
 - Reduces server load since the server handles only one request and response.
 - Requires less storage as the Firebase SDK is installed only on the client side.
 - Decreases complexity in comparison to server-side deletion.

#### Cons :
 - While deleting images from the client is feasible, there is a risk of data inconsistency. If an issue arises during the deletion request to Firebase, the media may not be successfully removed, despite the URL being deleted in MongoDB. 

### Choosing the Right Approach
Both approaches have their merits, and the choice ultimately depends on personal preference and project requirements. While Approach 1 ensures all operations are centralized and performed on the server, Approach 2 offers simplicity and reduces server load. Consider your priorities and project constraints when deciding which approach to implement for image deletion.

### Firebase setup in client & server side
Your firebase need to be configured both in server side as well as on client side based on your requirements.

![Setup of firebase in both client & server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8uvma5ixdacucdio6tq.png)

### Conclusion

In conclusion, handling image uploads in MERN web applications is crucial for building scalable and efficient systems. Let's summarize the key points discussed:

- **Understanding System Design**: We explored the system design concepts for image uploads in web applications, emphasizing the importance of a clear architecture.

- **Two Approaches for Image Uploads**: We discussed two approaches for uploading images: sending images through the server to Firebase and directly from the client to Firebase. Each approach has its advantages and considerations.

- **Delete Operation**: In addition to uploads, we also discussed the concept of image deletion. We explored two approaches: deletion from the server and deletion from the client. Both methods offer unique benefits and considerations, requiring careful consideration based on project requirements.

- **Optimization and Efficiency**: We considered factors such as server load, bandwidth usage, and error handling to optimize the image upload process for improved performance and user experience.