Next Cloudinary

repository·main·Indexed 43 days ago

https://github.com/cloudinary-community/next-cloudinary

A high-performance library for Next.js providing optimized image delivery, AI-based transformations, and easy uploading via Cloudinary. Features include the CldImage component for dynamic cropping and background removal, CldOgImage for social media cards, and the CldUploadWidget for asset management.

Tokens
52.7K
Snippets
196
Records
222
Agent score
54%

What's inside Next Cloudinary

  1. Overview of Next Cloudinary features

    main

    Next Cloudinary provides high-performance image and video delivery and uploading for Next.js applications using Cloudinary. Key capabilities include:

    • Optimization: Automatically optimizes images and videos with responsive sizes and modern formats.
    • Transformations: Supports dynamic cropping, resizing, background removal, Generative AI, and more.
    • Uploading: Provides a drop-in widget for easy asset uploading to the cloud.
    • Social Cards: Simplifies the creation of dynamic social media (Open Graph) cards.
    • Advanced Delivery: Supports Adaptive Bitrate Streaming for video and various text/image overlays.
  2. Add Overlays and Underlays to images

    main

    Cloudinary allows you to add layers above (overlays) or below (underlays) your primary asset.

    • Overlays: Can be images, videos, or text. Use the overlays array to pass an array of layer objects.
    • Underlays: Layers placed behind the primary asset. Use the underlays array. Note that underlays do not support text.

    Common layer properties include publicId, position, effects, and text (for overlays only).

    // Adding an overlay with position and effects
    overlays: [{
      publicId: 'images/earth',
      position: {
        x: 50,
        y: 50,
        gravity: 'north_west',
      },
      appliedEffects: [
        {
          multiply: true
        }
      ]
    }]
    
    // Adding an underlay
    underlays: [{
      publicId: 'images/earth',
    }]
  3. Distinguish between Next.js 'fill' and Cloudinary 'crop="fill"'

    main

    When working with CldImage, it is important to distinguish between the Next.js layout behavior and the Cloudinary image transformation:

    1. Next.js fill prop: Setting fill or fill={true} opts the component into the Next.js Image fill mode. This uses CSS to make the image fill its parent container via the native <img> tag.
    2. Cloudinary crop="fill": Setting the crop prop to "fill" opts the component into the Cloudinary crop mode. This instructs Cloudinary to transform the actual image file by cropping it to fill the requested dimensions.
    // Uses Next.js CSS fill mode
    <CldImage fill src="my-public-id" alt="..." />
    
    // Uses Cloudinary server-side cropping
    <CldImage crop="fill" src="my-public-id" alt="..." width={600} height={600} />
  4. How CldUploadWidget events work

    main

    The CldUploadWidget provides two ways to handle lifecycle events (like upload completion, errors, or opening the widget): Callback Functions and Actions.

    • Callback Functions: Use these for standard client-side interactions. They receive both the results and an options object. The options object contains the widget instance and its instance methods.
    • Actions: Use these to support the Server Actions workflow. They are more restricted and only receive the results object, omitting the widget instance and methods.

    Choose Callback Functions when you need to interact with the widget instance directly, and Actions when you are working within a Server Actions context.

    // Example of a Callback Function (receives results and options)
    <CldUploadWidget
      onSuccess={(results, options) => {
        console.log('Success!', results.info);
        // 'options' contains the widget instance and methods
      }}
    />
    
    // Example of an Action (receives only results)
    <CldUploadWidget
      onSuccessAction={(results) => {
        console.log('Success via Action!', results.info);
      }}
    />
  5. Configure Image Size and Canvas for getCldOgImageUrl

    main

    By default, getCldOgImageUrl uses a two-step sizing process to maintain a consistent design canvas while providing an optimized final file size:

    1. Canvas Size: The default canvas is 2400x1254. You can design overlays and elements relative to this size.
    2. Final Size: The image is automatically resized down to 1200x627 to satisfy the 1.91:1 ratio required by platforms like LinkedIn and to avoid excessively large files.

    Customizing Dimensions

    • Use width and height to control the initial canvas size.
    • Use widthResize to change the final scale of the image.
    • The final height is automatically calculated based on the width and widthResize values to maintain the correct aspect ratio.
  6. Control image upscaling with crop mode

    main

    By default, CldImage uses the limit crop mode. This prevents Cloudinary from upscaling an image if the requested size is larger than the original dimensions, opting instead to let the browser handle the resizing. If you want Cloudinary to upscale the image (which may result in lower quality/blurriness for small originals), set the crop prop to scale.

    <CldImage
      width="960"
      height="600"
      src="<Your Public ID>"
      crop="scale"
      alt="Description"
    />
  7. How CldUploadWidget UI composition works

    main

    The CldUploadWidget does not render any UI by default. It uses the Function as a Child pattern to allow you to compose your own UI.

    You must pass a function as the direct child of the component. This function receives an object containing the cloudinary instance, the widget instance, various methods to control the widget (like open), and other relevant data.

    <CldUploadWidget>
      {({ cloudinary, widget, open }) => {
        // Your custom UI logic here
      }}
    </CldUploadWidget>
  8. Manage CldOgImage image formats

    main

    While Cloudinary's f_auto is standard for web, CldOgImage defaults to jpg for most use cases because social networks require fast initial encoding to recognize and load images on the first share. WebP and AVIF may lack broad support in some social crawlers.

    However, since Twitter supports WebP, you can customize the format using Twitter-specific tags to optimize for that platform.

  9. Implement a Signature API Endpoint for Signed Uploads

    main

    To support CldUploadWidget signed uploads, you must create a server-side endpoint that uses the Cloudinary Node SDK to sign the parameters sent by the widget.

    Prerequisites

    1. Install the Cloudinary Node SDK:
    npm install cloudinary
    1. Configure the following environment variables:
    • NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME
    • NEXT_PUBLIC_CLOUDINARY_API_KEY
    • CLOUDINARY_API_SECRET (Keep this secret; do not prefix with NEXT_PUBLIC_)

    Implementation

    Depending on your Next.js routing architecture, use one of the following implementations.

    npm install cloudinary
  10. Remove a background from an image with CldImage

    main

    You can remove the background from an image by adding the removeBackground boolean prop to the CldImage component.

    Note: This feature requires the Cloudinary AI Background Removal Add-On to be enabled on your Cloudinary account.

    import { CldImage } from 'next-cloudinary';
    
    <CldImage
      width="960"
      height="600"
      src="images/turtle"
      sizes="100vw"
      removeBackground
      alt="Turtle"
    />
  11. Add layers under images using the underlay option

    main

    You can place an image or layer behind your main subject using the underlay option. This is particularly useful when combined with removeBackground to place a subject (like an animal or person) into a new environment.

    Note: Underlays function similarly to overlays but do not support text.

    import { CldImage } from 'next-cloudinary';
    
    <CldImage
      width="960"
      height="600"
      src="images/turtle"
      sizes="100vw"
      removeBackground
      underlay="images/galaxy"
      alt="Turtle swimming in a galaxy"
    />