Getting Started with CldUploadWidget
The CldUploadWidget creates a new instance of the Cloudinary Upload Widget giving you an easy way to add upload capabilities to your Next.js app.
It works by using the Next.js Script component to load the external dependency and initialize the widget.
Basic Usage
The CldUploadWidget will not render any UI by default. It will instead only render what's returned from the child function (see more below).
There are two options when using the CldUploadWidget: signed and unsigned. These options allow you to control the amount of security and restrictions you place on uploads.
To learn more about signed and unsigned upload, check out the Cloudinary docs.
Unsigned
To give unsigned access for upload, provide an upload preset as part of the component configuration.
Note: The upload preset requires that unsigned uploads are permitted.
Use the following to generate an unsigned upload widget:
<CldUploadWidget uploadPreset="next-cloudinary-unsigned">
{({ open }) => {
function handleOnClick(e) {
e.preventDefault();
open();
}
return (
<button onClick={handleOnClick}>
Upload an Image
</button>
);
}}
</CldUploadWidget>
If using the Next.js 13 app
directory, you must add the use client;
directive at the top of your file.
Signed
Signing upload requests requires passing in an endpoint to the component.
You can do this by creating a serverless function that reads the parameters as the body and returns an object with the signature.
Use the following to generate an signed upload widget:
<CldUploadWidget signatureEndpoint="/api/sign-cloudinary-params">
{({ open }) => {
function handleOnClick(e) {
e.preventDefault();
open();
}
return (
<button onClick={handleOnClick}>
Upload an Image
</button>
);
}}
</CldUploadWidget>
If using the Next.js 13 app
directory, you must add the use client;
directive at the top of your file.
Here's an example of how you could process the signature in an API endpoint that signs a request:
const signature = cloudinary.utils.api_sign_request(body.paramsToSign, process.env.CLOUDINARY_API_SECRET);
res.status(200).json({
signature,
});
See a full example used with the Next Cloudinary docs: https://github.com/colbyfayock/next-cloudinary/blob/main/docs/pages/api/sign-cloudinary-params.js