I have been trying to get access to an image I uploaded to Cloudinary and later made it restricted. The method I want to use is using it’s URL but for some reason no URL works and it’s documentation doesn’t mention how to get it using API key/Secret/token.
The URL will be in a React.JS img component (as will be in the code snippet).
so far I get 404 or 401 errors.
These are the code samples I use:
This is a function for the deployment server that supposed to get me the URL of the image.
const cloudinary = require("cloudinary").v2;
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
secure: true,
});
exports.handler = async (event, context) => {
try {
const { public_id } = JSON.parse(event.body || "{}");
const url = cloudinary.url(public_id, {
type: "authenticated",
sign_url: true,
transformation: [
{
width: 500,
height: 500,
crop: "fill",
gravity: "auto",
fetch_format: "auto",
quality: "auto",
},
],
});
return {
statusCode: 200,
body: JSON.stringify({ url }),
};
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify({ error: err.message }),
};
}
};
This is the code that create the img and return it:
import { AdvancedImage } from "@cloudinary/react";
import { useEffect, useState } from "react";
const SecureCloudinaryImage = () => {
const [imgUrl, setImgUrl] = useState("");
useEffect(() => {
try{
fetch("/.netlify/functions/<function_name_here>", {
method: "POST",
body: JSON.stringify({ public_id: "<img_name_goes_here>.jpg" }),
})
.then((res) => res.json())
.then((data) => setImgUrl(data.url));
}
catch(err){
console.log(err.message)
}
}, []);
if (!imgUrl) return <p>Loading...</p>;
return (
<>
{console.log("This is the url " + imgUrl)}
<img src={imgUrl} alt="Profile not found" />
</>);
};
export default SecureCloudinaryImage;
When I run this code the console.log("This is the url " + imgUrl)
shows the URL so I know that the URL isn’t empty.
I tried to remove the “.jpg” from the image name extension but got 401 error.
for refference this is the URL structure:
https://res.cloudinary.com/<cloud_name>/image/authenticated/<string_created_by_code>/c_fill,f_auto,g_auto,h_500,q_auto,w_500/<img_name_goes_here>.jpg?_a=BAMAK+ZU0
I tried going over Cloudinary documentation but couldn’t find any good suggestion for how to do it with restricted image.