Skip to content

Commit 6afd7ab

Browse files
authored
feat: createMiddleware reports middleware usage
1 parent d6d4b8f commit 6afd7ab

File tree

3 files changed

+58
-51
lines changed

3 files changed

+58
-51
lines changed

packages/open-next/src/adapters/middleware.ts

Lines changed: 46 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -13,51 +13,51 @@ const resolveOriginResolver = () => {
1313
const openNextParams = globalThis.openNextConfig.middleware;
1414
if (typeof openNextParams?.originResolver === "function") {
1515
return openNextParams.originResolver();
16-
} else {
17-
return Promise.resolve<OriginResolver>({
18-
name: "env",
19-
resolve: async (_path: string) => {
20-
try {
21-
const origin = JSON.parse(
22-
process.env.OPEN_NEXT_ORIGIN ?? "{}",
23-
) as Record<string, Origin>;
24-
for (const [key, value] of Object.entries(
25-
globalThis.openNextConfig.functions ?? {},
26-
).filter(([key]) => key !== "default")) {
27-
if (
28-
value.patterns.some((pattern) => {
29-
// Convert cloudfront pattern to regex
30-
return new RegExp(
31-
// transform glob pattern to regex
32-
"/" +
33-
pattern
34-
.replace(/\*\*/g, "(.*)")
35-
.replace(/\*/g, "([^/]*)")
36-
.replace(/\//g, "\\/")
37-
.replace(/\?/g, "."),
38-
).test(_path);
39-
})
40-
) {
41-
debug("Using origin", key, value.patterns);
42-
return origin[key];
43-
}
44-
}
45-
if (_path.startsWith("/_next/image") && origin["imageOptimizer"]) {
46-
debug("Using origin", "imageOptimizer", _path);
47-
return origin["imageOptimizer"];
48-
}
49-
if (origin["default"]) {
50-
debug("Using default origin", origin["default"], _path);
51-
return origin["default"];
16+
}
17+
18+
return Promise.resolve<OriginResolver>({
19+
name: "env",
20+
resolve: async (_path: string) => {
21+
try {
22+
const origin = JSON.parse(
23+
process.env.OPEN_NEXT_ORIGIN ?? "{}",
24+
) as Record<string, Origin>;
25+
for (const [key, value] of Object.entries(
26+
globalThis.openNextConfig.functions ?? {},
27+
).filter(([key]) => key !== "default")) {
28+
if (
29+
value.patterns.some((pattern) => {
30+
// Convert cloudfront pattern to regex
31+
return new RegExp(
32+
// transform glob pattern to regex
33+
"/" +
34+
pattern
35+
.replace(/\*\*/g, "(.*)")
36+
.replace(/\*/g, "([^/]*)")
37+
.replace(/\//g, "\\/")
38+
.replace(/\?/g, "."),
39+
).test(_path);
40+
})
41+
) {
42+
debug("Using origin", key, value.patterns);
43+
return origin[key];
5244
}
53-
return false as const;
54-
} catch (e) {
55-
error("Error while resolving origin", e);
56-
return false as const;
5745
}
58-
},
59-
});
60-
}
46+
if (_path.startsWith("/_next/image") && origin["imageOptimizer"]) {
47+
debug("Using origin", "imageOptimizer", _path);
48+
return origin["imageOptimizer"];
49+
}
50+
if (origin["default"]) {
51+
debug("Using default origin", origin["default"], _path);
52+
return origin["default"];
53+
}
54+
return false as const;
55+
} catch (e) {
56+
error("Error while resolving origin", e);
57+
return false as const;
58+
}
59+
},
60+
});
6161
};
6262

6363
globalThis.internalFetch = fetch;
@@ -93,10 +93,10 @@ const defaultHandler = async (internalEvent: InternalEvent) => {
9393
origin,
9494
isISR: result.isISR,
9595
};
96-
} else {
97-
debug("Middleware response", result);
98-
return result;
9996
}
97+
98+
debug("Middleware response", result);
99+
return result;
100100
};
101101

102102
export const handler = await createGenericHandler({

packages/open-next/src/build/createMiddleware.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ import { type MiddlewareManifest } from "../types/next-types.js";
66
import { buildEdgeBundle } from "./edge/createEdgeBundle.js";
77
import * as buildHelper from "./helper.js";
88

9+
/**
10+
* Compiles the middleware bundle.
11+
*
12+
* @param options Build Options.
13+
* @returns Whether the app uses a Middleware.
14+
*/
915
export async function createMiddleware(options: buildHelper.BuildOptions) {
1016
logger.info(`Bundling middleware function...`);
1117

@@ -21,7 +27,7 @@ export async function createMiddleware(options: buildHelper.BuildOptions) {
2127

2228
const entry = middlewareManifest.middleware["/"];
2329
if (!entry) {
24-
return;
30+
return { useMiddleware: false };
2531
}
2632

2733
// Create output folder
@@ -70,4 +76,6 @@ export async function createMiddleware(options: buildHelper.BuildOptions) {
7076
onlyBuildOnce: true,
7177
});
7278
}
79+
80+
return { useMiddleware: true };
7381
}

packages/open-next/src/converters/aws-cloudfront.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -149,12 +149,9 @@ async function convertToCloudFrontRequestResult(
149149
result: InternalResult | MiddlewareEvent,
150150
originalRequest: CloudFrontRequestEvent,
151151
): Promise<CloudFrontRequestResult> {
152-
let responseHeaders =
153-
result.type === "middleware"
154-
? result.internalEvent.headers
155-
: result.headers;
156152
if (result.type === "middleware") {
157153
const { method, clientIp, origin } = originalRequest.Records[0].cf.request;
154+
const responseHeaders = result.internalEvent.headers;
158155

159156
// Handle external rewrite
160157
if (result.isExternalRewrite) {
@@ -215,6 +212,7 @@ async function convertToCloudFrontRequestResult(
215212
}
216213

217214
const body = await fromReadableStream(result.body, result.isBase64Encoded);
215+
const responseHeaders = result.headers;
218216

219217
const response: CloudFrontRequestResult = {
220218
status: result.statusCode.toString(),
@@ -223,6 +221,7 @@ async function convertToCloudFrontRequestResult(
223221
bodyEncoding: result.isBase64Encoded ? "base64" : "text",
224222
body,
225223
};
224+
226225
debug(response);
227226
return response;
228227
}

0 commit comments

Comments
 (0)