Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions examples/app-pages-router/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

// Needed to test top-level await
// @ts-expect-error - It will cause a warning at build time, but it should just work
const topLevelAwait = await new Promise<string>((resolve) => {
setTimeout(() => {
resolve("top-level-await");
}, 150);
Copy link
Contributor

Choose a reason for hiding this comment

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

Interesting - does it have to have a timeout? Would await Promise.resolve('top-level-await') work w/o the timeout?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Not necessarily, it should work with Promise.resolve. I just wanted to emulate some wait time and be sure that we are not running on the same loop of the event loop.
We can probably make it 5 or 10 ms, no need for 150

});

export function middleware(request: NextRequest) {
const path = request.nextUrl.pathname; //new URL(request.url).pathname;

Expand All @@ -25,6 +33,14 @@ export function middleware(request: NextRequest) {
},
});
}
if (path === "/api/middlewareTopLevelAwait") {
return new NextResponse(JSON.stringify({ hello: topLevelAwait }), {
status: 200,
headers: {
"content-type": "application/json",
},
});
}
const rHeaders = new Headers(request.headers);
const r = NextResponse.next({
request: {
Expand Down
6 changes: 6 additions & 0 deletions packages/tests-e2e/tests/appPagesRouter/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,9 @@ test("API call from middleware", async ({ page }) => {
el = page.getByText('API: { "hello": "middleware" }');
await expect(el).toBeVisible();
});

test("API call from middleware with top-level await", async ({ request }) => {
const response = await request.get("/api/middlewareTopLevelAwait");
const data = await response.json();
expect(data).toEqual({ hello: "top-level-await" });
});
Loading