rsnext/packages/next/build/webpack/loaders/next-edge-function-loader.ts
Gal Schlezinger b62bb97b6f
Re-introduce Edge API Endpoints (#37481)
* Re-introduce Edge API Endpoints

This reverts commit 210fa39961, and
re-introduces Edge API endpoints as a possible runtime selection in API
endpoints.

This is done by exporting a `config` object:

```ts
export config = { runtime: 'edge' }
```

Note: `'edge'` will probably change into `'experimental-edge'` to show
that this is experimental and the API might change in the future.

* Support `experimental-edge`, but allow `edge` too

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-06-13 11:17:44 -07:00

43 lines
1.3 KiB
TypeScript

import { getModuleBuildInfo } from './get-module-build-info'
import { stringifyRequest } from '../stringify-request'
export type EdgeFunctionLoaderOptions = {
absolutePagePath: string
page: string
}
export default function middlewareLoader(this: any) {
const { absolutePagePath, page }: EdgeFunctionLoaderOptions =
this.getOptions()
const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const buildInfo = getModuleBuildInfo(this._module)
buildInfo.nextEdgeApiFunction = {
page: page || '/',
}
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 Edge Function "pages${page}" must export a \`default\` function');
}
export default function (opts) {
return adapter({
...opts,
page: ${JSON.stringify(page)},
handler,
})
}
`
}