Sentry Answers>Next.js>

How to allow domains for images in Next.js

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:

Click to Copy
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:

Click to Copy
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.

  • Community SeriesDebug Next.js with Sentry
  • ResourcesJavaScript Frontend Error Monitoring 101
  • ResourcesSentry vs. Crashlytics: The Mobile Developer's Decision-Making Guide
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,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.

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