Capítulo 289 de 456

Images

Core Idea

Use next/image (Pages Router) instead of <img> to get automatic size optimization, layout-shift prevention, lazy loading and support for local or remote sources.

Key Concepts

  • Local images: place under public/ and reference from /, or import the file directly to get automatic width/height/blurDataURL.
  • Dynamic import(): in a Server Component, await import(...) a file path with a static prefix to still get automatic dimensions when the filename is dynamic.
  • Remote images: pass a URL string to src; you must manually supply width, height, and optional blurDataURL (or use fill), since Next.js can't inspect remote files at build time.
  • remotePatterns: next.config.js images.remotePatterns allowlist required for any remote src, to prevent malicious usage.

Code Examples

import Image from 'next/image'

async function PostImage({ imageFilename, alt }: { imageFilename: string; alt: string }) {
  const { default: image } = await import(
    `../content/blog/images/${imageFilename}`
  )
  // image contains width, height, and blurDataURL
  return <Image src={image} alt={alt} />
}
  • O que demonstra: import dinâmico com prefixo estático preserva as dimensões automáticas mesmo com nome de arquivo variável.
const config: NextConfig = {
  images: {
    remotePatterns: [
      { protocol: 'https', hostname: 's3.amazonaws.com', port: '', pathname: '/my-bucket/**', search: '' },
    ],
  },
}
  • O que demonstra: allowlist restritiva de host/path pra imagens remotas.

Anti-patterns

  • Import dinâmico com prefixo variável: o prefixo do path precisa ser estático; todos os arquivos que casam com ele são empacotados, então seja específico.
  • remotePatterns genérico demais: hostname/pathname amplos abrem brecha pra uso malicioso do otimizador de imagem.

Key Takeaways

  1. Import estático ou dinâmico de imagem local elimina a necessidade de passar width/height manualmente.
  2. Imagem remota exige width+height (ou fill) e um remotePatterns explícito no config.
  3. <Image> já resolve lazy loading nativo e blur-up sem configuração extra.

Connects To

  • ch290 Fonts: mesmo padrão de otimização automática via next/font.