Skip to content

Commit cf33973

Browse files
authored
fix(middleware): always compiles the middleware (#604)
1 parent 8624ae9 commit cf33973

File tree

8 files changed

+58
-81
lines changed

8 files changed

+58
-81
lines changed

.changeset/angry-cougars-tap.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@opennextjs/aws": patch
3+
---
4+
5+
fix(middleware): always compiles the middleware.
6+
7+
Prior to this PR the middleware would only be compiled when a middleware.ts exists.

packages/open-next/src/adapters/plugins/README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
### Known issues
1+
# Known issues
22

3-
Do not include `types` in #override and #imports, as esbuild will remove preceeding comments (ie it removes //#override id)when it builds.
3+
Do not include `types` in #override and #imports, as esbuild will remove preceding comments (ie it removes //#override id)when it builds.
44

55
Instead, put the `import type` outside like:
66

7-
```
7+
```ts
88
import type { PluginHandler } from "../next-types.js";
99
import type { IncomingMessage } from "../request.js";
1010
import type { ServerResponse } from "../response.js";

packages/open-next/src/adapters/plugins/without-routing/requestHandler.ts

Lines changed: 0 additions & 18 deletions
This file was deleted.

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

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ import fs from "node:fs";
22
import path from "node:path";
33

44
import logger from "../logger.js";
5-
import { type MiddlewareManifest } from "../types/next-types.js";
5+
import {
6+
type MiddlewareInfo,
7+
type MiddlewareManifest,
8+
} from "../types/next-types.js";
69
import { buildEdgeBundle } from "./edge/createEdgeBundle.js";
710
import * as buildHelper from "./helper.js";
811
import { installDependencies } from "./installDeps.js";
@@ -11,7 +14,6 @@ import { installDependencies } from "./installDeps.js";
1114
* Compiles the middleware bundle.
1215
*
1316
* @param options Build Options.
14-
* @returns Whether the app uses a Middleware.
1517
*/
1618
export async function createMiddleware(options: buildHelper.BuildOptions) {
1719
logger.info(`Bundling middleware function...`);
@@ -26,15 +28,9 @@ export async function createMiddleware(options: buildHelper.BuildOptions) {
2628
),
2729
) as MiddlewareManifest;
2830

29-
const entry = middlewareManifest.middleware["/"];
30-
if (!entry) {
31-
return { useMiddleware: false };
32-
}
33-
34-
const commonMiddlewareOptions = {
35-
middlewareInfo: entry,
36-
options,
37-
};
31+
const middlewareInfo = middlewareManifest.middleware["/"] as
32+
| MiddlewareInfo
33+
| undefined;
3834

3935
if (config.middleware?.external) {
4036
const outputPath = path.join(outputDir, "middleware");
@@ -55,7 +51,8 @@ export async function createMiddleware(options: buildHelper.BuildOptions) {
5551
"middleware.js",
5652
),
5753
outfile: path.join(outputPath, "handler.mjs"),
58-
...commonMiddlewareOptions,
54+
middlewareInfo,
55+
options,
5956
overrides: config.middleware?.override,
6057
defaultConverter: "aws-cloudfront",
6158
includeCache: config.dangerous?.enableCacheInterception,
@@ -71,10 +68,9 @@ export async function createMiddleware(options: buildHelper.BuildOptions) {
7168
"edgeFunctionHandler.js",
7269
),
7370
outfile: path.join(options.buildDir, "middleware.mjs"),
74-
...commonMiddlewareOptions,
71+
middlewareInfo,
72+
options,
7573
onlyBuildOnce: true,
7674
});
7775
}
78-
79-
return { useMiddleware: true };
8076
}

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

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import fs from "node:fs";
2-
import { createRequire } from "node:module";
32
import path from "node:path";
43

54
import type { FunctionOptions, SplittedFunctionOptions } from "types/open-next";
@@ -15,8 +14,6 @@ import { generateEdgeBundle } from "./edge/createEdgeBundle.js";
1514
import * as buildHelper from "./helper.js";
1615
import { installDependencies } from "./installDeps.js";
1716

