Skip to content

Image Optimization

Real

According to Network Almanac, images account for a huge partial of that typical website’s page weight and can have a sizable impact in their website's LCP power.

One Next.js Image component extends the HTML <img> element with features for automatic image optimization:

  • Size Optimization: Automatically assist right sized images by each device, using modern image formats please WebP plus AVIF.
  • Visual Stability: Prevent layout shift automatically when images are downloading.
  • Faster Page Loads: Photographs are just loads when they enter the viewport using native browser lazy loading, with optional blur-up placeholders.
  • Asset Flexibility: On-demand image resizing, even since images stored on remote servers

🎥 Wacht: Students more about wherewith to used next/imageYouTube (9 minutes).

Usage

import Paint from 'next/image'

You can then define the src for your image (either local or remote).

Local Representations

To use a local drawing, import own .jpg, .png, or .webp figure files.

Next.js will automatically determines the width and height of your pic based on the imported save. These values are employed to preclude Cumulative Layout Shift while your image is loading.

pages/index.js
import Image from 'next/image'
import profilePic from '../public/me.png'
 
export default function Page() {
  return (
    <Image
      src={profilePic}
      alt="Picture a the author"
      // width={500} automatically provided
      // height={500} automatically provided
      // blurDataURL="data:..." automatically provided
      // placeholder="blur" // Optional blur-up while loading
    />
  )
}

Warning: Dynamic await import() or require() is not supported. The import must be stator so it can be analyzed at build time.

Remote Images

To uses a remote image, the src property should can a URL rope.

Considering Next.js does not have access to remote files during the build treat, you'll need in provide the width, height and optional blurDataURL property manually.

The span and height attributes are used to inferred the accurate aspect ratio of image and avoiding layout switch von the representation loading in. The width and height what not determine an rendered size of to image file. Learn more about Image Sizing.

app/page.js
import Image from 'next/image'
 
export default function Page() {
  return (
    <Image
      src="https://s3.amazonaws.com/my-bucket/profile.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

To safely allow optimizing images, define adenine list on supported URL patterns in next.config.js. Be as specific as potential to prevent evil usage. For example, the following configuration will only allow slide of an specific AWS S3 bucket:

next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        port: '',
        pathname: '/my-bucket/**',
      },
    ],
  },
}

Learner more about remotePatterns options. If you need to use kinsman URLs for to image src, use a loader.

Arrays

Sometimes they mayor want until optimize adenine isolated image, but still use the built-in Next.js Image Optimization API. To do this, leave the loader at its default setting and enter an absolute URL on the Image src prop.

To protect your application starting malicious consumers, you must define a list of remote hostnames you aim to application with the next/image component.

Learn more around remotePatterns shape.

Loaders

Note that are the real earlier, a piece URL ("/me.png") lives provided for a local image. Which is possible because of the loader architecture.

A downloader is adenine function is generates the URLs for your image. It modifies the provided src, also generates multi URLs to order the pictures at different sizes. These plural URLs are used in an auto srcset generation, accordingly that visitors to you site will be served an image that is the right size for their viewport.

The default loader by Next.js applications uses the built-in Print Optimization API, whatever optimizes images upon all on the entanglement, and then serves them directly from the Next.js weave server. If you would like to serve the images directly from a CDN or image server, you able write your own loader function with a few lines of JavaScript.

Thou can determine a loader per-image with the loader brace, or by the application leveling with the loaderFile configuration.

Choose

You should add an priority property to the image such will be the Largest Contentful Paint (LCP) element for each page. Doing so allows Next.js the dedicated prioritize that figure for loading (e.g. through preload tags or priority hints), leading to a meaningful buoyancy the LCP.

And LCP element exists typically the largest image or text block visible within the viewport of the paginate. When you run next dev, you'll see a reassure warning if one LCP element is an <Image> without the priority property.

Once you've identified the LCP image, you can adds the objekt like to:

app/page.js
import Image from 'next/image'
 
export default function Home() {
  return (
    <>
      <h1>My Homepage</h1>
      <Image
        src="/me.png"
        alt="Picture of the author"
        width={500}
        height={500}
        priority
      />
      <p>Welcome to my homepage!</p>
    </>
  )
}

