rsnext/packages/next/build/webpack/loaders/next-middleware-loader.ts
Javi Velasco c497b3a5ff
Improve deprecation errors for new middleware API (#30316)
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Steven <steven@ceriously.com>
2021-10-26 17:03:39 +02:00

34 lines
929 B
TypeScript

import loaderUtils from 'next/dist/compiled/loader-utils'
export type MiddlewareLoaderOptions = {
absolutePagePath: string
page: string
}
export default function middlewareLoader(this: any) {
const { absolutePagePath, page }: MiddlewareLoaderOptions =
loaderUtils.getOptions(this)
const stringifiedPagePath = loaderUtils.stringifyRequest(
this,
absolutePagePath
)
return `
import { adapter } from 'next/dist/server/web/adapter'
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,
})
}
`
}