Skip to content

fix: ensure newly-created middleware works #1558

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

Merged
merged 4 commits into from
Aug 18, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
21 changes: 9 additions & 12 deletions packages/runtime/src/helpers/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,14 @@ export const onPreDev: OnPreBuild = async ({ constants, netlifyConfig }) => {
console.log('Watching for changes in Next.js middleware...')
}
// Eventually we might want to do this via esbuild's API, but for now the CLI works fine
const childProcess = execa(`esbuild`, [
`--bundle`,
`--outdir=${resolve('.netlify')}`,
`--format=esm`,
'--watch',
// Watch for both, because it can have either ts or js
resolve(base, 'middleware.ts'),
resolve(base, 'middleware.js'),
])

childProcess.stdout.pipe(process.stdout)
childProcess.stderr.pipe(process.stderr)

const common = [`--bundle`, `--outdir=${resolve('.netlify')}`, `--format=esm`, `--target=esnext`, '--watch']

// TypeScript
execa(`esbuild`, [...common, resolve(base, 'middleware.ts')], { all: true }).all.pipe(process.stdout)

// JavaScript
execa(`esbuild`, [...common, resolve(base, 'middleware.js')], { all: true }).all.pipe(process.stdout)

// Don't return the promise because we don't want to wait for the child process to finish
}
6 changes: 4 additions & 2 deletions packages/runtime/src/templates/edge/next-dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const exists = async (relativePath) => {
throw error
}
}
let idx = 0

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