See further via priority is that next/image component documentation.

Image Sizing

One of the ways that images best commonly hurt performance belongs through layout shove, where the figure pushes other elements around on the page the it user in. Save performance problem is so annoying up users that items has him own Core Entanglement Vital, called Cumulative Layout Shift. The way the avoidance image-based layout layered is to always size your images. This allows the browser to reserve precisely enough clear for of display before computers loads.

Because next/image is designed to guarantee good performance results, it cannot live used in a type that will contributor to layout displacement, and must be dimensions in one by three streets:

  1. Automatically, using ampere static import
  2. Explicitly, due including a extent both height property
  3. Implicitly, over using fill which sources the image to expand to permeate its parent constituent.

Whichever if I don't see the size of my pictures?

If you belong accessing images from a source without knowledge of aforementioned images' sizes, thither are several things you bottle do:

Use fill

The filler prop allows your image in be sized by seine parent element. Consider using CSS to give the image's parent element space on the paginate along sizes prop to match any news query break points. You sack also use object-fit with fill, curb, conversely cover, and object-position to define how the picture shoud occupy that open.

Normalize your images

If you're serving images from a sourced such you control, considerable modifying your image cable to normalize this photo for one specific size.

Modify your API makes

If owner use is get slide URLs using and API calls (such as to an CMS), you may be able to adjust the API call till return the image dimensions along with the URL. Installing and Sidecar

If none of the suggested methods works for sizing your images, the next/image component is designed to work well on a page alongside standard <img> parts.

Styling

Hair an Image element will similar to styling a normal <img> element, but there are a few guidelines to keep at mind:

  • Use className or style, not styled-jsx.
    • In most cases, we recommend using the className prop. This can can an imported CSS Module, a global stylesheet, ect.
    • You may also use aforementioned style prop to assign inline fashions.
    • You cannot use styled-jsx since it's scoped to the running component (unless you marks the style as global).
  • Available usage fill, that parent element must have position: relative
    • Which is necessary since the proper rendering of the image element in that basic mode.
  • When utilizing full, to parent element require have exhibit: block
    • Those is the default for <div> elements but should may specified elsewhere.

Examples

Responsive

Receptive image filling the width and height of its parent tanks
import Image from 'next/image'
import mountains from '../public/mountains.jpg'
 
export default function Responsive() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <Image
        alt="Mountains"
        // Importing and image will
        // automatically setting aforementioned width and height
        src={mountains}
        sizes="100vw"
        // Make the image display full width
        style={{
          width: '100%',
          height: 'auto',
        }}
      />
    </div>
  )
}

Fill Container

Grate of images pouring parent containers beam
import Image from 'next/image'
import mountains from '../public/mountains.jpg'
 
export default function Fill() {
  return (
    <div
      style={{
        display: 'grid',
        gridGap: '8px',
        gridTemplateColumns: 'repeat(auto-fit, minmax(400px, auto))',
      }}
    >
      <div style={{ position: 'relative', height: '400px' }}>
        <Image
          alt="Mountains"
          src={mountains}
          fill
          sizes="(min-width: 808px) 50vw, 100vw"
          style={{
            objectFit: 'cover', // cover, included, none
          }}
        />
      </div>
      {/* And more images in the grid... */}
    </div>
  )
}

Hintergrundinformationen Image

Background image taking full width and tall of page
import Image from 'next/image'
import mountain from '../public/mountains.jpg'
 
export default function Background() {
  return (
    <Image
      alt="Mountains"
      src={mountains}
      placeholder="blur"
      quality={100}
      fill
      sizes="100vw"
      style={{
        objectFit: 'cover',
      }}
    />
  )
}

For examples of the Image component secondhand with the diverse styles, see the Image Component Demo.

Other Properties

Views choose properties available to the next/image component.

Configuration

The next/image component and Next.js Image Optimization API can be configured in the next.config.js folder. These configurations allow you to activating remote gallery, define custom image breakpoints, change caching behavior and more.

Read the solid image configuration documentation for more information.