Menu

Optimising Images with next/image

Lesson 2: Optimising Images with next/image

What does next/image do?

The Image component extends the HTML <img> tag with automatic optimisation.

Feature Benefit
Resizes per device Phones download smaller files
Modern formats (WebP, AVIF) Smaller files at similar quality
Lazy loading by default Off-screen images load only when needed
Required size information Prevents layout shift while loading
Caching Optimised images are reused

Example

import Image from 'next/image';
import hero from '@/public/hero.jpg'; // Local, static import

export function Hero() {
  return (
    <Image
      src={hero}
      alt="Students learning online"
      priority
      placeholder="blur"
    />
  );
}

export function CourseThumbnail({ url, title }: { url: string; title: string }) {
  return (
    <Image src={url} alt={title} width={400} height={225} sizes="(max-width: 768px) 100vw, 400px" />
  );
}

Remote images must be allowed in next.config.ts:

import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  images: {
    remotePatterns: [
      { protocol: 'https', hostname: 'cdn.learnhub.in', pathname: '/thumbnails/**' },
    ],
  },
};

export default nextConfig;

How it works

  • Static imports give Next.js the width and height automatically. Remote images need width and height, or fill inside a positioned parent.
  • sizes tells the browser how wide the image will be displayed, so it downloads the right file.
  • priority (or preload) loads above-the-fold images early, improving Largest Contentful Paint.
  • In Next.js 16, images.domains is deprecated in favour of remotePatterns, and the default allowed quality is 75. Add other values to images.qualities if you need them.

Common mistakes

Mistake Effect Fix
Missing alt text Accessibility and SEO issues Describe the image; use alt="" only for decoration
Using fill without a sized parent Image collapses or covers the page Parent needs position: relative and a height
Lazy-loading the hero image Slow LCP Add priority to the main above-the-fold image
Allowing any remote host (hostname: '**') Others can use your optimiser List specific hosts and paths

Key takeaways

  • Use next/image for content images; it handles size, format, and loading.
  • Always provide alt, size information, and sizes for responsive images.

Try it: Replace every <img> in LearnHub with Image, add priority to the hero, and compare page weight in DevTools.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details