Gathering detailed insights and metrics for @api-buddy/cloudinary
Gathering detailed insights and metrics for @api-buddy/cloudinary
Gathering detailed insights and metrics for @api-buddy/cloudinary
Gathering detailed insights and metrics for @api-buddy/cloudinary
npm install @api-buddy/cloudinary
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
2
4
A comprehensive Cloudinary integration for Next.js applications, providing a simple and type-safe way to upload, transform, and deliver images and videos.
1# Using npm 2npm install @api-buddy/cloudinary cloudinary 3 4# Using yarn 5yarn add @api-buddy/cloudinary cloudinary 6 7# Using pnpm 8pnpm add @api-buddy/cloudinary cloudinary
If you're using TypeScript, you'll also want to install the Cloudinary types:
1npm install --save-dev @types/cloudinary
Create a .env.local
file in your project root and add your Cloudinary credentials:
1NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME=your_cloud_name 2NEXT_PUBLIC_CLOUDINARY_API_KEY=your_api_key 3CLOUDINARY_API_SECRET=your_api_secret 4NEXT_PUBLIC_CLOUDINARY_UPLOAD_PRESET=your_upload_preset
Wrap your application with the CloudinaryProvider
in your root layout:
1// app/layout.tsx 2'use client'; 3 4import { CloudinaryProvider } from '@api-buddy/cloudinary'; 5 6export default function RootLayout({ 7 children, 8}: { 9 children: React.ReactNode; 10}) { 11 return ( 12 <html lang="en"> 13 <body> 14 <CloudinaryProvider 15 config={{ 16 // Optional: Configure default settings here 17 cloudName: process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME, 18 apiKey: process.env.NEXT_PUBLIC_CLOUDINARY_API_KEY, 19 apiSecret: process.env.CLOUDINARY_API_SECRET, 20 uploadPreset: process.env.NEXT_PUBLIC_CLOUDINARY_UPLOAD_PRESET, 21 }} 22 > 23 {children} 24 </CloudinaryProvider> 25 </body> 26 </html> 27 ); 28}
Create an API route to handle file uploads:
1// app/api/upload/route.ts 2import { NextResponse } from 'next/server'; 3import { upload } from '@api-buddy/cloudinary'; 4 5export async function POST(request: Request) { 6 try { 7 const formData = await request.formData(); 8 const file = formData.get('file') as File; 9 10 if (!file) { 11 return NextResponse.json( 12 { success: false, error: 'No file provided' }, 13 { status: 400 } 14 ); 15 } 16 17 // Convert the file to a buffer 18 const buffer = Buffer.from(await file.arrayBuffer()); 19 20 // Upload to Cloudinary 21 const result = await upload(buffer, { 22 folder: 'uploads', 23 resourceType: 'auto', 24 public_id: file.name.replace(/\.[^/.]+$/, ''), // Remove file extension 25 filename_override: file.name, 26 context: { 27 filename: file.name, 28 format: file.type, 29 size: file.size, 30 }, 31 }); 32 33 return NextResponse.json({ success: true, data: result }); 34 } catch (error) { 35 console.error('Upload error:', error); 36 return NextResponse.json( 37 { success: false, error: 'Failed to upload file' }, 38 { status: 500 } 39 ); 40 } 41}
1'use client'; 2 3import { useCloudinaryUpload } from '@api-buddy/cloudinary'; 4 5export default function UploadForm() { 6 const { uploadFile, isUploading, progress, error } = useCloudinaryUpload({ 7 options: { 8 folder: 'images', 9 resourceType: 'image', 10 }, 11 onSuccess: (result) => { 12 console.log('Upload successful:', result); 13 }, 14 onError: (error) => { 15 console.error('Upload error:', error); 16 }, 17 }); 18 19 const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => { 20 const file = e.target.files?.[0]; 21 if (file) { 22 await uploadFile(file); 23 } 24 }; 25 26 return ( 27 <div className="p-6 max-w-md mx-auto bg-white rounded-xl shadow-md"> 28 <h2 className="text-xl font-semibold mb-4">Upload an Image</h2> 29 30 <div className="mb-4"> 31 <input 32 type="file" 33 accept="image/*" 34 onChange={handleFileChange} 35 disabled={isUploading} 36 className="block w-full text-sm text-gray-500 37 file:mr-4 file:py-2 file:px-4 38 file:rounded-md file:border-0 39 file:text-sm file:font-semibold 40 file:bg-blue-50 file:text-blue-700 41 hover:file:bg-blue-100" 42 /> 43 </div> 44 45 {isUploading && ( 46 <div className="w-full bg-gray-200 rounded-full h-2.5"> 47 <div 48 className="bg-blue-600 h-2.5 rounded-full" 49 style={{ width: `${progress}%` }} 50 ></div> 51 <p className="text-sm text-gray-600 mt-1">Uploading: {progress}%</p> 52 </div> 53 )} 54 55 {error && ( 56 <div className="mt-4 p-3 bg-red-100 text-red-700 rounded-md"> 57 Error: {error.message} 58 </div> 59 )} 60 </div> 61 ); 62}
1import { CloudinaryImage } from '@api-buddy/cloudinary'; 2 3export default function ProfileImage({ publicId }: { publicId: string }) { 4 return ( 5 <div className="w-32 h-32 rounded-full overflow-hidden"> 6 <CloudinaryImage 7 publicId={publicId} 8 alt="Profile image" 9 width={128} 10 height={128} 11 className="w-full h-full object-cover" 12 transformation={[ 13 { width: 256, height: 256, crop: 'thumb', gravity: 'face' }, 14 { radius: 'max' }, 15 ]} 16 /> 17 </div> 18 ); 19}
For a quick setup, use the included CLI:
1npx @api-buddy/cloudinary setup
This will:
CloudinaryProvider
A context provider that makes the Cloudinary client available throughout your application.
config
: Configuration object
cloudName
: Your Cloudinary cloud name (required)apiKey
: Your Cloudinary API key (optional, defaults to process.env.NEXT_PUBLIC_CLOUDINARY_API_KEY
)apiSecret
: Your Cloudinary API secret (optional, defaults to process.env.CLOUDINARY_API_SECRET
)uploadPreset
: Your Cloudinary upload preset (optional)defaultUploadOptions
: Default options for all uploadsuseCloudinary()
A hook to access the Cloudinary client from the nearest CloudinaryProvider
.
client
: The Cloudinary client instanceconfig
: The current Cloudinary configurationuseCloudinaryUpload(options)
A hook for handling file uploads to Cloudinary.
options
: Upload options
options
: Default upload options for all uploadsonSuccess
: Callback when an upload succeedsonError
: Callback when an upload failsonProgress
: Callback with upload progress (0-100)uploadFile
: Function to upload a single fileuploadFiles
: Function to upload multiple filesisUploading
: Boolean indicating if an upload is in progressprogress
: Current upload progress (0-100)error
: Error object if an upload failedreset
: Function to reset the hook stateCloudinaryImage
A React component for displaying Cloudinary images with automatic optimization.
publicId
: The public ID of the image (required)alt
: Alternative text for the image (required)width
: Width of the imageheight
: Height of the imageclassName
: CSS class namestyle
: Inline stylesloading
: Loading behavior (lazy
or eager
)transformation
: Array of Cloudinary transformationsformat
: Image format to convert toquality
: Image quality (1-100)responsive
: Whether to generate responsive imagessizes
: Sizes attribute for responsive imagessrcSet
: Custom srcset for responsive imagesonLoad
: Callback when the image loadsonError
: Callback when the image fails to loadCloudinaryVideo
A React component for displaying Cloudinary videos.
publicId
: The public ID of the video (required)width
: Width of the video playerheight
: Height of the video playerclassName
: CSS class namestyle
: Inline stylesautoPlay
: Whether to autoplay the videoloop
: Whether to loop the videomuted
: Whether to mute the videocontrols
: Whether to show video controlsposter
: URL of the poster imagetransformation
: Array of Cloudinary transformationsonPlay
: Callback when the video starts playingonPause
: Callback when the video is pausedonEnded
: Callback when the video endsonError
: Callback when the video fails to loadupload(file, options)
Upload a file to Cloudinary.
file
: File to upload (Buffer, ReadStream, or base64 string)options
: Upload options (see Cloudinary documentation)A promise that resolves to the upload result.
deleteFile(publicId, options)
Delete a file from Cloudinary.
publicId
: The public ID of the file to deleteoptions
: Delete options
resourceType
: Type of resource (image
, video
, raw
, or auto
)type
: The type of the resourceinvalidate
: Whether to invalidate the CDN cacheA promise that resolves to the delete result.
getUrl(publicId, options)
Generate a URL for a Cloudinary resource.
publicId
: The public ID of the resourceoptions
: URL and transformation options
transformation
: Array of Cloudinary transformationsresourceType
: Type of resource (image
, video
, raw
, or auto
)type
: The type of the resourceformat
: Format to convert the resource tosecure
: Whether to use HTTPSsignUrl
: Whether to sign the URLversion
: The version of the resourceThe generated URL as a string.
1import { upload } from '@api-buddy/cloudinary'; 2 3// In an API route or server component 4const file = // your file buffer or stream 5const result = await upload(file, { 6 folder: 'uploads', 7 resourceType: 'auto', 8 public_id: 'my-file', 9}); 10 11console.log('File uploaded:', result.url);
1import { CloudinaryImage } from '@api-buddy/cloudinary'; 2 3function ProductImage({ publicId }: { publicId: string }) { 4 return ( 5 <CloudinaryImage 6 publicId={publicId} 7 alt="Product image" 8 width={400} 9 height={400} 10 transformation={[ 11 { width: 800, height: 800, crop: 'fill' }, 12 { effect: 'sharpen' }, 13 { quality: 'auto' }, 14 ]} 15 /> 16 ); 17}
1import { CloudinaryImage } from '@api-buddy/cloudinary'; 2 3function HeroImage({ publicId }: { publicId: string }) { 4 return ( 5 <CloudinaryImage 6 publicId={publicId} 7 alt="Hero image" 8 width={1200} 9 height={630} 10 className="w-full h-auto" 11 responsive 12 sizes="(max-width: 768px) 100vw, 50vw" 13 transformation={[ 14 { width: 1200, height: 630, crop: 'fill' }, 15 { quality: 'auto' }, 16 ]} 17 /> 18 ); 19}
All functions throw a CloudinaryError
when something goes wrong. You can catch and handle these errors:
1try { 2 await upload(file, options); 3} catch (error) { 4 if (error.name === 'CloudinaryError') { 5 console.error('Cloudinary error:', error.message); 6 // Handle specific error cases 7 if (error.code === 'LIMIT_FILE_SIZE') { 8 // Handle file size limit exceeded 9 } else if (error.code === 'UNAUTHORIZED') { 10 // Handle authentication error 11 } else { 12 // Handle other errors 13 } 14 } else { 15 // Handle non-Cloudinary errors 16 console.error('Unexpected error:', error); 17 } 18}
Contributions are welcome! Please open an issue or submit a pull request.
MIT
No vulnerabilities found.
No security vulnerabilities found.