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

add next.js (app directory) example #101

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft

add next.js (app directory) example #101

wants to merge 7 commits into from

Conversation

kettanaito
Copy link
Member

@kettanaito kettanaito commented Jan 22, 2024

Adds a Next.js 14 (App directory ) + MSW usage example.

@kettanaito
Copy link
Member Author

Server-side integration

I got the server-side MSW integration working in Next.js by using the instrumentation hook:

export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { server } = await import('./mocks/node')
    server.listen()
  }
}

This allows MSW to intercept server-side requests Next.js makes.

Downsides

  1. Next seems to evaluate the instrumentation hook once. The import graph it creates will not update if you change mocks/handlers.ts because nothing but the instrumentation hook depends on that import. This means stale mocks until you re-run Next.js/force it re-evaluate the instrumentation hook.

* this module and runs it during the build
* in Node.js. This makes "msw/browser" import to fail.
*/
const { worker } = await import('../mocks/browser')
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Next.js puts this dynamic import from the browser runtime to the Node.js build by moving it to the top of the module.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about fixing like this?

if (typeof window !== 'undefined') {
  const { worker } = await import('../mocks/browser')
  await worker.start()
}

* export conditions and don't try to import "msw/browser" code
* that's clearly marked as client-side only in the app.
*/
if (isServer) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a hack. I'm not sure why webpack has trouble resolving export conditions. I suspect this isn't webpack's fault. Next.js runs a pure client-side component in Node.js during SSR build, which results in webpack thinking those client-side imports must be resolved in Node.js.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kettanaito I think the 'use client' directive is a bit of a misnomer. Components marked with that directive can still be SSR and are by default in Next unless you lazy load with ssr: false. Obviously anything in useEffect would only run on the client, so I'm not sure why the dynamic import you have in the other file is placed in a Node.js runtime. Let me know if I'm missing any context.

Having said that, I pulled this repository down and ran dev and build and both succeeded.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it, thanks for clarifying, @dbk91!

I suspect webpack extracts that import and puts it at the top of the module for whichever optimization. This is a bit odd since import() is a valid JavaScript API in the browser so it can certainly be client-side only.

I know this example succeeds. I've added tests to confirm that and they are passing. But I'm not looking for the first working thing. I'm looking for an integration that'd last and make sense for developers. This one, in its current state, doesn't, as it has a couple of fundamentals problems.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Understood, that makes sense! I totally missed your follow up messages in your original Tweet—I was expecting something non-functional and didn't realize there was extra work to get these tests passing.

Either way, I've been following this for quite some time and appreciate the work you've put into MSW and specifically this integration. My team was using it prior to upgrading to app router and we've sorely missed it, but that's on us for upgrading.

@SalahAdDin
Copy link

SalahAdDin commented Jan 31, 2024

I'm our company we are using this example as a reference.

@mizamelo
Copy link

mizamelo commented Feb 9, 2024

@SalahAdDin

I'm our company we are using this example as a reference.

is it working? I've tried to use, but it's showing these messages below:

Internal error: TypeError: fetch failed

`[MSW] Warning: intercepted a request without a matching request handler:

• POST https://telemetry.nextjs.org/api/v1/record`

carloscuesta added a commit to carloscuesta/carloscuesta.me that referenced this pull request Feb 9, 2024
@SalahAdDin
Copy link

@SalahAdDin

I'm our company we are using this example as a reference.

Is it working? I've tried to use it, but it's showing these messages below:

Internal error: TypeError: fetch failed

`[MSW] Warning: intercepted a request without a matching request handler:

• POST https://telemetry.nextjs.org/api/v1/record`

Not checked it yet, We just set it up.

'use client'
import { useEffect, useState } from 'react'

export function MockProvider({
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about using suspense?

mockProvider.tsx

'use client'

let triggered = false

async function enableApiMocking() {
  const { worker } = await import('../mocks/browser')
  await worker.start()
}

export function MockProvider() {
  if (!triggered) {
    triggered = true
    throw enableApiMocking()
  }

  return null
}

layout.tsx

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

By doing so, we can avoid wrapping children in the mock provider client component.
But I am not sure if this is a good solution.

useEffect Suspense
ss2 ss

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The goal of this is to defer the rendering of the children until the service worker is activated. You are proposing keeping the state internally but I don't see it affecting {children}. So they will render, and if they make any HTTP requests, those will not be intercepted because the worker is not ready yet.

@SalahAdDin
Copy link

@kettanaito I don't know why but MSW is not intercepting page request. The mock is enabled but does not catch any fetch.

@pandeymangg
Copy link

how does playwright work with this? My test makes the actual api call instead of the mocked call

@kettanaito
Copy link
Member Author

@pandeymangg, there should be nothing specific to Playwright here. You enable MSW in your Next.js app, then navigate to it in a Playwright test and perform the actions you need.

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

Successfully merging this pull request may close these issues.

None yet

7 participants