0

I've been trying to setup Mock Service Worker in my NextJS 15 app (App Router) and faced problems with my client workers. Here are my files with setupWorker/setupServer: @src/shared/api/mocks/server.ts - mocks on server

import { setupServer } from "msw/node"
import { storiesHandlers } from "./handlers/story"

export const server = setupServer(...storiesHandlers)

@src/shared/api/mocks/browser.ts - mocks on client

import { setupWorker } from "msw/browser"
import { storiesHandlers } from "./handlers/story"

export const worker = setupWorker(...storiesHandlers)

I apply server.listen in my app/layout.ts file and it works fine:

import type { Metadata } from "next"
import "./globals.css"
import { Providers } from "@/src/app"
import { server } from "@/src/shared/api/mocks/server"

export const metadata: Metadata = {
   title: "Create Next App",
   description: "Generated by create next app",
}

server.listen()

export default function RootLayout({
   children,
}: Readonly<{
   children: React.ReactNode
}>) {
   return (
      <html lang="en">
         <body>
            <Providers>{children}</Providers>
         </body>
      </html>
   )
}

But wherever i tried to configure worker.start(), it simply refused to work (it gave a 404 error when trying to execute a request or threw an error msw that the worker is installed in a server environment) Moreover, when i change the code and the request starts again, the data is visible for a couple of seconds, that is, the worker itself is configured poorly, it just does not have time to install before the request.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.