stackademic

The leading education platform for anyone with an interest in software development.

Image Optimization

Serve responsive, lazy-loaded images with the built-in next/image component

Overview

The next/image component automatically optimizes images: it resizes for the viewport, serves modern formats like WebP, lazy-loads offscreen images, and prevents layout shift by reserving space. It works with static imports, remote URLs, and fills, replacing manual <img> tuning with sensible defaults.

Syntax / Usage

Import Image and provide a source. Static imports supply width and height automatically; remote images need them explicitly.

import Image from 'next/image'
import hero from '@/public/hero.png'

export default function Banner() {
  return (
    <Image
      src={hero}
      alt="Product hero"
      placeholder="blur" // auto blur-up for static imports
      priority // preload above-the-fold images
    />
  )
}
// Remote image — dimensions are required
<Image src="https://cdn.example.com/a.jpg" alt="Avatar" width={80} height={80} />

Examples

Allow remote hosts in next.config.ts before using external URLs:

// next.config.ts
import type { NextConfig } from 'next'

const config: NextConfig = {
  images: {
    remotePatterns: [{ protocol: 'https', hostname: 'cdn.example.com' }],
  },
}
export default config

Use fill with a sized parent for responsive cards:

<div style={{ position: 'relative', aspectRatio: '16 / 9' }}>
  <Image
    src="/cover.jpg"
    alt="Cover"
    fill
    sizes="(max-width: 768px) 100vw, 50vw"
    style={{ objectFit: 'cover' }}
  />
</div>

Common Mistakes

  • Omitting sizes with fill, causing oversized downloads
  • Using priority on many images instead of just the LCP element
  • Forgetting remotePatterns, which throws for external URLs
  • Setting width/height that mismatch the aspect ratio, distorting the image
  • Missing meaningful alt text, hurting accessibility and SEO

See Also

nextjs-data-fetching metadata app-router