How to add authentication in file uploads using Node.js ? Last Updated : 01 Aug, 2024 Comments Improve Suggest changes Like Article Like Report 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 commandnpm i multerStep 2: You can check the module version by running the below command.npm version multerStep 3: After that, you can just create a folder and add a file and run the created file by the below command.node <filename>.jsStep 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 fileTypeExample: 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. Comment More infoAdvertise with us Next Article How to add authentication in file uploads using Node.js ? ankit1210 Follow Improve Article Tags : Web Technologies Node.js Geeks Premier League Geeks-Premier-League-2022 NodeJS-Questions Similar Reads How to check user authentication in GET method using Node.js ? There are so many authentication methods like web token authentication, cookies based authentication, and many more. In this article, we will discuss one of the simplest authentication methods using express.js during handling clients get a request in node.js with the help of the HTTP headers. Appro 3 min read Google Authentication using Passport in Node.js The following approach covers how to authenticate with google using passport in nodeJs. Authentication is basically the verification of users before granting them access to the website or services. Authentication which is done using a Google account is called Google Authentication. We can do Google 2 min read How to Add Data in JSON File using Node.js ? JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article.Prerequisites:NPM NodeApproachTo add data in JSON file using the node js 4 min read Adding User Authentication in Next.js using Auth0 Auth0 is a flexible, drop-in solution to add authentication and authorization services to your applications. Integrating Auth0 with Next.js allows you to manage user authentication seamlessly. In this article, we will learn How we can add user authentication in our NextJS project using Auth0.Approac 3 min read Basic Authentication in Node.js using HTTP Header Basic Authentication is a simple authentication method where the client sends a username and password encoded in base64 format in the HTTP request header.The basic authentication in the Node.js application can be done with the help express.js framework. Express.js framework is mainly used in Node.js 3 min read How to Upload File using formidable module in Node.js ? A formidable module is used for parsing form data, especially file uploads. It is easy to use and integrate into your project for handling incoming form data and file uploads.ApproachTo upload file using the formidable module in node we will first install formidable. Then create an HTTP server to ac 2 min read How to handle file upload in Node.js ? File upload can easily be done by using Formidable. Formidable is a module that we can install on our project directory by typing the commandnpm install formidableApproach: We have to set up a server using the HTTPS module, make a form that is used to upload files, save the uploaded file into a temp 3 min read How to Upload File and JSON Data in Postman? Postman is a very famous API development tool used to test APIs. Postman simplifies the process of the API lifecycle to create and test better APIs. Now, while we are working with APIs sometimes we need to send JSON as data or upload a file through API. There may be a scenario where we have to do bo 4 min read Node.js authentication using Passportjs and passport-local-mongoose Passport is the authentication middleware for Node. It is designed to serve a singular purpose which is to authenticate requests. It is not practical to store user password as the original string in the database but it is a good practice to hash the password and then store them into the database. Bu 5 min read How to Download a File Using Node.js? Downloading files from the internet is a common task in many Node.js applications, whether it's fetching images, videos, documents, or any other type of file. In this article, we'll explore various methods for downloading files using Node.js, ranging from built-in modules to external libraries.Using 3 min read Like