How to Fix Image Not Loading in Next.js Quickly
In Next.js, images may not load if you use the
next/image component incorrectly or if external domains are not allowed in next.config.js. Fix this by ensuring you import and use Image from next/image properly and configure domains for external images.Why This Happens
Next.js uses a special Image component to optimize images. If you use a regular <img> tag or forget to configure external domains, images may not load. Also, incorrect import or missing width and height props can cause the image to fail rendering.
javascript
import React from 'react'; export default function Profile() { return ( <div> {/* Broken: Using img tag instead of next/image */} <img src="https://example.com/photo.jpg" alt="Profile photo" /> </div> ); }
Output
Image does not load or shows broken image icon in the browser.
The Fix
Use the Image component from next/image and provide width and height props. For external images, add the domain to next.config.js under images.domains. This enables Next.js to optimize and serve the image correctly.
javascript
import Image from 'next/image'; export default function Profile() { return ( <div> <Image src="https://example.com/photo.jpg" alt="Profile photo" width={300} height={300} /> </div> ); } // next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { images: { domains: ['example.com'], }, }; module.exports = nextConfig;
Output
The image loads correctly and is optimized by Next.js.
Prevention
Always use the next/image component for images in Next.js projects. Declare external image domains in next.config.js to avoid loading issues. Provide explicit width and height to prevent layout shifts. Use linting tools that warn about incorrect image usage.
Related Errors
- Image Optimization Error: Happens if the image URL is blocked or invalid. Fix by checking URL and domain config.
- Missing Width/Height Warning: Next.js warns if you omit these props. Always include them.
- Static Export Image Issues: External images may not work with static export unless configured properly.
Key Takeaways
Use the next/image component for all images in Next.js.
Add external image domains in next.config.js under images.domains.
Always specify width and height props to avoid layout problems.
Avoid using plain
tags for images in Next.js projects.
Check image URLs and domain settings if images fail to load.