I can't delete upladed image using it's public_id from react vite app.

Options
mikiyasegaye
mikiyasegaye Member Posts: 1

I have react vite app and I wanted to delete an image by passing public_id, but I couldn't make it work. My upload code works fine, but not the delete one. Please review my code and I needed your assistance.

export async function uploadFile( profilePicture: File): Promise<{ images_url: string; images_public_id: string }> { const formData = new FormData(); formData.append("file", profilePicture); formData.append( "upload_preset", import.meta.env.VITE_CLOUDINARY_UPLOAD_PERSIST ); formData.append("folder", import.meta.env.VITE_CLOUDINARY_UPLOAD_PATH);
try { const response = await fetch( `https://api.cloudinary.com/v1_1/${ import.meta.env.VITE_CLOUDINARY_CLOUD_NAME }/image/upload`, { method: "POST", body: formData, } );
const data = await response.json(); const images_url = data.secure_url; const images_public_id = data.public_id;
return { images_url, images_public_id }; } catch (error) { console.error("Error uploading file:", error); throw error; }}
export async function deleteFile(publicId: string): Promise<void> { const formData = new FormData(); formData.append("public_id", publicId);
console.log( "consoleData_ ~ file: uploadFile.ts:94 ~ deleteFile ~ formData:", formData );
try { const response = await fetch( `https://api.cloudinary.com/v1_1/${ import.meta.env.VITE_CLOUDINARY_CLOUD_NAME }/image/destroy`, { method: "POST", body: formData, headers: { Authorization: `Bearer ${import.meta.env.VITE_CLOUDINARY_API_SECRET}`, }, } );
const data = await response.json();
console.log( "consoleData_ ~ file: uploadFile.ts:61 ~ deleteFile ~ data:", data ); if (data.result !== "ok") { throw new Error("Failed to delete image"); } console.log("Image deleted successfully"); } catch (error) { console.error("Error deleting file:", error); throw error; }}

Tagged:

Answers

  • DannyFromCloudinary
    DannyFromCloudinary Member, Cloudinary Staff Posts: 102
    Options

    Hi @mikiyasegaye.

    For security reasons, we don't allow operations sent from the frontend that require you to send your API credentials in plain-text. I see you're using Bearer ${import.meta.env.VITE_CLOUDINARY_API_SECRET}, so this is likely the reason your request is failing.

    If you expose your API secret on the frontend, anyone who gets hold of it can authenticate as you and cause all kinds of damage to your account. I would strongly recommend going into Settings > Access keys and creating a new API secret, decommissioning your old one.

    In terms of how to perform a delete from the frontend, the best approach is to pass the request to a backend script that takes care of the authentication, away from the prying eyes of the general public. This could be by generating a signature for the request manually, or by using one of our backend SDKs.

    I hope this helps. Please let me know if you have any questions.

    Kind regards,

    -Danny