rsnext/packages/next/build/webpack/loaders/next-middleware-loader.ts
Javi Velasco a815ba9f79
Implement Middleware RFC (#30081)
This PR adds support for [Middleware as per RFC ](https://github.com/vercel/next.js/discussions/29750). 

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes
2021-10-20 17:52:11 +00:00

33 lines
883 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,
handler
})
}
`
}