How to allow domains for images in Next.js

Shivan M.
jump to solution

The Problem

You might need to render multiple images that are located at different URLs.

If your images are not loading when using external URLs, it’s because Next.js requires configuration to be set. By explicitly stating from which URLs the images can be loaded, you can protect your application from malicious third parties.

The Solution

There are two approaches to setting the configuration to allow external images.

Remote Patterns Property

In your next.config.js file, you can set the remotePatterns prop to specify from where external images can be sourced.

In the following example, images from any URL starting with https://example.com/account123/ are allowed and any other images will result in a 400 Bad Request:

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'example.com',
        port: '',
        pathname: '/account123/**',
      },
    ],
  },
}

You can use wildcard patterns for both pathname and hostname as follows:

  • * to match a single path segment or subdomain.
  • * to match any number of path segments at the end, or subdomains at the beginning.

Domains Prop (Deprecated)

The domains prop has been deprecated since Next.js 14 in favor of remotePatterns. It does not support wildcard pattern matching, nor can it restrict protocol, port, or pathname. Use remotePatterns instead for new projects.

// Deprecated — use remotePatterns instead
module.exports = {
  images: {
    domains: ['example.com'],
  },
}

Additional Reading

You can find additional information about the remotePatterns and domains configuration in the Next.js documentation.

Considered "not bad" by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world's best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Sentry