Skip to content

Commit d17c030

Browse files
authoredJan 9, 2024
fix: preserve functions in patched middleware manifest (#139)
1 parent 6a0e4b1 commit d17c030

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed
 

‎src/build/content/server.ts

+24-12
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,22 @@ export const copyNextServerCode = async (ctx: PluginContext): Promise<void> => {
2020

2121
await Promise.all(
2222
paths.map(async (path: string) => {
23+
const srcPath = join(srcDir, path)
2324
const destPath = join(destDir, path)
2425

2526
// If this is the middleware manifest file, replace it with an empty
2627
// manifest to avoid running middleware again in the server handler.
2728
if (path === 'server/middleware-manifest.json') {
28-
await mkdir(dirname(destPath), { recursive: true })
29-
await writeFile(destPath, getEmptyMiddlewareManifest())
29+
try {
30+
await replaceMiddlewareManifest(srcPath, destPath)
31+
} catch (error) {
32+
throw new Error('Could not patch middleware manifest file', { cause: error })
33+
}
3034

3135
return
3236
}
3337

34-
await cp(join(srcDir, path), destPath, { recursive: true })
38+
await cp(srcPath, destPath, { recursive: true })
3539
}),
3640
)
3741
}
@@ -125,17 +129,25 @@ export const writeTagsManifest = async (ctx: PluginContext): Promise<void> => {
125129
}
126130

127131
/**
128-
* Generates an empty middleware manifest. We don't want to run middleware in
129-
* the server handler, because we'll run it upstream in an edge function. So
130-
* we patch the manifest to make it seem like there's no middleware configured.
132+
* Generates a copy of the middleware manifest without any middleware in it. We
133+
* do this because we'll run middleware in an edge function, and we don't want
134+
* to run it again in the server handler.
131135
*/
132-
const getEmptyMiddlewareManifest = () => {
133-
const manifest = {
134-
sortedMiddleware: [],
136+
const replaceMiddlewareManifest = async (sourcePath: string, destPath: string) => {
137+
await mkdir(dirname(destPath), { recursive: true })
138+
139+
const data = await readFile(sourcePath, 'utf8')
140+
const manifest = JSON.parse(data)
141+
142+
// TODO: Check for `manifest.version` and write an error to the system log
143+
// when we find a value that is not equal to 2. This will alert us in case
144+
// Next.js starts using a new format for the manifest and we're writing
145+
// one with the old version.
146+
const newManifest = {
147+
...manifest,
135148
middleware: {},
136-
functions: {},
137-
version: 2,
138149
}
150+
const newData = JSON.stringify(newManifest)
139151

140-
return JSON.stringify(manifest)
152+
await writeFile(destPath, newData)
141153
}

0 commit comments

Comments
 (0)
Please sign in to comment.