Skip to content

How to Parse Media Files with Multer

This post will describe how to use Multer — a Node.js middleware used to handle multipart/form-data, and it makes the process of uploading files easy. We will be using it in a Next.js application where we will be leveraging one of its core features called API routes which allows us to write server-side logic within our Next.js applications.

We would first create an API route and write some logic that describes how Multer can be used to parse files. We will then upload the said file(s) to Cloudinary. To spice up things further, we will build a simple UI that will allow us to interact with our API and upload some files. Let’s get to it!

Here is a link to the demo CodeSandbox.

Create a Next.js app using the following command:

npx create-next-app my-project

Next, add the project dependencies using the following command:

npm install cloudinary multer axios

To use the services Cloudinary provides, you need to first sign up for a free Cloudinary account if you don’t have one already. Displayed on your account’s Management Console (aka Dashboard) are important details: your cloud name, API key, etc.

You will need your cloud name and API key to initialize the Cloudinary SDK and API secret to authenticate requests we will be making to the Cloudinary servers. Next, let’s create some environment variables to hold the Cloudinary details.

Create a file called .env at the root of the project with the content below:

CLOUD_NAME = YOUR CLOUD NAME HERE
API_KEY = YOUR API KEY HERE
API_SECRET = YOUR API SECRET HERE

This will be used as the default if you set up the project on another system. To update your local environment, create a copy of the .env file by running this command:

cp .env .env.local
Code language: CSS (css)

By default, this local file resides in the .gitignore folder, mitigating the security risk of inadvertently exposing secret credentials to the public. Be sure to update the .env.local file with your Cloudinary credentials.

Let’s create a file that will hold some helper functions. At the root of your project, create a file called helper.js and add this code to it:

const cloudinary = require("cloudinary").v2;
cloudinary.config({
  cloud_name: process.env.CLOUD_NAME,
  api_key: process.env.API_KEY,
  api_secret: process.env.API_SECRET,
});
export async function handleUpload(file) {
  const res = await cloudinary.uploader.upload(file, {
    resource_type: "auto",
  });
  return res;
}
Code language: JavaScript (javascript)

In this file, we start by bringing in the Cloudinary SDK, which we use to configure our credentials. The call to cloudinary.config() essentially authenticates requests we make to the Cloudinary servers. Next, we defined and exported a function called handleUpload that expects a file as input, uploads it to our account, and returns the response it gets.

API routes are just files that reside in the pages/api directory of our Next.js application that allow us to write some server-side logic to handle HTTP requests. In our case, we will need just one route. In your pages/api directory, create a file called upload.js.

We would incrementally update the logic of the upload.js file to define our request handler.

First, we would start by bringing the necessary imports — the Multer module and our handleUpload utility function.

import multer from "multer";
import { handleUpload } from "../../helpers";
Code language: JavaScript (javascript)

Next, we will set up the Multer middleware.

const storage = multer.memoryStorage();
const upload = multer({ storage });
const myUploadMiddleware = upload.single("sample_file");
Code language: JavaScript (javascript)

Multer provides us with two storage options: disk and memory storage. In the above snippet, we start by selecting the storage option we want for our Multer instance. We choose the memory storage option because we do not want to store parsed files on our server; instead, we want them temporarily stored on the RAM so that we can quickly upload them to Cloudinary.

Next, we created the Multer instance and initialized it with the storage option. Finally, since we expect only a single file when we use Multer, the call to upload.single() does just that for us; it is for uploading only a single file.

Next, let’s create a helper function that will allow us run our middleware. Add the following to your upload.js file:

function runMiddleware(req, res, fn) {
  return new Promise((resolve, reject) => {
    fn(req, res, (result) => {
      if (result instanceof Error) {
        return reject(result);
      }
      return resolve(result);
    });
  });
}
Code language: JavaScript (javascript)

The runMiddleware function accepts three parameters. The first two are the request and response objects, and the third is a callback function that will be some middleware. runMiddleware returns a promise that resolves successfully when the middleware callback runs successfully and fails with an error otherwise.

