"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Integrate Cloudinary in a Next.js application

Integrate Cloudinary in a Next.js application

Published on 2024-11-08
Browse:189

Integrate Cloudinary in a Next.js application

Read About Cloudinary and its pricing.

1. Create a Cloudinary Account

Sign up at Cloudinary and create a new account if you don't have one.

2. Install Cloudinary SDK

You can install the Cloudinary SDK using npm or yarn:

npm install cloudinary

3. Configure Cloudinary

You can create a configuration file to hold your Cloudinary credentials. It’s good practice to keep these in environment variables.

Create a .env.local file in your project root and add your Cloudinary credentials:

CLOUDINARY_URL=cloudinary://:@

4. Set Up Cloudinary in Your Application

// utils/cloudinary.js
import { v2 as cloudinary } from 'cloudinary';

cloudinary.config({
  cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET,
});

export const uploadImage = async (file) => {
  try {
    const result = await cloudinary.uploader.upload(file, {
      folder: 'your_folder_name', // optional
    });
    return result.secure_url; // Return the URL of the uploaded image
  } catch (error) {
    console.error('Cloudinary upload error:', error);
    throw new Error('Upload failed');
  }
};

5. Use the Upload Function

// pages/api/upload.js
import { uploadImage } from '../../utils/cloudinary';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { file } = req.body; // Assume you're sending a file in the body

    try {
      const url = await uploadImage(file);
      res.status(200).json({ url });
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

6. Upload from the Frontend

// components/ImageUpload.js
import { useState } from 'react';

const ImageUpload = () => {
  const [file, setFile] = useState(null);
  const [imageUrl, setImageUrl] = useState('');

  const handleFileChange = (event) => {
    setFile(event.target.files[0]);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    const formData = new FormData();
    formData.append('file', file);

    const res = await fetch('/api/upload', {
      method: 'POST',
      body: formData,
    });

    const data = await res.json();
    if (data.url) {
      setImageUrl(data.url);
    } else {
      console.error('Upload failed:', data.error);
    }
  };

  return (
    
{imageUrl && Uploaded}
); }; export default ImageUpload;

7. Test Your Setup

Run your Next.js application and test the image upload functionality.

Conclusion

You should now have a working integration of Cloudinary in your Next.js app! If you have any specific requirements or need further customization, feel free to ask!

Release Statement This article is reproduced at: https://dev.to/devops_den/integrate-cloudinary-in-a-nextjs-application-8op?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3