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

Ways to halt the expressjs server

After deploying my express and nextjs based app on EC2, I encountered an issue where the server automatically starts Nginx and node with different process IDs after I attempt to stop it by killing the process. This is happening even without using tools lik ...

Adding images dynamically in Next.js version 14 is a breeze with the latest updates and features

I have developed an admin panel where images can be added for projects. The following javascript code is what enables this action: export const createProduct = async (state, formData) => { const result = productSchema.safeParse( Object.fromEntries ...

What is the best way to execute my mocha fixtures with TypeScript?

I am seeking a cleaner way to close my server connection after each test using ExpressJS, TypeScript, and Mocha. While I know I can manually add the server closing code in each test file like this: this.afterAll(function () { server.close(); ...

How come the type checker is not throwing an error for this indexable type?

I recently delved into the Microsoft Typescript Handbook and found myself intrigued by the indexable types chapter. To gain a deeper understanding, I decided to experiment with the code provided. Strangely enough, upon running this particular piece of code ...

What is the best way to share an HTML element across multiple pages in Next.js?

I am in the process of developing a website that features a table of contents with links on the left side, content sections in the middle, and an overview on the right. For a visual representation of the general concept, please visit: Currently, all code ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...

When invoking a service repeatedly in Angular within a loop, the result is returned on the second iteration rather than the first

I've run into an issue where I'm attempting to invoke a service in Angular within a for loop and store the result in a Map. map = new Map<string, string[]>(); this.effectivitiesList = this.trimEffectivities.split(","); for (let ...

Using Next.js with Material-UI pagination for a MongoDB API integration

I am currently developing an administrator dashboard for a personal website using Next.js. Below is the backend API I am working with: import nc from 'next-connect'; import Listing from '../../../../models/Notes'; import db from '. ...

typescript import { node } from types

Exploring the possibilities with an electron application developed in typescript. The main focus is on finding the appropriate approach for importing an external module. Here is my typescript configuration: { "compilerOptions": { "target": "es6", ...

Encountering an unexpected token error while using Webpack with React modules

I've been attempting to utilize the react-spin npm package, but when I try to create a bundle.js with webpack, an error occurs: Module parse failed: /Users/nir/browsewidget/node_modules/react-spin/src/main.js Line 29: Unexpected token < You may ne ...

You are able to use a null type as an index in angular.ts(2538) error message occurred

onClick() { let obj = { fName: "ali", LName: "sarabi", age: "19", } let fieldName = prompt("field"); alert(obj[fieldName]); } I encountered an issue with the code above where alert(obj[fieldName] ...

Challenges arise when working with Angular using ngrx and typescript, particularly when dealing

I'm encountering an issue while working with ngrx. I keep receiving an error when attempting to implement a simple effect. The specific error message mentions that the Argument of type 'MonoTypeOperatorFunction<LoadContainerAction>' is ...

Converting JSON array to custom object array in TypeScript

As a newcomer to this area, please excuse any inaccuracies in my language. Don't hesitate to ask for more details if needed. I currently have some TypeScript interfaces: export interface Item { id: string type: string state: string } ex ...

Encountering a Static Injector error in Angular 5 while trying to inject a component from a shared module

Here lies the code for my component file. My goal is to develop a reusable modal component using ng-bootstrap's modal feature. However, upon trying to import the following component from the shared module, I encounter a static injector error. Despite ...

Tips for setting up the configuration of @typescript-eslint guidelines

I am in the process of transitioning to @typescript-eslint but I am finding the documentation to be quite inadequate. One specific issue I am facing is the errors like the following: Line 58: Expected a semicolon @typescript-eslint/member-del ...

Can you please provide the Typescript type of a route map object in hookrouter?

Is there a way to replace the 'any' type in hookrouter? type RouteMap = Record<string, (props?: any) => JSX.Element>; Full Code import { useRoutes, usePath, } from 'hookrouter' //// HOW DO I REPLACE any??? type RouteMap = ...

brings fulfillment except for categories

The new satisfies operator in TypeScript 4.9 is incredibly useful for creating narrowly typed values that still align with broader definitions. type WideType = Record<string, number>; const narrowValues = { hello: number, world: number, } sa ...

Tips for retrieving the ID of a dynamic page

In my Higher Order Component (HOC), I have set up a function that redirects the user to the login page if there is no token. My goal is to store the URL that the user intended to visit before being redirected and then push them back to that page. However, ...

Setting up redux with Next.js: a step-by-step guide

After setting up redux in this manner, everything is functioning properly. The _app.js file has been reorganized as follows : import App from 'next/app'; import { Provider } from 'react-redux'; import withRedux from 'next-redux-wr ...

Encountering a Typescript Type error when attempting to include a new custom property 'tab' within the 'Typography' component in a Material UI theme

Currently, I am encountering a Typescript Type error when attempting to add a custom new property called 'tab' inside 'Typography' in my Material UI Theme. The error message states: Property 'tab' does not exist on type &apos ...