next.js

Next.js - Can I configure multiple image hostnames in next.config.js?


I write this code below in my next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: [
          'images.unsplash.com',
          'hydeparkwinterwonderland.com',
          'wembleypark.com']
      },
    ]
  }
}

module.exports = nextConfig

but it throw an error like this:

- The value at .images.remotePatterns[0].hostname must be a string but it was an array.

See more info here: https://nextjs.org/docs/messages/invalid-next-config
Error: Invalid images.remotePatterns values:
{"protocol":"https","hostname":["images.unsplash.com","hydeparkwinterwonderland.com","wembleypark.com"]}

remotePatterns value must follow format { protocol: 'https', hostname: 'example.com', port: '', pathname: '/imgs/**' }.
See more info here: https://nextjs.org/docs/messages/invalid-images-config

looking for an answer, I'm a newbie please be patient with me


Solution

  • hostname only allows a single value, so you cannot pass an array of host names. Instead of that, you can have multiple items for host names in remotePatterns.

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      reactStrictMode: true,
      images: {
        remotePatterns: [
          {
            protocol: 'https',
            hostname: 'images.unsplash.com'
          },
          {
            protocol: 'https',
            hostname: 'hydeparkwinterwonderland.com'
          },
          {
            protocol: 'https',
            hostname: 'wembleypark.com'
          },
        ]
      }
    }
    

    Or less duplicated code with map

    const hostnames = [
              'images.unsplash.com',
              'hydeparkwinterwonderland.com',
              'wembleypark.com']
    
    /** @type {import('next').NextConfig} */
    const nextConfig = {
      reactStrictMode: true,
      images: {
        remotePatterns: hostnames.map(hostname => ({
            protocol: 'https',
            hostname
        }))
      }
    }