Blog.

How to load images from AWS S3 in NextJs (Static website export)

Cover Image for How to load images from AWS S3 in NextJs (Static website export)

Next.js image loaders

The Next.js Image component, next/image, is an extension of the HTML <img> element, evolved for the modern web. It includes a variety of built-in performance optimizations to help you achieve good Core Web Vitals. These scores are an important measurement of user experience on your website, and are factored into Google's search rankings.

Some optimizations built into the Image component include:

  • Improved Performance: Always serve correctly sized image for each device, using modern image formats.
  • Visual Stability: Prevent Cumulative Layout Shift automatically.
  • Faster Page Loads: Images are only loaded when they enter the viewport, with optional blur-up placeholders
  • Asset Flexibility: On-demand image resizing, even for images stored on remote servers

Built-in Loaders

The following Image Optimization cloud providers are included:

  • Default: Works automatically with next dev, next start, or a custom server
  • Vercel: Works automatically when you deploy on Vercel, no configuration necessary. Learn more
  • Imgix: loader: 'imgix'
  • Cloudinary: loader: 'cloudinary'
  • Akamai: loader: 'akamai'
  • Custom: loader: 'custom' use a custom cloud provider by implementing the loader prop on the next/image component

Static web hosting

To be able to use the image loaders we are going to need a server to do the optimization process, or use an external service. I'm going to be handling the image optimization on the build process so I don't want to worry about that when serving the image.

Create a Custom image loader

What I did was to wrap the component into my own MyImage component which will pass down the props, but will always use my custom image loader.

import Image from 'next/image'

const imageLoader = ({ src }) => {
    return `https://naveira.dev${src}`;
}

export default function MyImage(props){
    return <Image {...props} alt={props.alt || "Image"} loader={imageLoader}/>
}

Summary

If you want to optimize your images on the fly and for each user (Meaning different port size and all) you might want to consider one of the other options. For a traditional approach of a static loading of images you might want to do this, all depends on your requirements and how do you want to handle the worflow of your website.

Sign up

Subscribe to get monthly exclusive insights, advice, and the latest industry trends delivered directly to your inbox.

No spam. Unsubscribe at anytime.