Upload image to cloudinary using next js (App router)

Options
Devlanrey
Devlanrey Member Posts: 3
edited July 2023 in Developer APIs

I have been trying to upload an image from my next js app to cloudinary using App router version of next js. I will be really happy if someone can look into this for me.

Tagged:

Comments

  • CloudinarySam
    CloudinarySam Administrator, Cloudinary Staff Posts: 22
    edited March 12
    Options

    March 2024: This answer has been updated to use the Cloudinary Node SDK

    Hey @Devlanrey -I'd be happy to help you with uploading an image from your Next.js app to Cloudinary using the App router version of Next.js. Let's walk through the process step by step:

    1. First, ensure that you have the necessary credentials from Cloudinary, specifically your Cloud Name, API Key, and API Secret. You'll need these to authenticate your requests. https://cloudinary.com/documentation/cloudinary_credentials_tutorial

    2. Make sure you have the required dependencies installed for working with Cloudinary in your Next.js app. You can use the 'cloudinary' package to make the integration easier.  https://cloudinary.com/documentation/node_integration

    3. Within your Next.js app, create a file where you'll handle the image upload. This could be an API route or a regular serverless function, depending on your project setup. For this example, let's assume you're using an API route.

    4. Inside the API route file (e.g., `/pages/api/upload.js`), import the necessary modules and Cloudinary configuration.

    5. Implement the logic to handle the image upload. This would typically involve receiving the image from your frontend, using a form or some other method, and then sending it to Cloudinary using their SDK.

    Here's a simplified example of what the API route file might look like:

    ```javascript
    // /pages/api/upload.js
    
    import { v2 as cloudinary } from 'cloudinary';
    
    cloudinary.config({
     cloud_name: 'YOUR_CLOUD_NAME',
     api_key: 'YOUR_API_KEY',
     api_secret: 'YOUR_API_SECRET',
    });
    
    export default function handler(req, res) {
     if (req.method === 'POST') {
      const fileStr = req.body.image; // Assuming the image is sent as a base64 string from the frontend
    
      try {
       // Upload the image to Cloudinary
       const uploadResponse = await cloudinary.uploader.upload(fileStr, {
        upload_preset: 'YOUR_UPLOAD_PRESET', // Set this up in your Cloudinary settings
       });
    
       // Send the uploaded image URL back to the frontend
       res.status(200).json({ imageURL: uploadResponse.secure_url });
      } catch (error) {
       // Handle any errors that may occur during the upload process
       console.error('Error uploading image:', error);
       res.status(500).json({ error: 'Something went wrong during image upload' });
      }
     } else {
      res.status(405).end(); // Method Not Allowed
     }
    }
    ```
    

    Remember to replace `'YOUR_CLOUD_NAME'`, `'YOUR_API_KEY'`, `'YOUR_API_SECRET'`, and `'YOUR_UPLOAD_PRESET'` with your actual Cloudinary credentials.

    On the frontend side, you can make a POST request to this API route with the image data you want to upload. You can use the Fetch API, Axios, or any other library to perform the request.

    Please note that this is a basic example, and in a real-world application, you might need to add more error handling, validation, and security measures.

    If you encounter any specific issues during the implementation or have further questions, feel free to ask. Happy coding!

  • Devlanrey
    Devlanrey Member Posts: 3
    Options

    I have tried this method. And it gives an error of "method not allowed" handler

  • SreeCloudinary
    SreeCloudinary Member, Cloudinary Staff Posts: 28
    Options

    Hi @Devlanrey,

    Thanks for your response. "Method not allowed" is returned when your request does not have the proper verb(GET, POST, PUT etc). Can you please check what is the value of req.method when you are passing it to the function?

    Thanks

    Sree

  • Devlanrey
    Devlanrey Member Posts: 3
    Options

    It is a 'POST' method.