forked from vercel/next.js
/
next-edge-function-loader.ts
40 lines (33 loc) · 1.13 KB
/
next-edge-function-loader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { getModuleBuildInfo } from './get-module-build-info'
import { stringifyRequest } from '../stringify-request'
export type EdgeFunctionLoaderOptions = {
absolutePagePath: string
page: string
rootDir: string
}
export default function middlewareLoader(this: any) {
const { absolutePagePath, page, rootDir }: EdgeFunctionLoaderOptions =
this.getOptions()
const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const buildInfo = getModuleBuildInfo(this._module)
buildInfo.nextEdgeApiFunction = {
page: page || '/',
}
buildInfo.rootDir = rootDir
return `
import { adapter, enhanceGlobals } from 'next/dist/server/web/adapter'
enhanceGlobals()
var mod = require(${stringifiedPagePath})
var handler = mod.middleware || mod.default;
if (typeof handler !== 'function') {
throw new Error('The Edge Function "pages${page}" must export a \`default\` function');
}
export default function (opts) {
return adapter({
...opts,
page: ${JSON.stringify(page)},
handler,
})
}
`
}