Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always 404 error returns on next.js environment #119

Open
hiromaily opened this issue Aug 30, 2023 · 8 comments
Open

Always 404 error returns on next.js environment #119

hiromaily opened this issue Aug 30, 2023 · 8 comments

Comments

@hiromaily
Copy link

hiromaily commented Aug 30, 2023

Though I set handler that handler doesn't work and 404 error returns.
I made sure logging [MSW] Mocking enabled. on console.

I set various handler, get method, post method, full path url, relative path url, handler on preview.ts, handler on each component, but it doesn't change anything.

when I set onUnhandledRequest event, this event always emits.

initialize({
  onUnhandledRequest: ({ method, url }) => {
    console.log(`MSW:onUnhandledRequest [method] ${method}, [url] ${url}`);
  },
});

Is that because next.js specific issue?

I called getWorker() on my storybook component, but its data currentHandlers: Array(0) expresses no handlers set.

  useEffect(() => {
    console.log(getWorker());
    
    fetch("/get_config")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        console.log(data);
      });
  }, []);

my preview.ts is

const preview: Preview = {
  parameters: {
    msw: {
      handlers: [
        rest.get("/get_config", (req, res, ctx) => {
          return res(
            ctx.status(200),
            ctx.json({ jsonrpc: "2.0", id: 1, result: JSON.parse("{}") }),
          );
        }),
        rest.get("http://localhost:6006/get_config", (req, res, ctx) => {
          return res(
            ctx.status(200),
            ctx.json({ jsonrpc: "2.0", id: 1, result: JSON.parse("{}") }),
          );
        }),
        rest.post("/get_config", (req, res, ctx) => {
          return res(
            ctx.status(200),
            ctx.json({ jsonrpc: "2.0", id: 1, result: JSON.parse("{}") }),
          );
        }),
        rest.post("http://localhost:6006/get_config", (req, res, ctx) => {
          return res(
            ctx.status(200),
            ctx.json({ jsonrpc: "2.0", id: 1, result: JSON.parse("{}") }),
          );
        }),
      ],
    },
    loaders: [mswLoader],
  },
};

dependency

    "@storybook/addon-essentials": "^7.4.0",
    "@storybook/addon-interactions": "^7.4.0",
    "@storybook/addon-links": "^7.4.0",
    "@storybook/blocks": "^7.4.0",
    "@storybook/nextjs": "^7.4.0",
    "@storybook/react": "^7.4.0",
@hiromaily
Copy link
Author

workaround is I added the below code in my component

  const server = getWorker();
  server.use(...handlers);

@conradogarciaberrotaran

Having the same issue, thank you @hiromaily for the workaround.

@conradogarciaberrotaran

Actually, it would be better to be able to have different handlers for different stories.
Is there anyway to do this?

@conradogarciaberrotaran

I've found a better solution, I'm now using mswDecorator instead of mswLoader. and it's working fine.

@devlulcas
Copy link

I've found a better solution, I'm now using mswDecorator instead of mswLoader. and it's working fine.

can you share with us how you configuration looks like? I'm having the same problem :(

@conradogarciaberrotaran

Hi!
Just this in my preview:

const preview: Preview = {
  decorators: [ mswDecorator ]
 }

@devlulcas
Copy link

Hi! Just this in my preview:

const preview: Preview = {
  decorators: [ mswDecorator ]
 }

Thank you, it worked for me. Now I'm having a problem with MSW and Vitest (not related to the storybook stuff) but that's a problem for the me of the future :)

@ekeijl
Copy link

ekeijl commented Oct 26, 2023

I'm encountering the same problem and nothing I do seems to work.

My stack:

  • Storybook 7.4.5
  • MSW 1.2.1
  • msw-storybook-addon 1.8.0
  • Yarn 3.5.0 (pnp)

I tried skipping the addon completely and initializing MSW with a debug handler manually.
It always fails, even in fallback mode. It does log the console message from the handler but then the request still fails???

import { graphql, rest, setupWorker } from 'msw';

     loaders: [
		async () => {
			const worker = setupWorker(
				...[
					rest.get('/test', (req, res, ctx) => {
						console.log('REST');
						return res(ctx.status(200), ctx.json({ foo: 'bar' }));
					}),
					graphql.operation((req, res, ctx) => {
						console.log('GQL');
						return res(ctx.data({ foo: 'bar' }));
					}),
				],
			);
			await worker.start({
				serviceWorker: {
					url: '/mockServiceWorker.js',
				},
				onUnhandledRequest(request, print) {
					// Ignore any requests containing "cdn.com" in their URL.
					if (!request.url.href.includes('graphql')) {
						return;
					}

					console.debug(worker);

					// Otherwise, print an unhandled request warning.
					print.warning();
				},
			});
		},
	],

The worker does seem to have the handlers registered correctly

I do get the following response for the REST handler:

{
    "name": "TypeError",
    "message": "response2.headers.all is not a function",
    "stack": "TypeError: response2.headers.all is not a function\n    at Object.transformResponse ("
}

Seems to point to this line of code.

Could there be something wrong?

Edit: if I dig a little deeper, it seems to point to this commit in the headers-polyfill version 3.3.0 package where .all() was removed?

Workaround: Setting the package resolution in package.json for headers-polyfill to 3.2.5 seems to resolve the issue:

	"resolutions": {
		"headers-polyfill": "3.2.5"
	}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants