Unable to serve static files when using NextJs in conjunction with Storybook

The documentation for Next.js (found here) suggests placing image file paths under the public directory.

I have a component that successfully displays an image in my Next.js project, but it doesn't render properly within Storybook. The image file is currently located 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 the current configuration 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 a missing piece that would enable me to display images in Storybook the same way they are set up in Next.js?

Answer №1

If you want to use images in Storybook, you need to specify where they are located. For Next.js projects, the images typically reside in the 'public/' directory, so you can simply add '-s ./public' to your script when running Storybook:

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

For more information, refer to the documentation here:

Answer №2

My solution involved specifying the location of my public resources for storybook.js by using the staticDirs property.

For example, I structured it as follows: main directory > .storybook folder > main.ts

const config: StorybookConfig = {
 //other stuff .... 
  docs: {
    autodocs: 'tag',
  },

  staticDirs: ['../public/'], //<--- FIX    };

};
export default config;

Answer №3

To make changes to the .storybook/preview.js file, follow these steps:

import * as CustomImage from 'next/image';

const OriginalCustomImage = CustomImage.default;

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a GIF loader in your webpack configuration for a Typescript/React/Next.js application

Upon inserting a .gif file in my Typescript React app, an error message has surfaced. ./src/gif/moving.gif 1:6 Module parse failed: Unexpected token (1:6) You may need an appropriate loader to handle this file type, currently no loaders are configured to p ...

The troubleshooting of compatibility issues between TailwindCSS and HTML Input and Button tags

Recently, I decided to switch from using plain CSS to TailwindCSS for styling the navbar component that I obtained from the Bootstrap website. While TailwindCSS has helped me style most parts of the navbar successfully, I have encountered a challenge with ...

What is the reason behind the exclusion of post categories from Strapi's API?

I have created two content types: post and category. The category has a relationship of many-to-many with the post content type. However, I am unable to retrieve each post's category through the API! The API URL that I am using to fetch all posts ...

Error 401: Unauthorized access detected while handling a Webhook

My goal is to handle a webhook sent by the authentication provider Clerk when a new user is created. To test this process locally, I initially used localtunnel without success and then switched to ngrok. Upon receiving the webhook at https://13f1-...-859 ...

Session creation issue with custom Credential Provider in NextAuth

I am currently in the process of integrating NextAuth into my NextJs application by following the official documentation. However, I have encountered an issue where the user session object does not seem to be generated upon login. Below is the snippet of ...

How can one click the button within the expanded dropdown while hovering over the navigation item in Angular and Bootstrap?

Issue Description: Upon hovering over a navigation item, the dropdown container is displayed but it's not clickable. Desired Behavior: Hovering over a navigation item should display the dropdown container and allow clicking on its contents. Furthermo ...

Issue with S3 when attempting to download an image due to CORS

I am encountering an issue with downloading images from S3. It was functioning properly recently, but now I am facing a CORS Error. My setup includes Next.js v12.3.0 and Strapi. Here is the CORS Configuration that I have implemented: (imagine that I added ...

Properly passing props to child components in React with TypeScript. Resolve Error ts(2322)

I am facing an issue where my code works perfectly in Javascript, but encounters problems when converted to Typescript. Despite the complexity of the question, it actually boils down to a simple query. I just wanted to share the functional JS code as a sol ...

Establish a permanent code folding feature in the Monaco editor for enhanced text organization

I need help implementing persistent code folding on the Monaco editor. Specifically, I am unsure about: how to extract the view state when it changes; storing it in localstorage; and then restoring it when Monaco is loaded. Although I am aware of saveVie ...

Struggling to incorporate this script tag into my next.js application and encountering some difficulties

If you want to integrate EmailJS into your website, simply add the code snippet below before the closing tag, making sure to replace "YOUR_USER_ID" with your actual user ID: <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com@2 ...

Creating an Angular 2 component library that is compatible with both webpack.js and system.js: A guide

This is my first venture into creating an Angular 2 library. So far, it consists of a collection of components. I am aiming to make this library compatible with both Webpack and SystemJS. I have successfully written the code for the first component to be c ...

"Looking for a way to eliminate the background of an image on NextJS? Learn

https://i.stack.imgur.com/zAsrJ.png When this image is incorporated into a Nextjs rendering, it unexpectedly includes additional content. <div className="flex flex-col items-start justify-start rounded-3xl p-4 bg-boxi w-1/3"> <div cla ...

Can html-webpack-plugin be configured to create <style> elements from CSS files?

I am managing a static site with Vue and Webpack. In my project, I have a file named style.css containing global CSS rules which I import using import './styles.css' in my index.js file. Additionally, I have some .vue files that generate their o ...

When a module is generated, it appends an additional slash to the path in the app.module.ts file

I've noticed a strange behavior with the generator in Angular CLI tools that adds an extra slash character for modules. For example, when running ng generate component visual a line like this is added to the app.module.ts file import { VisualCo ...

Issue with displaying data using a custom pure pipe and boolean in ngIf condition

For my current web project, I require a friendship/follow feature. There are two roles involved: admins and regular users. Regular users have the ability to follow other users, while admins do not possess this capability. When a user wishes to follow anot ...

Allowing HTML attributes in reusable components with Vue TSX: A guide on informing Typescript

Imagine I have a custom input component: import { defineComponent } from "@vue/runtime-core" export default defineComponent({ inheritAttrs: false, setup(props, { attrs }) { return () => ( <div> ...

What are the advantages of utilizing the HttpParams object for integrating query parameters into angular requests?

After exploring different ways to include query parameters in HTTP requests using Angular, I found two methods but struggled to determine which one would be the most suitable for my application. Option 1 involves appending the query parameters directly to ...

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

Simultaneously executing React and Node

I have encountered a challenge with my use case that involves integrating React into my existing express/EJS application. Currently, the express app is running on port 35, while I am trying to add React by following a tutorial and running it on a different ...

Encountering issues while attempting to connect to Metamask using React and Next.js

I'm currently working through a tutorial on creating an NFT marketplace using Next.js, and I've hit a roadblock when it comes to implementing a button that should open MetaMask. From what I understand, calling 'connectWallet('injected&a ...