I am using nextjs-auth0, I am controlling authentication with Middleware, I am writing test code for Middleware in Vites, but in edge-client (oauth4webapi?) of nextjs-auth0, ES Modules? error. Is there any workaround?
middleware.ts
import { withMiddlewareAuthRequired } from "@auth0/nextjs-auth0/edge";
import {
type NextFetchEvent,
type NextRequest,
NextResponse,
} from "next/server";
export default function (request: NextRequest, event: NextFetchEvent) {
const { pathname } = new URL(request.url);
if (/^\/protect(\/|$)/.test(pathname)) {
return withMiddlewareAuthRequired()(request, event);
}
return NextResponse.next();
}
middleware.test.ts
// @vitest-environment edge-runtime
import { middleware } from "@/middleware";
import { FetchEvent } from "next/dist/compiled/@edge-runtime/primitives";
import { type NextFetchEvent, NextRequest } from "next/server";
import { expect, test, vi } from "vitest";
test("Auth0 middleware", async () => {
const request = new NextRequest("http://localhost:3000/protect");
const event = new FetchEvent(request);
const response = await middleware(
request,
event as unknown as NextFetchEvent,
);
expect(response?.status).toBe(401);
});
vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
alias: {
"@/": new URL("./src/", import.meta.url).pathname,
},
},
});
Error
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
FAIL test/middleware.test.ts [ test/middleware.test.ts ]
Error: require() of ES Module /Users/zaru/Sites/nextjs-middleware/node_modules/oauth4webapi/build/index.js from /Users/zaru/Sites/nextjs-middleware/node_modules/@auth0/nextjs-auth0/dist/auth0-session/client/edge-client.js not supported.
Instead change the require of index.js in /Users/zaru/Sites/nextjs-middleware/node_modules/@auth0/nextjs-auth0/dist/auth0-session/client/edge-client.js to a dynamic import() which is available in all CommonJS modules.
❯ Object.<anonymous> node_modules/@auth0/nextjs-auth0/dist/auth0-session/client/edge-client.js:5:36
❯ Object.<anonymous> node_modules/@auth0/nextjs-auth0/dist/edge.js:7:23
❯ async /Users/zaru/Sites/nextjs-middleware/src/middlewares/hofMiddleware.ts:2:31
❯ async /Users/zaru/Sites/nextjs-middleware/test/middleware.test.ts:1:31
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { code: 'ERR_REQUIRE_ESM' }
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