Unverified Commit 6dc85796 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

fix edge runtime asset fetch in pages api (#76750)

### What

We discoved an issue that fetch new URL with static assets in Pages API on edge runtime were failing. Located the issue was an introduced in #66534 where we changed the layer of Pages API with edge runtime entries into API layer, where it actually should be another separate layer like middleware.

The quick fix is using middleware bundle layer for Pages API edge functions, but middleware is server-only layer which Pages API is not yet, since it doesn't bundle everything and picking up the `react-server` condition. So we have to create a new layer `apiEdge` to minimize the behavior changes and also fix the bug.

The test suite was disabled due to node-fetch blocker, but we now we can enable it.

Closes NDX-941
Fixes #74385 
[slack-ref](https://vercel.slack.com/archives/C07CGAA2RS6/p1740868643335099)
parent ead6e95f
......@@ -424,7 +424,10 @@ export function getEdgeServerEntry(opts: {
).toString('base64'),
}
return `next-edge-function-loader?${stringify(loaderParams)}!`
return {
import: `next-edge-function-loader?${stringify(loaderParams)}!`,
layer: WEBPACK_LAYERS.apiEdge,
}
}
const loaderParams: EdgeSSRLoaderQuery = {
......@@ -876,7 +879,7 @@ export function finalizeEntrypoint({
switch (compilerType) {
case COMPILER_NAMES.server: {
const layer = isApi
? WEBPACK_LAYERS.api
? WEBPACK_LAYERS.apiNode
: isInstrumentation
? WEBPACK_LAYERS.instrument
: isServerComponent
......@@ -895,7 +898,7 @@ export function finalizeEntrypoint({
case COMPILER_NAMES.edgeServer: {
return {
layer: isApi
? WEBPACK_LAYERS.api
? WEBPACK_LAYERS.apiEdge
: isMiddlewareFilename(name) || isInstrumentation
? WEBPACK_LAYERS.middleware
: name.startsWith('pages/')
......
......@@ -645,7 +645,7 @@ export default async function getBaseWebpackConfig(
const apiRoutesLayerLoaders = useSWCLoader
? getSwcLoader({
serverComponents: false,
bundleLayer: WEBPACK_LAYERS.api,
bundleLayer: WEBPACK_LAYERS.apiNode,
})
: defaultLoaders.babel
......@@ -1575,15 +1575,20 @@ export default async function getBaseWebpackConfig(
oneOf: [
{
...codeCondition,
issuerLayer: WEBPACK_LAYERS.api,
issuerLayer: WEBPACK_LAYERS.apiNode,
use: apiRoutesLayerLoaders,
// In Node.js, switch back to normal URL handling.
// We won't bundle `new URL()` cases in Node.js bundler layer.
parser: {
// In Node.js, switch back to normal URL handling.
// In Edge runtime, we should disable parser.url handling in webpack so URLDependency is not added.
// Then there's browser code won't be injected into the edge runtime chunk.
// x-ref: https://github.com/webpack/webpack/blob/d9ce3b1f87e63c809d8a19bbd92257d65922e81f/lib/web/JsonpChunkLoadingRuntimeModule.js#L69
url: !isEdgeServer,
url: true,
},
},
{
...codeCondition,
issuerLayer: WEBPACK_LAYERS.apiEdge,
use: apiRoutesLayerLoaders,
// In Edge runtime, we leave the url handling by default.
// The new URL assets will be converted into edge assets through assets loader.
},
{
test: codeCondition.test,
......
......@@ -279,7 +279,7 @@ function buildWebpackError({
function isInMiddlewareLayer(parser: webpack.javascript.JavascriptParser) {
const layer = parser.state.module?.layer
return layer === WEBPACK_LAYERS.middleware || layer === WEBPACK_LAYERS.api
return layer === WEBPACK_LAYERS.middleware || layer === WEBPACK_LAYERS.apiEdge
}
function isNodeJsModule(moduleName: string) {
......@@ -868,7 +868,7 @@ export async function handleWebpackExternalForEdgeRuntime({
}) {
if (
(contextInfo.issuerLayer === WEBPACK_LAYERS.middleware ||
contextInfo.issuerLayer === WEBPACK_LAYERS.api) &&
contextInfo.issuerLayer === WEBPACK_LAYERS.apiEdge) &&
isNodeJsModule(request) &&
!supportedEdgePolyfills.has(request)
) {
......
......@@ -118,9 +118,13 @@ const WEBPACK_LAYERS_NAMES = {
*/
actionBrowser: 'action-browser',
/**
* The layer for the API routes.
* The Node.js bundle layer for the API routes.
*/
api: 'api',
apiNode: 'api-node',
/**
* The Edge Lite bundle layer for the API routes.
*/
apiEdge: 'api-edge',
/**
* The layer for the middleware code.
*/
......@@ -169,7 +173,8 @@ const WEBPACK_LAYERS = {
],
neutralTarget: [
// pages api
WEBPACK_LAYERS_NAMES.api,
WEBPACK_LAYERS_NAMES.apiNode,
WEBPACK_LAYERS_NAMES.apiEdge,
],
clientOnly: [
WEBPACK_LAYERS_NAMES.serverSideRendering,
......
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { fetchViaHTTP, renderViaHTTP } from 'next-test-utils'
import path from 'path'
import { promises as fs } from 'fs'
import { readJson } from 'fs-extra'
// TODO: `node-fetch` hangs on some of these tests in Node.js.
// Re-enable when `node-fetch` is dropped.
// See: https://github.com/vercel/next.js/pull/55112
describe.skip('Edge Compiler can import asset assets', () => {
let next: NextInstance
// TODO: remove after this is supported for deploy
if ((global as any).isNextDeploy) {
it('should skip for deploy for now', () => {})
return
}
beforeAll(async () => {
next = await createNext({
files: new FileRef(path.join(__dirname, './app')),
})
describe('Edge Compiler can import asset assets', () => {
const { next, isTurbopack, isNextDeploy } = nextTestSetup({
files: path.join(__dirname, './app'),
})
afterAll(() => next.destroy())
it('allows to fetch a remote URL', async () => {
const response = await fetchViaHTTP(next.url, '/api/edge', {
......@@ -66,33 +51,63 @@ describe.skip('Edge Compiler can import asset assets', () => {
})
})
it('extracts all the assets from the bundle', async () => {
const manifestPath = path.join(
next.testDir,
'.next/server/middleware-manifest.json'
)
const manifest = await readJson(manifestPath)
const orderedAssets = manifest.functions['/api/edge'].assets.sort(
(a, z) => {
return String(a.name).localeCompare(z.name)
}
)
// Cannot read the file on deployment
if (!isNextDeploy) {
it('extracts all the assets from the bundle', async () => {
const manifestPath = path.join(
next.testDir,
'.next/server/middleware-manifest.json'
)
const manifest = await readJson(manifestPath)
const orderedAssets = manifest.functions['/api/edge'].assets.sort(
(a, z) => {
return String(a.name).localeCompare(z.name)
}
)
expect(orderedAssets).toMatchObject([
{
name: expect.stringMatching(/^text-file\.[0-9a-f]{16}\.txt$/),
filePath: expect.stringMatching(
/^server\/edge-chunks\/asset_text-file/
),
},
{
name: expect.stringMatching(/^vercel\.[0-9a-f]{16}\.png$/),
filePath: expect.stringMatching(/^server\/edge-chunks\/asset_vercel/),
},
{
name: expect.stringMatching(/^world\.[0-9a-f]{16}\.json/),
filePath: expect.stringMatching(/^server\/edge-chunks\/asset_world/),
},
])
})
if (isTurbopack) {
expect(orderedAssets).toMatchObject([
{
name: expect.stringMatching(
/server\/edge\/assets\/text-file\.[0-9a-f]{8}\.txt$/
),
filePath: expect.stringMatching(/^server\/edge\/assets\/text-file/),
},
{
name: expect.stringMatching(
/^server\/edge\/assets\/vercel\.[0-9a-f]{8}\.png$/
),
filePath: expect.stringMatching(/^server\/edge\/assets\/vercel/),
},
{
name: expect.stringMatching(
/^server\/edge\/assets\/world\.[0-9a-f]{8}\.json/
),
filePath: expect.stringMatching(/^server\/edge\/assets\/world/),
},
])
} else {
expect(orderedAssets).toMatchObject([
{
name: expect.stringMatching(/^text-file\.[0-9a-f]{16}\.txt$/),
filePath: expect.stringMatching(
/^server\/edge-chunks\/asset_text-file/
),
},
{
name: expect.stringMatching(/^vercel\.[0-9a-f]{16}\.png$/),
filePath: expect.stringMatching(
/^server\/edge-chunks\/asset_vercel/
),
},
{
name: expect.stringMatching(/^world\.[0-9a-f]{16}\.json/),
filePath: expect.stringMatching(
/^server\/edge-chunks\/asset_world/
),
},
])
}
})
}
})
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