'Cant serve static files in NextJs + Storybook

The nextjs docs (https://nextjs.org/docs/basic-features/static-file-serving) state to add image file paths under the public directory.

I have a component that renders an image component and the file renders correctly on my nextjs project but doesn't render inside of storybook. The image file is currently living in public/images/

const renderImage = () => {
    const portraitClassName = cx({
        [styles.imageContainerPortrait]: true,
    });

    return (
        <img
            className={portraitClassName}
            data-testid="image"
            src="/images/portrait.png"
            alt={image.imgAlt}
        />
    );
};

This is my current config file for storybook

webpackFinal: async (config) => {
        config.module.rules.push({
            test: /\.(scss|sass|css)$/,
            use: [
                {
                    loader: "sass-loader",
                    options: {
                        implementation: require("sass"),
                    },
                },
                {
                    loader: "postcss-loader",
                    options: {
                        ident: "postcss",
                        plugins: [tailwindcss, autoprefixer],
                    },
                }
            ],
            include: path.resolve(__dirname, "../"),
        });
        return config;
    }

Is there something missing that would allow me to render images in the same manner as how Nextjs is set up?



Solution 1:[1]

You need to tell storybook where to find your images. In nextjs they stays in public/ so you can just add -s ./public to your script to run storybook:

//package.json
{
"scripts": {
    "start-storybook": "start-storybook -s ./public"
  }
}

Here docs link for reference: https://storybook.js.org/docs/react/configure/images-and-assets#serving-static-files-via-storybook

Solution 2:[2]

You need to modify the .storybook/preview.js file like this:

import * as NextImage from 'next/image';

const OriginalNextImage = NextImage.default;

Object.defineProperty(NextImage, 'default', {
  configurable: true,
  value: (props) => (
    <OriginalNextImage
      {...props}
      unoptimized
      blurDataURL="data:image/jpeg;base64,/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAADAAQDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAf/xAAbEAADAAMBAQAAAAAAAAAAAAABAgMABAURUf/EABUBAQEAAAAAAAAAAAAAAAAAAAMF/8QAFxEAAwEAAAAAAAAAAAAAAAAAAAECEf/aAAwDAQACEQMRAD8Anz9voy1dCI2mectSE5ioFCqia+KCwJ8HzGMZPqJb1oPEf//Z"
    />
  ),
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Giorgia Sambrotta
Solution 2 Xiao Yun