Category: Advanced Next.js Concepts

Dive into the more advanced concepts of Next.js with our advanced guides.

 

This category is designed for experienced developers looking to master topics such as serverless functions, edge rendering, performance optimization, custom middleware, and scaling Next.js applications.

  • How to set up custom image loader for Next.js

    When working with Next.js’ Image component you specify the src prop to set the source image url. But did you know you can save a lot of time using a custom image loader for the Image component so that you can predefine some variables in it to avoid repeated tasks?

    For example you could configure the image loader to always use a specific CDN for example vyso.io for every image? You could also pre-define some parameter for the url so that you don’t need to repeat them!

    Here’s how you do it:

    1. Create custom image loader config file

    First, create a new file in the project’s root, e.g.:

    my-custom-image-loader.js

    And export a default function from it with the source url that should be used whenever you use a next/image component:

    export default function MyCustomImageLoader({ src }) {
      return `https://cdn.vyso.io/${src}`
    }

    The props in curly braces are the props that will be passed down from the Image component so you can use them to freely shape your target url as in the example above.

    2. Add custom image loader to Next.js config

    Now you’ve defined your basic image loader config you must make Next.js aware of it. To do this edit your next.config.mjs or next.config.ts file and add the following block:

    images: {
        loader: 'custom',
        loaderFile: 'my-custom-image-loader.js',
      },

    Congratulations, you’ve just configured your custom image loader for Next.js and can use Image component in the following fashion:

    <Image
                      src="image-without-base-url.jpg"
                      alt="Image alt text"
                      width={600}
                      height={400}
                    />

    As I mentioned before you can make use of the Image component props in the loader, because they are passed down to its function.

    So for example vyso.io digital asset management platform allows you to specify some optimization parameters for example width, height and quality that will be dynamically applied to the image served before it’s downloaded from the CDN, so you can apply these params directly from the Image component and all optimizations will run automatically in the background without any manual intervention:

    export default function MyCustomImageLoader({ src, width, quality }) {
      return `https://cdn.vyso.io/${src}?w=${width}&h=${height}&q=${quality || 75}`
    }
    

    That’s it! I highly recommend using custom loaders to avoid repetition of providing the source url and parameters for each individual image, which makes work so much quicker.

    Happy coding!