Search code examples
webpacknext.jsstorybook

Can't properly set up next-config storybook to get images from url


I'm trying to import an image from an url in storybook. In nextJS, images can't come from a domain unless you allow it. I allowed it in the next-config.js file doing the following:

module.exports = {
  env: {
    API: process.env.API
  },
  images: {
    domains: ['https://sourceexample.com/image']
  }
};

It works for when making pages outside of storybook, with the regular next dev. However, when I try to render the same page that has this component:

      <Image
       alt="example"
       src="https://sourceexample.com/image.png"
       width="auto"
       height="auto"
     />

It shows the exact same error when I didn't add the allowed domain in next-config.js, which is: Invalid src prop (https://sourceexample.com/image.png) on `next/image`, hostname "source" is not configured under images in your `next.config.js

I thought that maybe it was because I should import next-config.jsinto storybook configurations, so I google for it and stumbled upon this piece of code, which I don't know what to do with it. This code is written under "How do I setup Storybook to share Webpack configuration with Next.js?" in the storyboook documentation.

module.exports = {
  webpackFinal: async (baseConfig) => {
    const nextConfig = require('/path/to/next.config.js');

    // merge whatever from nextConfig into the webpack config storybook will use
    return { ...baseConfig };
  },

I tried making a spread of the properties in nextConfig like adding return {...baseConfig, ...nextConfig} in the return method. It didn't work. Can someone explain what is happening here and how am I supposed to use it?


Solution

  • Just add this code to the .storybook/preview.js file:

    import * as nextImage from 'next/image';
    
    Object.defineProperty(nextImage, 'default', {
      configurable: true,
      value: props => <img {...props} />
    });
    

    Update: seems that this addon fixes the issue - https://storybook.js.org/addons/storybook-addon-next