How to allow domains for images in Next.js

Shivan M.

The Problem

In Next.js 13, 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

You can also use the domains prop to provide a list of hostnames that are allowed for external images. However, the domains prop does not support wildcard pattern matching, nor can it restrict protocol, port, and pathname. Thus, any route of a provided hostname can be used for external images.

Below is an example of the domains prop:

module.exports = { images: { domains: ['example.com'], }, }

In this case, both https://example.com/account123 and http://example.com/account113 are valid URLs for external images.

Additional Reading

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

Get Started With Sentry

Get actionable, code-level insights to resolve Next.js performance bottlenecks and errors.

Run the line of code below to:

  1. Create a free Sentry account

  2. Run the CLI install command to automatically add the Sentry SDK to your project:

    npx @sentry/wizard@latest -i nextjs
  3. Start capturing errors and performance issues

Loved by over 4 million developers and more than 90,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.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.