CPCODELAB
Next.js

Optimised Images with next/image

7 min read

The Image Component

The next/image component automatically resizes, compresses, and serves images in modern formats (WebP, AVIF). It lazy-loads by default and prevents layout shift by requiring explicit width and height props.

tsx
import Image from "next/image";

export default function Avatar() {
  return (
    <Image
      src="/team/jaideep.jpg"
      alt="Jaideep Chauhan"
      width={128}
      height={128}
      priority // load eagerly for above-the-fold images
    />
  );
}

For images from external domains, you must whitelist the hostname in next.config.ts under images.remotePatterns. This prevents arbitrary external URLs from being proxied through Next.js's optimisation server.

ts
// next.config.ts
import type { NextConfig } from "next";

const config: NextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "images.unsplash.com",
      },
    ],
  },
};

export default config;

Always use next/image instead of a plain <img> tag for any image in a Next.js project. The performance gains are automatic and significant.

Ready to test yourself?
Practice Next.js— quiz & coding exercises