Next.js Discord

Discord Forum

need help with setuping msw

Unanswered
Aditya Kirad posted this in #help-forum
Open in Discord
Hey folks I want to integrate msw in my Next App to mock the resend API currently I have mock directory inside the src directory and have these files
resend.ts
import { http, HttpResponse, type HttpHandler } from "msw";
import { z } from "zod";

export const handlers: Array<HttpHandler> = [
  http.post(`https://api.resend.com/emails`, async ({ request }) => {
    const headers = request.headers;
    if (!headers.has("Authorization")) {
      const headersString = JSON.stringify(
        Object.fromEntries(headers.entries()),
        null,
        2,
      );
      throw new Error(
        `Header "Authorization" required, but not found in ${headersString}`,
      );
    }
    const body = await request.json();
    console.info("🔶 mocked email contents:", body);

    const email = z
      .object({
        to: z.string(),
        from: z.string(),
        subject: z.string(),
        text: z.string(),
        html: z.string(),
      })
      .parse(body);

    return HttpResponse.json({
      id: crypto.randomUUID(),
      from: email.from,
      to: email.to,
      created_at: new Date().toISOString(),
    });
  }),
];

index.ts
import { setupServer } from "msw/node";
import { handlers as pwnedPasswordHandlers } from "./pwned-password";
import { handlers as resendHandlers } from "./resend";

export const server = setupServer(...pwnedPasswordHandlers, ...resendHandlers);
and then I import the server in the instrumentation.ts file
export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    const { server } = await import("./mock");
    server.listen();
  }
}

but this setup is causing this error
Read more: https://mswjs.io/docs/getting-started/mocks
 ⨯ [Error: [object Object]] { digest: '1669965221' }
 POST /account/register 500 in 1248ms

0 Replies