Skip to content

Commit 39f3b4b

Browse files
fix: ensure newly-created middleware works (#1558)
* fix: ensure newly-created midldeware works * fix: set output format for middleware * fix: compile js and ts separately Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
1 parent 279db6e commit 39f3b4b

File tree

2 files changed

+13
-14
lines changed

2 files changed

+13
-14
lines changed

packages/runtime/src/helpers/dev.ts

+9-12
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,14 @@ export const onPreDev: OnPreBuild = async ({ constants, netlifyConfig }) => {
2727
console.log('Watching for changes in Next.js middleware...')
2828
}
2929
// Eventually we might want to do this via esbuild's API, but for now the CLI works fine
30-
const childProcess = execa(`esbuild`, [
31-
`--bundle`,
32-
`--outdir=${resolve('.netlify')}`,
33-
`--format=esm`,
34-
'--watch',
35-
// Watch for both, because it can have either ts or js
36-
resolve(base, 'middleware.ts'),
37-
resolve(base, 'middleware.js'),
38-
])
39-
40-
childProcess.stdout.pipe(process.stdout)
41-
childProcess.stderr.pipe(process.stderr)
30+
31+
const common = [`--bundle`, `--outdir=${resolve('.netlify')}`, `--format=esm`, `--target=esnext`, '--watch']
32+
33+
// TypeScript
34+
execa(`esbuild`, [...common, resolve(base, 'middleware.ts')], { all: true }).all.pipe(process.stdout)
35+
36+
// JavaScript
37+
execa(`esbuild`, [...common, resolve(base, 'middleware.js')], { all: true }).all.pipe(process.stdout)
38+
4239
// Don't return the promise because we don't want to wait for the child process to finish
4340
}

packages/runtime/src/templates/edge/next-dev.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const exists = async (relativePath) => {
1919
throw error
2020
}
2121
}
22+
let idx = 0
2223

2324
const handler = async (req, context) => {
2425
// Uncomment when CLI update lands
@@ -34,8 +35,9 @@ const handler = async (req, context) => {
3435
// because that would also throw if there's an error in the middleware,
3536
// which we would want to surface not ignore.
3637
if (await exists('../../middleware.js')) {
37-
// These will be user code
38-
const nextMiddleware = await import('../../middleware.js')
38+
// We need to cache-bust the import because otherwise it will claim it
39+
// doesn't exist if the user creates it after the server starts
40+
const nextMiddleware = await import(`../../middleware.js#${idx++}`)
3941
middleware = nextMiddleware.middleware
4042
} else {
4143
// No middleware, so we silently return

0 commit comments

Comments
 (0)