• Homeright arrow
  • Blogright arrow
  • Optimizing Images in Jamstack Sites with Next.js
Feature

Optimizing Images in Jamstack Sites with Next.js

Image optimization is vital for websites as it boosts loading speeds, enhancing user experience. Optimized images improve SEO by reducing bounce rates, increasing dwell time and conserving bandwidth, reducing server load and costs. Additionally, optimized images cater to mobile users, who form a significant portion of web traffic. Overall, image optimization ensures a seamless browsing experience, higher search engine rankings, and cost-effectiveness for website owners.

Image Optimization in Next.js

The Next.js Image component enhances the HTML <img> element with automatic image optimization features by optimizing sizes, stabilizing visibility and so on.

Usage

First, import the Image from next/image using the following code:

import Image from 'next/image'

Now define the src for your image. You can use either a local or remote image.

Local Image

To add a local image import your image from the public folder first. In this case, you don’t need to use any width and height property. Next.js will automatically determine the size of the image based on the imported file.

import Image from 'next/image'
import profilePic from '../public/me.png'

export default function Home() {
return (
<Image
src={profilePic}
alt="Picture of the author"
/>
)
}

Remote Images

To use a remote image, the src property should be a URL string. For remote images width and height is mandatory. The width and height characteristics are used to establish an image's exact aspect ratio, which reduces layout changes caused by image loading.

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 allow image optimization safely, add a list of permitted URL patterns to next.config.js. This ensures that the Next.js Image Optimization API can only deliver external pictures associated with your account. These external pictures can be specified in your next.config.js file using the remotePatterns parameter, as seen below:

module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/testPath/**',
},
],
},
}

The code above will make sure that the next/image's src attribute must begin with https://example.com/testPath/. Otherwise, A 400 Bad Request error message will be sent for any other protocol, hostname, port, or mismatched path.

Props used to Customize Images:

The Image Component requires the following properties: src, width, height, and alt.

SRC: src property is the source file of the image. It must be either imported statically or an absolute external URL or an internal path.

Width: The width property defines the displayed width of the image in pixels, influencing its size on the page. It's mandatory, except for statically imported images or those with the fill property.

Height: The height property specifies the displayed height of the image in pixels, affecting its visual dimensions. It's mandatory, except for statically imported images or those with the fill property.

Alt: The alt property describes the image for screen readers and search engines. It serves as fallback text when images are disabled or loading errors occur.

Optional Props

Several optional props are used in customizing images in addition to the required props in Next.js. Let’s discuss some optional props used in Next.js.

Loader

A loader is a custom function responsible for resolving image URLs. It returns a URL string for the image based on the provided parameters: src, width, and quality. This function enables the dynamic generation of image URLs tailored to specific requirements. Below is an example demonstrating the usage of a custom loader.

'use client'

import Image from 'next/image'

const imageLoader = ({ src, width, quality }) => {
return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}

export default function Page() {
return (
<Image
loader={imageLoader}
src="me.png"
alt="Picture of the author"
width={500}
height={500}
/>
)
}

Fill

When set to true, this boolean attribute enables the image to fill its parent element. This feature is valuable when the dimensions of the image are unknown. However, it requires the parent element to have a style of position: "relative", position: "fixed", or position: "absolute"

import Image from 'next/image'

export default function Page() {
return (
<Image
src="me.png"
alt="Picture of the author"
fill={true} // {true} | {false}
/>
)
}

Sizes

A string, similar to a media query, provides information about how wide the image will be at different breakpoints. The value of sizes will greatly affect performance for images using fill or which are styled to have a responsive size.

import Image from 'next/image'

export default function Page() {
return (
<div className="grid-element">
<Image
fill
src="/example.png"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
/>
</div>
)
}

quality:

The quality attribute determines the image's optimisation level, specified as an integer ranging from 1 to 100. A value of 100 indicates the highest quality but also results in a larger file size. By default, it's set to 75.

priority:

When set to true, the priority attribute marks the image as a high priority for loading, enabling preloading. This overrides lazy loading for the image. It's configured as a boolean attribute, accepting either true or false values.

placeholder:

The placeholder attribute determines the placeholder to display while the image is loading. It accepts three possible values:

"blur": Displays a blurred placeholder image.

"empty": The default value is "empty". Shows no placeholder, leaving the space blank.

"data:image/...": Specifies a custom placeholder using a data URI.

Styles

Allow CSS styles on image components.

const imageStyle = {
borderRadius: '50%',
border: '1px solid #fff',
}

export default function ProfileImage() {
return <Image src="..." style={imageStyle} />
}

It's very important to remember that the required width and height props can affect your styling choices. If you adjust an image's width using styling, make sure to set its height to "auto" as well. This preserves the image's intrinsic aspect ratio, preventing distortion.

There are also many optional props that we can use. To read more on those you can visit the official Next.js Image link.

Conclusion

In conclusion, effective image optimization is essential for enhancing website performance and user experience. By properly sizing images, optimizing quality, utilizing placeholders, and ensuring accessibility, websites can achieve faster loading times and improved visual appeal. Continuous optimization ensures ongoing efficiency and user satisfaction. Moreover, Next.js make image optimization easy, smooth and straightforward.

To create a fully optimized image site with Next.js, contact StaticMania. Our dedicated team will guide you on every step.

Create Progressive Web Apps (PWAs) with Next.js
thumbnail

Progressive Web Apps (PWAs) with Next.js

A Progressive Web App (PWA) is a web application that gives consumers a mobile app experience by leveraging contemporary web technology. PWAs are made to function on any platform or device - desktop, laptop, tablet, or smartphone - that has a browser that complies with standards

Read article
footer-particlefooter-particlefooter-particlefooter-particlefooter-particle
back-to-top