Home/Blog/Image optimization for Next.js applications

Image optimization for Next.js applications

Inย this article, weย will explore various methods ofย optimizing images inย Next.js applications, asย well asย the benefits ofย using Uploadcareโ€™s Next.js image loader and component over other solutions.

Next.js Image component

Next.js offers aย built-in image component that extends the regular <img> element toย help you optimize images on-demand when images are being served toย your users. The Next.js Image component isย designed toย improve the performance ofย your website byย automatically optimizing images and serving them inย the most efficient way possible.

This image component creates aย list of srcset ofย image sizes and automatically selects the appropriate size for users based onย their current browser viewport width.

Next.js Image component renders image with srcsetNext.js Image component renders image with srcset

Using Vercelโ€™s Image Optimization API, the Image component generates different image sizes and formats toย serve toย users. The API also caches images generated byย and serve them via Vercelโ€™s CDN soย your users can quickly access them.

Byย default, for every new Next.js application created, the Next.js image component isย installed. Toย use itย inย your application, import itย into your component using the code:

import Image from 'next/image';

You can then use inย your components:

<Image
  src={image}
  alt="nature image"
  width={800}
  height={600}
/>

Features ofย Next.js Image component

Some key features ofย the Image component byย Next.js include:

Automatic Image Optimization

  • The image component automatically generates different versions for different device screen sizes and pixel ratios.

  • Next.js image component serves images inย modern formats like WebP orย AVIF when supported byย the browser, ensuring efficient delivery and reduced file sizes.

Next.js Image component serves images inย modern formatsNext.js Image component serves images inย modern formats

Lazy Loading

The component supports lazy loading ofย images and loads images only when they enter the viewport, thereby reducing initial page load time.

Toย use this feature, set the loading props toย beย lazy:

<Image
  loading="lazy"
  src={image}
  alt="nature image"
  width={800}
  height={600}
/>

Priority Loading

Priority loading isย aย feature that ensures critical images are loaded asย soon asย possible toย improve your web pageโ€™s Largest Contentful Paint (LCP) and overall page performance. This isย particularly useful for images visible above the fold when aย page first loads.

The priority attribute can beย added toย the Image component. Images with priority are preloaded, meaning they are fetched earlier than other images, ensuring faster rendering.

Toย prioritize aย specific image onย aย page, add the priority props toย the component:

<Image
  src={img}
  alt="nature image"
  priority
  width={800}
  height={600}
/>

For aย complete list ofย the features and customization options available with the Next.js Image component, visit the official Next.js image optimization documentation.

Tips and best practices for image optimization when using Next.js image component

When using the Next.js image component, consider the following tips and best practices toย ensure optimal performance and user experience:

  • Use alt props: Always include descriptive alt text for images. This improves accessibility for screen readers and enhances SEO byย providing context toย search engines.

  • Specify height and width for remote images: Defining explicit height and width attributes helps Next.js calculate aspect ratios, preventing Cumulative Layout Shifts (CLS) and improving performance.

  • Use the priority prop for high-priority images: Apply the priority attribute toย critical images that should load first. This ensures essential visuals are displayed quickly, improving user experience and Largest Contentful Paint (LCP).

  • Use static imports for local images: Importing local images statically allows Next.js toย optimize them automatically during build time, resulting inย smaller file sizes and faster load times.

Uploadcare Next.js loader for images inย Next.js applications

Uploadcare enhances the image experience inย your Next.js applications byย providing aย robust image optimization solution that can beย used inย any Next.js application, nextjs-loader.

The component uses Uploadcareโ€™s optimization and transformation API toย optimize images inย your Next.js application. Then itย caches these images inย the Uploadcare CDN toย enableย us toย serve these images toย your users asย fast asย possible.

The nextjs-loader library provides an UploadcareImage component that functions identical toย the Next.js Image component but with some extra optimization features.

The UploadcareImage component also supports all the props available inย the Next.js Image component, such as src, alt, width, height, priority, etc.

Toย use the component and loader, install itย inย your application with the command:

npm install @uploadcare/nextjs-loader

Update the next.config.mjs file toย load images from the Uploadcare CDN:

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'ucarecdn.com',
        port: '',
        pathname: '/**',
      },
    ],
  },
};

export default nextConfig;

Next, create a .env.local file and add your Public key from your Uploadcare project dashboard:

#.env.local
NEXT_PUBLIC_UPLOADCARE_PUBLIC_KEY="YOUR_PUBLIC_KEY"

The image component also supports transformation operations provided byย the Uploadcare operations API that can beย used toย load better-optimized images.

Toย use these transformations, update your env.local file with the values:

#.env.local
NEXT_PUBLIC_UPLOADCARE_TRANSFORMATION_PARAMETERS="format/auto, stretch/off, progressive/yes, quality/lightest"

