How to add authentication in file uploads using Node.js ?
Last Updated :
01 Aug, 2024
There are multiple ways to upload files and apply authentications to them. The easiest way to do so is to use a node module called multer. We can add authentication by restricting users on file uploads such as they can upload only pdf and the file size should be less than 1 Mb.
There are many modules available in the market but multer is the most popular. It provides us with different options to customize and restrict which type of file formats we want.
Prerequisites:
You should know how file uploading in multer works.
Installation of multer module:
Step 1: You can the multer by running the below command
npm i multer
Step 2: You can check the module version by running the below command.
npm version multer
Step 3: After that, you can just create a folder and add a file and run the created file by the below command.
node <filename>.js
Step 4: Requiring module: You need to include the multer module in your file by using these lines.
const multer = require('multer');
1. Restricting the user by fileSize:
Example: Multer provides us with a property called limits in which we can define the file size and
Node
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'src/');
},
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 * 1 } });
app.post('/upload', upload.single('file'), (req, res) => {
// Handle uploaded file
console.log(req.file);
res.send('File uploaded successfully');
});
app.use((err, req, res, next) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.send('File size is too large');
}
}
next(err);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
Output:
In the above code, we are restricting the user by specifying that the program will only take files which has a size less than or equal to the specified size.
In the above image, we are trying to upload an image that is greater than 1 MB so it is giving us an error.
2. Restricting by fileType
Example: The multer has a function called fileFilter which gives us access to file objects and then we can perform necessary operations in it.
JavaScript
// Requiring the multer module in our project
const multer = require('multer');
const upload = multer({
// dest is the destination where file will be stored
dest: 'src',
fileFilter(req, file, cb) {
// We are providing a regular expression
// which accepts only jpg,jpeg and png
if (!file.originalname.match(/\.(png|jpg|jpeg)$/)) {
return cb(new Error('Upload an image'));
}
cb(undefined, true);
}
})
Output:
In the above example, we are uploading a doc file but the multer is not accepting it as we are only accepting images.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
REST API Introduction REST API stands for REpresentational State Transfer API. It is a type of API (Application Programming Interface) that allows communication between different systems over the internet. REST APIs work by sending requests and receiving responses, typically in JSON format, between the client and server.
7 min read
Use Case Diagram - Unified Modeling Language (UML) A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read