Middleware Magic: Getting Image URLs with Multer and Cloudinary in Node.js

Tushar Chavan
4 min readMar 4, 2023

--

Here we move hey I’m back again!, In my previous posts, I’ve written about topic Exploring Custom Hooks in React and Creating a Reusable Modal Component in React . Today, I,m excited to talk about how middle ware work in node js and showcasing an example how use middleware in order get image url sent to our node server. We will be discussing how to set up multer and cloudinary to achieve our goal.So without any delay, let’s get started!

Node.js middleware are functions that have access to the request and response objects in an HTTP request. They can execute any code, perform authentication, validation, logging, and more before sending a response back to the client. Middleware functions can be chained together to create a pipeline for handling requests. Middleware is a fundamental concept in Node.js web development and is used extensively in frameworks like Express.js.

The following blog post assumes familiarity with setting up and running a basic Node.js application. It focuses on the use of middleware for getting image URLs using Multer and Cloudinary.

So, once you finish the initial setup of node js and up listening to the requests on your desired port.We must first have to install some dependencies so that we can continue.

npm i multer cloudinary datauri@2.0.0

The above command installs the cloudinary,multer and datauri npm packages check package.json for confirmation 😅️.

intial setup

This is my initial setup for app.js . In your src folder create a folder and name it middleware and create two files with names multer.js and cloudinary.js .

multer.js

This code is used to set up a middleware for uploading image files in Node.js using Multer. Multer is a middleware for handling multipart/form-data, which is primarily used for uploading files. The multerUpload function is an instance of the Multer middleware, which sets the options for the upload process.

In this code, the options are set to limit the file size to 2MB and filter files to only allow files with the .png extension. If a file does not match the required criteria, an error message is returned, otherwise, the file is accepted and passed to the next middleware.

cloudinary.js

This code sets up the cloudinary configuration for uploading and retrieving images. The getUrl function extracts image data from the req object and uploads it to cloudinary. It then sets the secure_url property of the response to the req.imgURI property for use in subsequent middleware or routes. The DataURI library is used to convert the file buffer to a base64-encoded URI format for upload to cloudinary. The req.file object is validated to ensure it is a .png file before proceeding with the upload.

Note: You have to login to cloudinary and get your api and secret key and set up those key in your environment and then proceed further

app.js

This is a route for handling a POST request to upload an image to the server. The route has three middleware functions, which are executed sequentially. The first middleware function is multerUpload.single("imgUrl"), which handles the file upload using multer. The single method specifies that only one file with the name "imgUrl" can be uploaded. The second middleware function is geturl, which is responsible for uploading the image to Cloudinary and getting the URL of the uploaded image. The third middleware function is the route handler function that receives the req and res objects. It retrieves the image URL from req.imgURI, which was set by the geturl middleware function. If the URL is not found, it returns a 404 response. Otherwise, it sends a 201 response with the URL in the response body. Finally, there is an error handling middleware function that is executed if any of the previous middleware functions throw an error.

Here i am sending the url of image uploaded to cloudinary back to client you can also store the url to your desired database and then send the response

conclusion

In conclusion, using Multer and Cloudinary together provides a powerful solution for handling file uploads in a Node.js application. With Multer, we can easily set up file size limits and filters for accepted file types, while Cloudinary offers an efficient way to store and manage image assets. The multerUpload middleware function and getUrl function work together to handle the file upload and URL retrieval processes seamlessly. By implementing these techniques, we can create a robust and scalable application with minimal hassle.

I hope this blog post has been informative and helpful for those familiar with Node.js initial setup 😅️. Thank you for reading, and I will be back next Sunday with another exciting topic!

--

--

Tushar Chavan

👩‍💻Software engineer specializing in MERN and various tech📚.Sharing coding insights, experiences,and best practices. https://www.buymeacoffee.com/tusharchav7