Next.js Image Loader and Component

Optimize images with Uploadcare on the fly by using the UploadcareImage component or the uploadcareLoader custom image loader for Next.js.

The built-in Next.js Image component does a great job in optimizing images but the number of optimizations is limited. It allows setting a custom image loader to process images externally. This is where the @uploadcare/nextjs-loader package comes in handy.

GitHub

Here is a demo app and its source code.

Features

  • Optimize image characteristics (quality, resolution, format, and others) with extended list of Uploadcare image transformations.
  • Load the optimized images through the Uploadcare CDN network.

Installation

yarn add @uploadcare/nextjs-loader

Configuration

Step 1

Get your public key from the dashboard and add it to your environment variables through .env file or your hosting UI.

# .env
NEXT_PUBLIC_UPLOADCARE_PUBLIC_KEY="YOUR_PUBLIC_KEY"

Don’t forget to set your app base URL, which is necessary to process local images properly.

# .env
NEXT_PUBLIC_UPLOADCARE_APP_BASE_URL="https://your-domain.com/"

Find additional settings, such as image transformation settings, custom CDN domain, and custom proxy domain, in the developer documentation on Github.

Step 2

Allow custom image loaders through next.config.js:

// next.config.js
module.exports = {
  images: {
    loader: "custom"
  }
}

You’re all set now.

Usage

The easiest and the most straightforward way of utilizing the power of Uploadcare is to use the UploadcareImage component for all images on your site the same way as the built-in Image component.

import UploadcareImage from '@uploadcare/nextjs-loader';

<UploadcareImage
  alt="A test image"
  src="https://your-domain/image.jpg"
  width="400"
  height="300"
  quality="80"
/>

If you still need to use the built-in Image component with the uploadcareLoader:

import Image from 'next/image';
import { uploadcareLoader } from '@uploadcare/nextjs-loader';

<Image 
  alt="A test image"
  src="https://your-domain/image.jpg"
  width="400"
  height="300"
  quality="80"
  loader={uploadcareLoader}
/>

Note that if you pass a local image URL, the loader returns it AS IS if the app is run in the development mode or if the NEXT_PUBLIC_UPLOADCARE_APP_BASE_URL is not set.

Full documentation

Read the full documentation on GitHub.