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

Better support for cloudflare external middleware #449

Merged
merged 7 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
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
7 changes: 6 additions & 1 deletion packages/open-next/src/adapters/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,12 @@ const resolveOriginResolver = () => {
return origin[key];
}
}
if (_path.startsWith("/_next/image") && origin["imageOptimizer"]) {
debug("Using origin", "imageOptimizer", _path);
return origin["imageOptimizer"];
}
if (origin["default"]) {
debug("Using default origin", origin["default"]);
debug("Using default origin", origin["default"], _path);
return origin["default"];
}
return false as const;
Expand All @@ -65,6 +69,7 @@ const defaultHandler = async (internalEvent: InternalEvent) => {
internalEvent: result.internalEvent,
isExternalRewrite: result.isExternalRewrite,
origin,
isISR: result.isISR,
};
} else {
debug("Middleware response", result);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const preprocessResult: MiddlewareOutputEvent = {
internalEvent: internalEvent,
isExternalRewrite: false,
origin: false,
isISR: false,
};
//#endOverride

Expand Down
6 changes: 5 additions & 1 deletion packages/open-next/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,11 @@ async function createMiddleware() {
fs.mkdirSync(outputPath, { recursive: true });

// Copy open-next.config.mjs
copyOpenNextConfig(options.tempDir, outputPath);
copyOpenNextConfig(
options.tempDir,
outputPath,
config.middleware.override?.wrapper === "cloudflare",
);

// Bundle middleware
await buildEdgeBundle({
Expand Down
16 changes: 13 additions & 3 deletions packages/open-next/src/converters/edge.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Buffer } from "node:buffer";

import { parseCookies } from "http/util";
import { Converter, InternalEvent, InternalResult } from "types/open-next";

Expand Down Expand Up @@ -28,13 +30,15 @@ const converter: Converter<
headers[key] = value;
});
const rawPath = new URL(event.url).pathname;
const method = event.method;
const shouldHaveBody = method !== "GET" && method !== "HEAD";

return {
type: "core",
method: event.method,
method,
rawPath,
url: event.url,
body: event.method !== "GET" ? Buffer.from(body) : undefined,
body: shouldHaveBody ? Buffer.from(body) : undefined,
headers: headers,
remoteAddress: (event.headers.get("x-forwarded-for") as string) ?? "::1",
query,
Expand Down Expand Up @@ -68,7 +72,13 @@ const converter: Converter<
},
});

return fetch(req);
const cfCache = result.isISR ? { cacheEverything: true } : {};

return fetch(req, {
// This is a hack to make sure that the response is cached by Cloudflare
// @ts-expect-error - This is a Cloudflare specific option
conico974 marked this conversation as resolved.
Show resolved Hide resolved
cf: cfCache,
});
} else {
const headers = new Headers();
for (const [key, value] of Object.entries(result.headers)) {
Expand Down
1 change: 1 addition & 0 deletions packages/open-next/src/core/requestHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export async function openNextHandler(
internalEvent: internalEvent,
isExternalRewrite: false,
origin: false,
isISR: false,
};
try {
preprocessResult = await routingHandler(internalEvent);
Expand Down
25 changes: 16 additions & 9 deletions packages/open-next/src/core/routing/matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ export function fixDataPage(
export function handleFallbackFalse(
internalEvent: InternalEvent,
prerenderManifest: PrerenderManifest,
): InternalEvent {
): { event: InternalEvent; isISR: boolean } {
const { rawPath } = internalEvent;
const { dynamicRoutes, routes } = prerenderManifest;
const routeFallback = Object.entries(dynamicRoutes)
Expand All @@ -365,17 +365,24 @@ export function handleFallbackFalse(
const localizedPath = routesAlreadyHaveLocale
? rawPath
: `/${NextConfig.i18n?.defaultLocale}${rawPath}`;
if (routeFallback && !Object.keys(routes).includes(localizedPath)) {
const isPregenerated = Object.keys(routes).includes(localizedPath);
if (routeFallback && !isPregenerated) {
return {
...internalEvent,
rawPath: "/404",
url: "/404",
headers: {
...internalEvent.headers,
"x-invoke-status": "404",
event: {
...internalEvent,
rawPath: "/404",
url: "/404",
headers: {
...internalEvent.headers,
"x-invoke-status": "404",
},
},
isISR: false,
};
}

return internalEvent;
return {
event: internalEvent,
isISR: routeFallback || isPregenerated,
};
}
11 changes: 10 additions & 1 deletion packages/open-next/src/core/routingHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export interface MiddlewareOutputEvent {
internalEvent: InternalEvent;
isExternalRewrite: boolean;
origin: Origin | false;
isISR: boolean;
}

const staticRegexp = RoutesManifest.routes.static.map(
Expand Down Expand Up @@ -84,7 +85,11 @@ export default async function routingHandler(
}

// We want to run this just before the dynamic route check
internalEvent = handleFallbackFalse(internalEvent, PrerenderManifest);
const { event: fallbackEvent, isISR } = handleFallbackFalse(
internalEvent,
PrerenderManifest,
);
internalEvent = fallbackEvent;

const isDynamicRoute =
!isExternalRewrite &&
Expand All @@ -108,6 +113,8 @@ export default async function routingHandler(
internalEvent.rawPath === "/api" ||
internalEvent.rawPath.startsWith("/api/");

const isNextImageRoute = internalEvent.rawPath.startsWith("/_next/image");

const isRouteFoundBeforeAllRewrites =
isStaticRoute || isDynamicRoute || isExternalRewrite;

Expand All @@ -116,6 +123,7 @@ export default async function routingHandler(
if (
!isRouteFoundBeforeAllRewrites &&
!isApiRoute &&
!isNextImageRoute &&
// We need to check again once all rewrites have been applied
!staticRegexp.some((route) =>
route.test((internalEvent as InternalEvent).rawPath),
Expand Down Expand Up @@ -154,5 +162,6 @@ export default async function routingHandler(
internalEvent,
isExternalRewrite,
origin: false,
isISR,
};
}
2 changes: 1 addition & 1 deletion packages/open-next/src/wrappers/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const handler: WrapperHandler<

const response = await handler(internalEvent);

const result: Response = converter.convertTo(response);
const result: Response = await converter.convertTo(response);

return result;
};
Expand Down
Loading