7c103fac7d
Fixes the problem that global `process` variable has only the `env` field. Also fixed the issue that the `env` field is empty when the `process` module is used as the value of the variable (which happens when the module is contained in a dependency of application). ## Bug - [ ] Related issues linked using `fixes #number` - [x] Integration tests added - [ ] Errors have helpful link attached, see `contributing.md`
37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
import { stringifyRequest } from '../stringify-request'
|
|
|
|
export type MiddlewareLoaderOptions = {
|
|
absolutePagePath: string
|
|
page: string
|
|
}
|
|
|
|
export default function middlewareLoader(this: any) {
|
|
const { absolutePagePath, page }: MiddlewareLoaderOptions = this.getOptions()
|
|
const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
|
|
|
|
return `
|
|
import { adapter } from 'next/dist/server/web/adapter'
|
|
|
|
// The condition is true when the "process" module is provided
|
|
if (process !== global.process) {
|
|
// prefer local process but global.process has correct "env"
|
|
process.env = global.process.env;
|
|
global.process = process;
|
|
}
|
|
|
|
var mod = require(${stringifiedPagePath})
|
|
var handler = mod.middleware || mod.default;
|
|
|
|
if (typeof handler !== 'function') {
|
|
throw new Error('The Middleware "pages${page}" must export a \`middleware\` or a \`default\` function');
|
|
}
|
|
|
|
export default function (opts) {
|
|
return adapter({
|
|
...opts,
|
|
page: ${JSON.stringify(page)},
|
|
handler,
|
|
})
|
|
}
|
|
`
|
|
}
|