Course
Optimizing II
Next.js Mastery: From Fundamentals to Full-Stack
Unlock the power of Next.js with this comprehensive course! Starting with the basics, you’ll learn essential skills such as routing, data fetching, and styling. Progress through practical projects, including building your own React Notes app, to gain hands-on experience. Dive into the source code to understand the inner workings and core principles of Next.js. Perfect for developers with a basic knowledge of React and Node.js, this course ensures you’ll be ready to create high-performance full-stack applications efficiently. Join us and master Next.js, backed by industry experts and a supportive learning community.
Optimizing
Animated Images
The default loader will automatically skip optimization for animated images and display them as is.
Next.js will automatically detect animated images and supports GIF, APNG, and WebP formats. For specific animated images, if you want to explicitly skip optimization, you can use the
unoptimized
prop (this avoids the need for Next.js to detect and judge).Responsive Images
By default, the generated
srcset
for images includes 1x and 2x images to support different device pixel ratios. However, there are times when you want to render responsive images that automatically adapt to the viewport. In such cases, you need to set the sizes
and style
(or className
). Here are different ways to render responsive images:1. Responsive Images with Static Import
If the source image is not animated, you can create a responsive image through static import:
// components/author.jsimport Image from 'next/image'import me from '../photos/me.jpg'
export default function Author() { return ( <Image src={me} alt="Picture of the author" sizes="100vw" style={{ width: '100%', height: 'auto', }} /> )}
2. Responsive Images with Aspect Ratio
If the source image is animated or a remote URL, you need to provide
width
and height
to set the correct aspect ratio for the responsive image.// components/page.jsimport Image from 'next/image'
export default function Page({ photoUrl }) { return ( <Image src={photoUrl} alt="Picture of the author" sizes="100vw" style={{ width: '100%', height: 'auto', }} width={500} height={300} /> )}
3. Responsive Images with the fill Attribute
If you don't know the aspect ratio of the image, you can consider using the
fill
attribute. Make sure to set the parent element to position: relative
. You can also use object-fit
depending on the desired effect:// app/page.jsimport Image from 'next/image'
export default function Page({ photoUrl }) { return ( <div style={{ position: 'relative', width: '500px', height: '300px' }}> <Image src={photoUrl} alt="Picture of the author" sizes="500px" fill style={{ objectFit: 'contain', }} /> </div> )}
4. Using Grid with Responsive Images
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, contain, none }} /> </div> {/* And more images in the grid... */} </div> )}
Theme-Specific Images
If you want to display different images in light and dark modes, you can create a new component containing two
<Image>
components and use CSS media queries to display the correct one:/* components/theme-image.module.css */.imgDark { display: none;}
@media (prefers-color-scheme: dark) { .imgLight { display: none; } .imgDark { display: unset; }}
// components/theme-image.tsximport styles from './theme-image.module.css'import Image from 'next/image'
const ThemeImage = (props) => { const { srcLight, srcDark, ...rest } = props
return ( <> <Image {...rest} src={srcLight} className={styles.imgLight} /> <Image {...rest} src={srcDark} className={styles.imgDark} /> </> )}
Cumulative Layout Shift (CLS)
When using the Next.js image component, you’ll notice that Next.js requires
width
and height
attributes, even when using static image imports. You don’t have to manually write these attributes, but Next.js will still automatically add width
and height
for you. The reason for this is to prevent layout shifts. A layout shift is when content unexpectedly moves on the page, often during loading. One common cause of layout shifts is images without specified dimensions. Let’s look at a demonstration video:
This is what happens when images don’t have dimensions, causing a layout shift. What if you set dimensions?
You’ll notice that when the image loads, the browser reserves space for it.
Don’t underestimate layout shifts; there’s a specific Web performance metric called Cumulative Layout Shift (CLS) dedicated to measuring this. CLS is one of Google’s Core Web Vitals. CLS measures the amount and impact of layout shifts visible in the viewport.
The design of
next/image
is intended to prevent layout shifts, so if you need to resize an image, you should use one of the following three methods:- Automatic static import
- Explicitly declare
width
andheight
attributes - Implicitly declare by using
fill
to make the image fill the parent element