Where:

  • format: isย the format ofย the image toย beย served. This could beย specified as jpeg, png, or webp image format; when set toย auto, the image component determines the best image format toย serve based onย what image format aย client browser supports.

  • progressive: tells Uploadcare toย load jpeg images inย aย progressive manner, which improves the loading experience byย displaying aย lower-quality version ofย the image initially, and gradually enhancing itย asย more data isย downloaded.

  • quality: tells Uploadcare toย optimize the image toย the smallest file size possible with the highest compression ratio while maintaining acceptable quality. This results inย approximatelyย 50% ofย the original file size.

Check out the transformation documentation for aย list ofย transformation operations you can apply toย images.

Toย use the UploadcareImage inย your component, import the UploadcareImage component and render with the src value asย the URL ofย your image:

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

<UploadcareImage
  alt="A test image"
  src="https://6ca2u7ybx5.ucarecd.net/bd5547b4-578a-4c53-8bf1-5cb43f5d4d30/img.jpg"
  width="800"
  height="500"
/>
UploadcareImage rendering an optimized imageUploadcareImage rendering an optimized image

The nextjs-loader library also provides aย loader that can beย used along with the Next.js Image component. This loader can beย used toย load images from the Uploadcare CDN and apply transformations toย images onย the fly.

Toย use the loader, update your next.config.mjs file toย use the loader from the nextjs-loader library:

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    // previous image configurations
    loader: 'custom',
  },
};

export default nextConfig;

You can now import the Uploadcare image loader from nextjs-loader toย use inย your Image components:

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

<Image
  src="https://6ca2u7ybx5.ucarecd.net/bd5547b4-578a-4c53-8bf1-5cb43f5d4d30/img.jpg"
  alt="Nature Image"
  width={800}
  height={500}
  loader={uploadcareLoader}
/>

Ifย youโ€™d like toย use uploadcareLoader toย optimize all images inย your Next.js application, update next.config.mjs toย load the uploadcareLoader asย aย loader file:

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    // previous image configurations
    loader: 'custom',
    loaderFile: './node_modules/@uploadcare/nextjs-loader/build/loader.js',
  },
};

export default nextConfig;

You can now use the Next.js Image component without specifying loader props, and Uploadcare will handle all image optimization for you:

<Image
  src="https://6ca2u7ybx5.ucarecd.net/bd5547b4-578a-4c53-8bf1-5cb43f5d4d30/img.jpg"
  alt="Nature Image"
  width={800}
  height={500}
/>

For images not uploaded toย Uploadcare servers, such asย local images, the nextjs-loader library optimizes such images via aย proxy. Toย use the proxy, update your env.local file toย include your applicationโ€™s URL asย the base URL for the proxy:

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

Inย your Project -> Settings -> Delivery, add your domain URL toย the list ofย allowed domains for proxy.

Uploadcare Proxy settingsUploadcare Proxy settings

You can now use the UploadcareImage component with local images onย your website:

<UploadcareImage
  src={img}
  alt="Nature Image"
  width={800}
  height={500}
/>

Note: Local images inย development will not beย optimized but will beย served asย they are; however, when your project isย deployed toย aย different environment, Uploadcare CDN will optimize all images via proxy.

Benefits ofย using Uploadcare image component and loader

  • Uploadcare transformations: Using the UploadcareImage component, you can apply different transformation operations like resizing, cropping, and format conversion. These transformations are applied onย the fly, ensuring images are optimized for any use case without manual intervention.

  • Responsive images: The UploadcareImage component automatically generates images tailored toย different devices and screen sizes. This ensures the best quality and performance byย delivering the optimal image for each userโ€™s device.

  • Uploadcare CDN for fast delivery: The component leverages Uploadcareโ€™s global CDN toย deliver images quickly and efficiently. This minimizes latency and ensures fast load times for users worldwide, improving overall user experience.

  • Proxy images: Utilize Uploadcareโ€™s proxy functionality toย serve external images seamlessly. This feature fetches images from any URL and applies optimizations such asย resizing and real-time format conversion. Byย caching and serving images through Uploadcareโ€™s CDN, you ensure consistent performance and security, reducing load times and enhancing user experience.

Conclusion

Image optimization isย vital toย enhancing the performance ofย Next.js applications. Using the built-in Next.js Image component, you can automatically optimize images for different devices and browsers, improving load times and user experience. Additionally, byย integrating Uploadcareโ€™s solutions, such asย the UploadcareImage component and loader, you can further enhance image delivery with advanced transformations and aย robust CDN.

Ready to get started?

Join developers who use Uploadcare to build fileย handling quickly andย reliably.

Sign up for free