naumch1k / one-fall

Landing page for ONE FALL, Salem-based melodic punk and hardcore quartet has rapidly made a mark in New England
https://develop--one-fall.netlify.app/
0 stars 0 forks source link

CHORE: Configure Image Optimization with Netlify Image CDN #5

Closed naumch1k closed 1 month ago

naumch1k commented 1 month ago

Description

When we working with images on the web there few main problems:

  1. Layout shifts with images loading in which is distracting for visitors
  2. Images loaded are not optimized for viewport or the device that the visitor is using

Image component in Next.js extends the HTML <img> element with features to solve those problems. Correct usage of Image component will prevent layout shift automatically when images are loading. All images will be only loaded when they enter the viewport using native browser lazy loading.

Next.js default loader uses the built-in Image Optimization API and serves them directly from the Next.js web server. That require zero configuration when an app deployed via Vercel. However, our app deployed via Netlify and we'll have to define custom image loader and utilize Netlify Image CDN.

Changes Made

Screenshots, GIFs, or videos

Let's take a look at one image before and after rerouting it to Netlify Image CDN. Original size is 162kB, this is PNG file.

Screenshot 2024-06-09 at 10 48 35 PM

Netlify Image CDN

At the screenshot below /.netlify/images is what automatically optimizing images making them a bit smaller. It also detects user's browser and converts to more modern image format - AVIF or WEBP, which is also contributing to smaller file sizes. Now file size is impressive 88.2kB and it was converted to AVIF. Lighthouse is giving us a green light for sure!

Screenshot 2024-06-09 at 11 00 11 PM Screenshot 2024-06-09 at 10 48 43 PM

Usage

netlifyLoader function constructs a URL for Netlify's Image CDN using the provided src, width, and quality. The quality parameter has a default value of 75 if not explicitly provided.

// src/helpers/netlifyLoader.ts
export default function netlifyLoader({ 
  src,
  width,
  quality = 75,
 }: INetlifyLoaderParams) {
  return `/.netlify/images?url=${src}&w=${width}&q=${quality}`
}

Next.js configuraton:

// next.config.mjs
const nextConfig = {
  images: {
    loader: 'custom',
    loaderFile: './src/helpers/netlifyLoader.ts',
  },
  ...
}