Now we have the necessary moving parts. Next, we need to define and export the main handler function. Update your upload.js file like so:

const handler = async (req, res) => {
  try {
    await runMiddleware(req, res, myUploadMiddleware);
    const b64 = Buffer.from(req.file.buffer).toString("base64");
    let dataURI = "data:" + req.file.mimetype + ";base64," + b64;
    const cldRes = await handleUpload(dataURI);
    res.json(cldRes);
  } catch (error) {
    console.log(error);
    res.send({
      message: error.message,
    });
  }
};
export default handler;
Code language: JavaScript (javascript)

In the above code, we define and export the main handler function that will be triggered by any HTTP request made to /api/upload. This function starts by parsing the files contained in the request body using the Multer middleware. If it succeeds, it attaches the parsed file data to the request object.

Next, we construct a data URI from the file object that holds the base64 encoded data representing the file. This data is fed to the handleUpload function we defined earlier, which uploads the file and returns the response stored in a variable called cldRes which is then attached to the response object sent back.

We are still missing one step. It will interest you to know that all API Route handler functions, by default, provide us with middleware under the hood that automatically parses the contents of the request body, cookies, and queries. This means that by default, we don’t consume the raw request body stream, and we need that because the Multer middleware is supposed to parse files contained in the raw, unadulterated request object. Thankfully, API routes also provide us with a config object that allows us to modify the settings to fit our needs.

Add the following to the end of the upload.js file:

export const config = {
  api: {
    bodyParser: false,
  },
};
Code language: JavaScript (javascript)

This disables body parsing and allows our handler function access to the raw stream of the request body.

We are now done with the Backend. Let’s build a simple UI to interact with it. Add the following to your pages/index.js file:

import { useState } from "react";
import axios from "axios";

export default function IndexPage() {
  const [loading, setLoading] = useState(false);
  const [res, setRes] = useState({});
  const [file, setFile] = useState(null);
  const handleSelectFile = (e) => setFile(e.target.files[0]);
  const uploadFile = async (e) => {
    setLoading(true);
    e.preventDefault();
    const data = new FormData();
    console.log(file);
    data.set("sample_file", file);
    try {
      const res = await axios.post("/api/upload", data);
      setRes(res.data);
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };
  return (
    <div className="App">
      <label htmlFor="file" className="btn-grey">
        {" "}
        select file
      </label>
      <input
        id="file"
        type="file"
        onChange={handleSelectFile}
        multiple={false}
      />
      {file && <p className="file_name">{file.name}</p>}
      <code>
        {Object.keys(res).map(
          (key) =>
            key && (
              <p className="output-item" key={key}>
                <span>{key}:</span>
                <span>
                  {typeof res[key] === "object" ? "object" : res[key]}
                </span>
              </p>
            )
        )}
      </code>
      {file && (
        <>
          <button className="btn-green" onClick={uploadFile}>
            {loading ? "uploading..." : "upload to Cloudinary"}
          </button>
        </>
      )}
    </div>
  );
}
Code language: PHP (php)

This component is relatively straightforward; it simply allows the user to select a file from their computer and provides them with a button to upload the file and display the result. The centerpiece of this component is the function we call uploadFile, which does the file uploading via the following steps:

  • It starts by using the FormData API to construct key-value pairs that represent the request payload. Since our payload is only the selected file, we define a key called sample_file with a value that points to the selected file. Notice that this key matches the one we defined when we earlier set up Multer on our API route. Multer only parses request payload that has an encoding of multipart/form-data, and by using the FormData API, this is automatically set for us in the request headers.
  • Next, it makes an HTTP request to our API route and passes the file as the payload. If the request succeeds, it stores the response in a state variable which is then iterated upon and rendered to the screen.

Start your application on http://localhost:3000/ with the following command:

    npm run dev

Once the app is up and running, you should be able to select a file, upload it and see the response displayed.

Find the complete project here on GitHub.

This tutorial walks you through using additional middleware within API routes. We saw how to parse files using Multer before uploading. Your API routes may require more logic to handle other specific concerns as your application grows in sophistication and requirements.

Back to top

Featured Post