#Images from outside server

1 messages · Page 1 of 1 (latest)

distant pendant
#

The next.js image tag wants an image that is in the public folder, but I need to be able to get the image from a server. Therefore I will just have a url with a different domain (my server), and i could server side it, but idk how, and I need to use that image. Is there any way to do that while still preserving the other good properties of a next.js Image tag?

safe jayBOT
#

Hi @distant pendant. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can use the Next.js Image component to optimize images from an external server while preserving its benefits. To do this, you need to configure Next.js to allow images from your external server. Here’s how you can achieve this:

  1. Configure next.config.js:
    Define a list of supported URL patterns in your next.config.js file to allow images from your external server. Be as specific as possible to prevent malicious usage.

    // next.config.js
    module.exports = {
      images: {
        remotePatterns: [
          {
            protocol: 'https',
            hostname: 'your-server.com',
            port: '',
            pathname: '/path-to-images/**',
          },
        ],
      },
    }
    
  2. Use the Image Component:
    Use the Image component in your pages or components, providing the URL of the image from your external server.

    // pages/index.js
    import Image from 'next/image'
    
    export default function Page() {
      return (
        <Image
          src="<https://your-server.com/path-to-images/image.png">
          alt="Description of the image"
          width={500}
          height={500}
        />
      )
    }
    
  3. Provide width and height:
    Since Next.js does not have access to remote files during the build process, you need to manually provide the width and height props to avoid layout shifts.

    // pages/index.js
    import Image from 'next/image'
    
    export default function Page() {
      return (
        <Image
          src="<https://your-server.com/path-to-images/image.png">
          alt="Description of the image"
          width={500}
          height={500}
        />
      )
    }
    

By following these steps, you can use images from an external server while still leveraging the optimization features of the Next.js Image component.