Unverified Commit 1079c100 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Alias next/server for edge runtime (#50268)

* For edge runtime, map `next/server` to esm assets to get benefit from
tree-shaking
* Mark process.turbo flag as `false` when running with webpack

Closes NEXT-1212

Compare with canary (13.4.4-canary.8)

#### Middleware

##### before vs after
<img width="319" alt="image"
src="https://github.com/vercel/next.js/assets/4800338/ffa3e744-8f14-4c61-9f5a-ccd04b8911f2">
<img width="317" alt="image"
src="https://github.com/vercel/next.js/assets/4800338/fc974a39-49f3-439a-966c-07af3c71db05">



#### Edge route

##### before vs after
<img width="313" alt="image"
src="https://github.com/vercel/next.js/assets/4800338/bea6e7bb-5875-4a6b-899f-94ad6a8df902">

<img width="314" alt="image"
src="https://github.com/vercel/next.js/assets/4800338/1783fb03-b473-496a-bb97-fa613fe58d7a">
parent ed60646a
...@@ -245,6 +245,7 @@ export function getDefineEnv({ ...@@ -245,6 +245,7 @@ export function getDefineEnv({
process.env.NEXT_EDGE_RUNTIME_PROVIDER || 'edge-runtime' process.env.NEXT_EDGE_RUNTIME_PROVIDER || 'edge-runtime'
), ),
}), }),
'process.turbopack': JSON.stringify(false),
// TODO: enforce `NODE_ENV` on `process.env`, and add a test: // TODO: enforce `NODE_ENV` on `process.env`, and add a test:
'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production'), 'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production'),
'process.env.NEXT_RUNTIME': JSON.stringify( 'process.env.NEXT_RUNTIME': JSON.stringify(
...@@ -1039,6 +1040,7 @@ export default async function getBaseWebpackConfig( ...@@ -1039,6 +1040,7 @@ export default async function getBaseWebpackConfig(
'next/dist/shared': 'next/dist/esm/shared', 'next/dist/shared': 'next/dist/esm/shared',
'next/dist/pages': 'next/dist/esm/pages', 'next/dist/pages': 'next/dist/esm/pages',
'next/dist/lib': 'next/dist/esm/lib', 'next/dist/lib': 'next/dist/esm/lib',
'next/dist/server': 'next/dist/esm/server',
// Alias the usage of next public APIs // Alias the usage of next public APIs
[require.resolve('next/dist/client/link')]: [require.resolve('next/dist/client/link')]:
...@@ -1058,9 +1060,9 @@ export default async function getBaseWebpackConfig( ...@@ -1058,9 +1060,9 @@ export default async function getBaseWebpackConfig(
[require.resolve('next/dist/pages/_app')]: [require.resolve('next/dist/pages/_app')]:
'next/dist/esm/pages/_app', 'next/dist/esm/pages/_app',
[require.resolve('next/dist/client/components/navigation')]: [require.resolve('next/dist/client/components/navigation')]:
'next/dist/client/components/navigation', 'next/dist/esm/client/components/navigation',
[require.resolve('next/dist/client/components/headers')]: [require.resolve('next/dist/client/components/headers')]:
'next/dist/client/components/headers', 'next/dist/esm/client/components/headers',
} }
: undefined), : undefined),
......
...@@ -31,12 +31,12 @@ const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoade ...@@ -31,12 +31,12 @@ const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoade
return ` return `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter' import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
import {IncrementalCache} from 'next/dist/esm/server/lib/incremental-cache' import { IncrementalCache } from 'next/dist/esm/server/lib/incremental-cache'
enhanceGlobals() enhanceGlobals()
var mod = require(${stringifiedPagePath}) const mod = require(${stringifiedPagePath})
var handler = mod.middleware || mod.default; const handler = mod.middleware || mod.default
if (typeof handler !== 'function') { if (typeof handler !== 'function') {
throw new Error('The Edge Function "pages${page}" must export a \`default\` function'); throw new Error('The Edge Function "pages${page}" must export a \`default\` function');
......
...@@ -96,7 +96,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -96,7 +96,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
const transformed = ` const transformed = `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter' import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
import { getRender } from 'next/dist/esm/build/webpack/loaders/next-edge-ssr-loader/render' import { getRender } from 'next/dist/esm/build/webpack/loaders/next-edge-ssr-loader/render'
import {IncrementalCache} from 'next/dist/esm/server/lib/incremental-cache' import { IncrementalCache } from 'next/dist/esm/server/lib/incremental-cache'
enhanceGlobals() enhanceGlobals()
......
...@@ -57,7 +57,7 @@ export default async function transformSource( ...@@ -57,7 +57,7 @@ export default async function transformSource(
if (clientRefs.includes('*')) { if (clientRefs.includes('*')) {
return callback( return callback(
new Error( new Error(
`It's currently unsupport to use "export *" in a client boundary. Please use named exports instead.` `It's currently unsupported to use "export *" in a client boundary. Please use named exports instead.`
) )
) )
} }
......
...@@ -17,10 +17,14 @@ let api: typeof import('next/dist/compiled/@opentelemetry/api') ...@@ -17,10 +17,14 @@ let api: typeof import('next/dist/compiled/@opentelemetry/api')
// @opentelemetry/tracing that is used, and we don't want to force users to use // @opentelemetry/tracing that is used, and we don't want to force users to use
// the version that is bundled with Next.js. // the version that is bundled with Next.js.
// the API is ~stable, so this should be fine // the API is ~stable, so this should be fine
try { if (process.env.NEXT_RUNTIME === 'edge') {
api = require('@opentelemetry/api') api = require('@opentelemetry/api')
} catch (err) { } else {
api = require('next/dist/compiled/@opentelemetry/api') try {
api = require('@opentelemetry/api')
} catch (err) {
api = require('next/dist/compiled/@opentelemetry/api')
}
} }
const { context, trace, SpanStatusCode, SpanKind } = api const { context, trace, SpanStatusCode, SpanKind } = api
......
export * from 'next/dist/compiled/@edge-runtime/cookies' export {
RequestCookies,
ResponseCookies,
} from 'next/dist/compiled/@edge-runtime/cookies'
import { NextResponse } from 'next/server'
export async function GET() {
return new NextResponse('hello app route')
}
export const runtime = 'edge'
import { NextResponse } from 'next/server'
export async function GET() {
return new NextResponse('hello app route')
}
...@@ -36,7 +36,7 @@ createNextDescribe( ...@@ -36,7 +36,7 @@ createNextDescribe(
buildCommand: 'yarn build', buildCommand: 'yarn build',
skipDeployment: true, skipDeployment: true,
}, },
({ next }) => { ({ next, isNextDev }) => {
it('should be able to opt-out 3rd party packages being bundled in server components', async () => { it('should be able to opt-out 3rd party packages being bundled in server components', async () => {
await next.fetch('/react-server/optout').then(async (response) => { await next.fetch('/react-server/optout').then(async (response) => {
const result = await resolveStreamResponse(response) const result = await resolveStreamResponse(response)
...@@ -188,7 +188,7 @@ createNextDescribe( ...@@ -188,7 +188,7 @@ createNextDescribe(
expect(html).toContain('Foo') expect(html).toContain('Foo')
}) })
if ((global as any).isNextDev) { if (isNextDev) {
it('should error for wildcard exports of client module references in esm', async () => { it('should error for wildcard exports of client module references in esm', async () => {
const page = 'app/esm-client-ref/page.js' const page = 'app/esm-client-ref/page.js'
const pageSource = await next.readFile(page) const pageSource = await next.readFile(page)
...@@ -207,7 +207,7 @@ createNextDescribe( ...@@ -207,7 +207,7 @@ createNextDescribe(
} }
expect(next.cliOutput).toInclude( expect(next.cliOutput).toInclude(
`It's currently unsupport to use "export *" in a client boundary. Please use named exports instead.` `It's currently unsupported to use "export *" in a client boundary. Please use named exports instead.`
) )
}) })
} }
......
import { createResponse } from 'cjs-lib' import { createResponse } from 'cjs-lib'
import { respond } from 'compat-next-server-module'
export function middleware(request) { export async function middleware(request) {
if (request.nextUrl.pathname === '/test-middleware') { if (request.nextUrl.pathname === '/test-middleware') {
return createResponse('it works') return createResponse('it works')
} }
return await respond()
} }
const { NextResponse } = require('next/server')
exports.respond = function () {
return NextResponse.next()
}
import { NextResponse } from 'next/server'
export function respond() {
return NextResponse.next()
}
{
"exports": {
".": {
"import": "./index.mjs",
"require": "./index.js",
"default": "./index.js"
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment