Next.js
Beginner
1 min read
Optimising Images with next/image
Example
// Local image import — width and height inferred automatically
import Image from 'next/image';
import heroImage from '@/public/hero.png';
export default function HeroSection() {
return (
<section>
{/* Local image: width/height from import */}
<Image
src={heroImage}
alt="Hero banner"
priority // LCP image — disables lazy load, adds preload
placeholder="blur" // blurred placeholder while loading
className="w-full h-auto"
/>
</section>
);
}
// Remote image — must allow hostname in next.config.js
function ProductCard({ product }: { product: { name: string; imageUrl: string } }) {
return (
<div className="relative">
{/* fill: image fills the parent container */}
<div className="relative w-full aspect-square">
<Image
src={product.imageUrl}
alt={product.name}
fill
sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
className="object-cover rounded-lg"
/>
</div>
<p>{product.name}</p>
</div>
);
}
// Fixed size remote image
function Avatar({ url, name }: { url: string; name: string }) {
return (
<Image
src={url}
alt={name}
width={48}
height={48}
className="rounded-full"
/>
);
}