File Uploading in NextJs

File Uploading in NextJs

Uploading an image to Cloudinary in NextJs

NextJs is a react framework that enables server-side rendering, generating static websites, and many other features. NextJs has gained great popularity as a framework for building web applications. It has many features to solve common application requirements such as routing, data fetching, and integrations while handling the tooling and configuration needed in React. Forms have been an integral part of many web applications for collecting user data. In this tutorial, we would be learning how to perform file uploading in NextJs, which is how to upload an image using middleware in NextJs called next-connect and inbuilt react form object. Before we start with the task at hand, let's install our NextJs application and the necessary dependencies. To install NextJs, we would have to have Node installed in our system. Then use the create-next-app command to set up a NextJs project.

npx create-next-app@latest
#or 
yarn create next-app

We need to install some dependencies: Cloudinary SDK and multiparty.

npm install cloudinary --save

#for multiparty and next-connect
npm install next-connect multiparty

After installation, start up the development server using npm run dev or yarn dev and access the server on http://localhost:3000.

Inside index.js file will create a simple form with a file input and a submit button.

import {  useState } from 'react';
const Testpage = () => {
const [image, setImage] = useState(null);

const submitHandler = async (e) => {
    e.preventDefault()
      const form = new FormData()
      form.append('image', image)

const res = await fetch('/api', {
      method: "POST",
      body: form
    });
    const data = await res.json()
}

return(
<div>
      <input name='image' type='file' onChange={(e) => setImage(e.target.files[0])} />
      <button type='button' onClick={(e) => submitHandler(e)}>Submit</button>
</div>
)
}
export default TestPage;

Now, let's our middleware using next-connect: middleware/upload.js

import nextConnect from 'next-connect';
import multiparty from 'multiparty';

const middleware = nextConnect()

middleware.use( (req, res, next) => {
    const form = new multiparty.Form()

     form.parse(req, (err, fields, files) => {
         if(err){
             console.log(err)
         }
        req.body = fields
        req.files = files
        next()
    })
})

export default middleware;

We had to create a configuration file for our Cloudinary for authentication. ../config/cloudinary.

const cloudinary = require('cloudinary').v2;
cloudinary.config({
  cloud_name: 'your_cloudinary_name',
  api_key: "your_api_key",
  api_secret: 'your_api_secret',
});

module.exports = cloudinary;

The values can be found in your cloudinary console dashboard on their website. It is preferable to save them in a .env file and read them as environmental variables.

Writing our API endpoint: /api/index.js

import middleware from "../middleware/upload";
import nextConnect from "next-connect";
import cloudinary from "../config/cloudinary";

const handler = nextConnect() 
handler.use(middleware)

handler.post(async (req,res) => {

  try{
      let filePath = req.files.image[0].path;
      const result = await cloudinary.uploader.upload(filePath);

      res.status(200).send(result);
   }
   catch(err){
   console.log(err)
   }

})

export const config = {
  api: {
     bodyParser : false
  }
}
export default handler

The result object returned will have a secure_url property which will serve as the URL location of the Image and for storage or rendering purposes.

That's it folks, hope this tutorial really helped to understanding how to use Cloudinary SDK and how to upload files in NextJs.

Happy coding👍👍..

Thanks for reading😉😉...