Next.js can serve static assets, like images, under the top-level public
directory. Files inside public
can be referenced from the root of the application similar to pages
.
The public
directory is also useful for robots.txt
, Google Site Verification, and any other static assets. Check out the documentation for Static File Serving to learn more.
First, let's retrieve your profile picture.
.jpg
format (or use this file).images
directory inside of the public
directory.profile.jpg
in the public/images
directory.public
directory.With regular HTML, you would add your profile picture as follows:
<img src="/images/profile.jpg" alt="Your Name" />
However, this means you have to manually handle:
And more. Instead, Next.js provides an Image
component out of the box to handle this for you.
next/image
is an extension of the HTML <img>
element, evolved for the modern web.
Next.js also has support for Image Optimization by default. This allows for resizing, optimizing, and serving images in modern formats like WebP when the browser supports it. This avoids shipping large images to devices with a smaller viewport. It also allows Next.js to automatically adopt future image formats and serve them to browsers that support those formats.
Automatic Image Optimization works with any image source. Even if the image is hosted by an external data source, like a CMS, it can still be optimized.
Instead of optimizing images at build time, Next.js optimizes images on-demand, as users request them. Unlike static site generators and static-only solutions, your build times aren't increased, whether shipping 10 images or 10 million images.
Images are lazy loaded by default. That means your page speed isn't penalized for images outside the viewport. Images load as they are scrolled into viewport.
Images are always rendered in such a way as to avoid Cumulative Layout Shift, a Core Web Vital that Google is going to use in search ranking.
Here's an example using next/image
to display our profile picture. The height
and width
props should be the desired rendering size, with an aspect ratio identical to the source image.
Note: We'll use this component later in "Polishing Layout", no need to copy it yet.
import Image from 'next/image';
const YourComponent = () => (
<Image
src="/images/profile.jpg" // Route of the image file
height={144} // Desired size with correct aspect ratio
width={144} // Desired size with correct aspect ratio
alt="Your Name"
/>
);
To learn more about Automatic Image Optimization, check out the documentation.
To learn more about the
Image
component, check out the API reference fornext/image
.
Quick Review: What does next/image
simplify for you?