18-
const require = createRequire(import.meta.url);
19-
2017
export async function createServerBundle(options: buildHelper.BuildOptions) {
2118
const { config } = options;
2219
const foundRoutes = new Set<string>();
@@ -146,10 +143,7 @@ async function generateBundle(
146143
}
147144

148145
// Copy middleware
149-
if (
150-
!config.middleware?.external &&
151-
fs.existsSync(path.join(options.buildDir, "middleware.mjs"))
152-
) {
146+
if (!config.middleware?.external) {
153147
fs.copyFileSync(
154148
path.join(options.buildDir, "middleware.mjs"),
155149
path.join(outputPath, packagePath, "middleware.mjs"),
@@ -191,18 +185,15 @@ async function generateBundle(
191185
buildHelper.compareSemver(options.nextVersion, "14.0.4") >= 0;
192186

193187
const disableRouting = isBefore13413 || config.middleware?.external;
188+
194189
const plugins = [
195190
openNextReplacementPlugin({
196191
name: `requestHandlerOverride ${name}`,
197192
target: /core(\/|\\)requestHandler\.js/g,
198-
deletes: disableNextPrebundledReact ? ["applyNextjsPrebundledReact"] : [],
199-
replacements: disableRouting
200-
? [
201-
require.resolve(
202-
"../adapters/plugins/without-routing/requestHandler.js",
203-
),
204-
]
205-
: [],
193+
deletes: [
194+
...(disableNextPrebundledReact ? ["applyNextjsPrebundledReact"] : []),
195+
...(disableRouting ? ["withRouting"] : []),
196+
],
206197
}),
207198
openNextReplacementPlugin({
208199
name: `utilOverride ${name}`,

packages/open-next/src/build/edge/createEdgeBundle.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import type { BuildOptions } from "../helper.js";
1919
import { copyOpenNextConfig, esbuildAsync } from "../helper.js";
2020

2121
interface BuildEdgeBundleOptions {
22-
middlewareInfo: MiddlewareInfo;
22+
middlewareInfo?: MiddlewareInfo;
2323
entrypoint: string;
2424
outfile: string;
2525
options: BuildOptions;
@@ -158,8 +158,6 @@ globalThis.AsyncLocalStorage = AsyncLocalStorage;
158158
}
159159
}
160160

161-
export function copyMiddlewareAssetsAndWasm({}) {}
162-
163161
export async function generateEdgeBundle(
164162
name: string,
165163
options: BuildOptions,
@@ -191,10 +189,10 @@ export async function generateEdgeBundle(
191189
if (functions.length > 1) {
192190
throw new Error("Only one function is supported for now");
193191
}
194-
const fn = functions[0];
192+
const middlewareInfo = functions[0];
195193

196194
//Copy wasm files
197-
const wasmFiles = fn.wasm;
195+
const wasmFiles = middlewareInfo.wasm;
198196
mkdirSync(path.join(outputPath, "wasm"), { recursive: true });
199197
for (const wasmFile of wasmFiles) {
200198
fs.copyFileSync(
@@ -204,7 +202,7 @@ export async function generateEdgeBundle(
204202
}
205203

206204
// Copy assets
207-
const assets = fn.assets;
205+
const assets = middlewareInfo.assets;
208206
mkdirSync(path.join(outputPath, "assets"), { recursive: true });
209207
for (const asset of assets) {
210208
fs.copyFileSync(
@@ -214,7 +212,7 @@ export async function generateEdgeBundle(
214212
}
215213

216214
await buildEdgeBundle({
217-
middlewareInfo: fn,
215+
middlewareInfo,
218216
entrypoint: path.join(
219217
options.openNextDistDir,
220218
"adapters",

packages/open-next/src/core/requestHandler.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,14 @@ export async function openNextHandler(
3131
}
3232
debug("internalEvent", internalEvent);
3333

34-
//#override withRouting
3534
let preprocessResult: InternalResult | MiddlewareOutputEvent = {
3635
internalEvent: internalEvent,
3736
isExternalRewrite: false,
3837
origin: false,
3938
isISR: false,
4039
};
40+
41+
//#override withRouting
4142
try {
4243
preprocessResult = await routingHandler(internalEvent);
4344
} catch (e) {

packages/open-next/src/plugins/edge.ts

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,14 @@ import {
1818
export interface IPluginSettings {
1919
nextDir: string;
2020
edgeFunctionHandlerPath?: string;
21-
middlewareInfo: MiddlewareInfo;
21+
middlewareInfo?: MiddlewareInfo;
2222
isInCloudfare?: boolean;
2323
}
2424

2525
/**
2626
* @param opts.nextDir - The path to the .next directory
2727
* @param opts.edgeFunctionHandlerPath - The path to the edgeFunctionHandler.js file that we'll use to bundle the routing
28-
* @param opts.entryFiles - The entry files that we'll inject into the edgeFunctionHandler.js file
28+
* @param opts.middlewareInfo - The entry files that we'll inject into the edgeFunctionHandler.js file
2929
* @returns
3030
*/
3131
export function openNextEdgePlugins({
@@ -34,17 +34,19 @@ export function openNextEdgePlugins({
3434
middlewareInfo,
3535
isInCloudfare,
3636
}: IPluginSettings): Plugin {
37-
const entryFiles = middlewareInfo.files.map((file: string) =>
38-
path.join(nextDir, file),
39-
);
40-
const routes = [
41-
{
42-
name: middlewareInfo.name || "/",
43-
page: middlewareInfo.page,
44-
regex: middlewareInfo.matchers.map((m) => m.regexp),
45-
},
46-
];
47-
const wasmFiles = middlewareInfo.wasm ?? [];
37+
const entryFiles =
38+
middlewareInfo?.files.map((file: string) => path.join(nextDir, file)) ?? [];
39+
const routes = middlewareInfo
40+
? [
41+
{
42+
name: middlewareInfo.name || "/",
43+
page: middlewareInfo.page,
44+
regex: middlewareInfo.matchers.map((m) => m.regexp),
45+
},
46+
]
47+
: [];
48+
const wasmFiles = middlewareInfo?.wasm ?? [];
49+
4850
return {
4951
name: "opennext-edge",
5052
setup(build) {
@@ -134,7 +136,7 @@ if(!globalThis.Crypto) {
134136
globalThis.Crypto = webcrypto.Crypto
135137
}
136138
// We also need to polyfill URLPattern
137-
if (!globalThis.URLPattern) {
139+
if (!globalThis.URLPattern) {
138140
await import("urlpattern-polyfill");
139141
}
140142
`
@@ -146,8 +148,8 @@ ${wasmFiles
146148
: `const ${file.name} = readFileSync(path.join(__dirname,'/wasm/${file.name}.wasm'));`,
147149
)
148150
.join("\n")}
149-
${entryFiles?.map((file) => `require("${file}");`).join("\n")}
150-
${contents}
151+
${entryFiles.map((file) => `require("${file}");`).join("\n")}
152+
${contents}
151153
`;
152154
return {
153155
contents,
@@ -166,18 +168,18 @@ ${contents}
166168

167169
const contents = `
168170
import path from "path";
169-
171+
170172
import { debug } from "../logger";
171-
173+
172174
if(!globalThis.__dirname) {
173175
globalThis.__dirname = ""
174176
}
175-
177+
176178
export const NEXT_DIR = path.join(__dirname, ".next");
177179
export const OPEN_NEXT_DIR = path.join(__dirname, ".open-next");
178-
180+
179181
debug({ NEXT_DIR, OPEN_NEXT_DIR });
180-
182+
181183
export const NextConfig = ${JSON.stringify(NextConfig)};
182184
export const BuildId = ${JSON.stringify(BuildId)};
183185
export const HtmlPages = ${JSON.stringify(HtmlPages)};
@@ -188,7 +190,7 @@ ${contents}
188190
export const MiddlewareManifest = ${JSON.stringify(MiddlewareManifest)};
189191
190192
process.env.NEXT_BUILD_ID = BuildId;
191-
193+
192194
`;
193195
return {
194196
contents,

0 commit comments

Comments
 (0)