Unverified Commit 088c19f7 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Correct server reference manifest in prod build (#46683)

Since we have 2 server compilers (node and edge), the `serverActions`
object will always get overridden by the second compilation during `next
build`. Like the client reference manifest, we need to have 2 objects
for each compiler and merge them when outputting the asset.

Besides that, to avoid `export default` being tree-shaken as unused
export, I changed the loader to use CJS `module.exports` instead. Can't
easily figure out a proper way for now but we plan to create separate
worker for the action endpoint and this will be gone then.

Fixes NEXT-759, read NEXT-761 for the full future plan.

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## 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`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 605f7e0e
......@@ -3,6 +3,7 @@ import type { AppBuildManifest } from './webpack/plugins/app-build-manifest-plug
import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
import type { NextConfigComplete } from '../server/config-shared'
import type { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import type { ActionManifest } from './webpack/plugins/flight-client-entry-plugin'
import '../lib/setup-exception-listeners'
import { loadEnvConfig } from '@next/env'
......@@ -1320,6 +1321,22 @@ export default async function build(
MIDDLEWARE_MANIFEST
))
const actionManifest = appDir
? (require(path.join(
distDir,
SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST + '.json'
)) as ActionManifest)
: null
const entriesWithAction = actionManifest ? new Set() : null
if (actionManifest && entriesWithAction) {
for (const id in actionManifest) {
for (const entry in actionManifest[id].workers) {
entriesWithAction.add(entry)
}
}
}
for (const key of Object.keys(middlewareManifest?.functions)) {
if (key.startsWith('/api')) {
edgeRuntimePagesCount++
......@@ -1458,6 +1475,14 @@ export default async function build(
isStatic = false
isSsg = false
} else {
// If a page has action and it is static, we need to
// change it to SSG to keep the worker created.
// TODO: This is a workaround for now, we should have a
// dedicated worker defined in a heuristic way.
const hasAction = entriesWithAction?.has(
'app' + originalAppPath
)
if (
workerResult.encodedPrerenderRoutes &&
workerResult.prerenderRoutes
......@@ -1475,7 +1500,7 @@ export default async function build(
}
const appConfig = workerResult.appConfig || {}
if (workerResult.appConfig?.revalidate !== 0) {
if (appConfig.revalidate !== 0 && !hasAction) {
const isDynamic = isDynamicRoute(page)
const hasGenerateStaticParams =
!!workerResult.prerenderRoutes?.length
......
......@@ -28,10 +28,13 @@ ${actionList
.join('\n')}
}
export default async function endpoint(id, bound) {
async function endpoint(id, bound) {
const action = await actions[id]()
return action.apply(null, bound)
}
// Using "export default" will cause this to be tree-shaken away due to unused exports.
module.exports = endpoint
`
}
......
......@@ -52,6 +52,8 @@ export type ActionManifest = {
const pluginState = getProxiedPluginState({
// A map to track "action" -> "list of bundles".
serverActions: {} as ActionManifest,
edgeServerActions: {} as ActionManifest,
actionModId: {} as Record<string, string | number>,
// Manifest of CSS entry files for server/edge server.
serverCSSManifest: {} as FlightCSSManifest,
......@@ -283,6 +285,12 @@ export class FlightClientEntryPlugin {
)
// Create action entry
if (this.isEdgeServer) {
pluginState.edgeServerActions = {}
} else {
pluginState.serverActions = {}
}
if (actionEntryImports.size > 0) {
addActionEntryList.push(
this.injectActionEntry({
......@@ -698,15 +706,18 @@ export class FlightClientEntryPlugin {
actions: JSON.stringify(actionsArray),
})}!`
let currentCompilerServerActions = this.isEdgeServer
? pluginState.serverActions
: pluginState.edgeServerActions
for (const [p, names] of actionsArray) {
for (const name of names) {
const id = generateActionId(p, name)
if (typeof pluginState.serverActions[id] === 'undefined') {
pluginState.serverActions[id] = {
if (typeof currentCompilerServerActions[id] === 'undefined') {
currentCompilerServerActions[id] = {
workers: {},
}
}
pluginState.serverActions[id].workers[bundlePath] = ''
currentCompilerServerActions[id].workers[bundlePath] = ''
}
}
......@@ -760,8 +771,6 @@ export class FlightClientEntryPlugin {
compilation: webpack.Compilation,
assets: webpack.Compilation['assets']
) {
const actionModId: Record<string, string | number> = {}
traverseModules(compilation, (mod, _chunk, chunkGroup, modId) => {
// Go through all action entries and record the module ID for each entry.
if (
......@@ -769,19 +778,23 @@ export class FlightClientEntryPlugin {
mod.request &&
/next-flight-action-entry-loader/.test(mod.request)
) {
actionModId[chunkGroup.name] = modId
pluginState.actionModId[chunkGroup.name] = modId
}
})
for (let id in pluginState.serverActions) {
const action = pluginState.serverActions[id]
const fullServerActions = {
...pluginState.serverActions,
...pluginState.edgeServerActions,
}
for (let id in fullServerActions) {
const action = fullServerActions[id]
for (let name in action.workers) {
action.workers[name] = actionModId[name]
action.workers[name] = pluginState.actionModId[name]
}
}
const json = JSON.stringify(
pluginState.serverActions,
fullServerActions,
null,
this.dev ? 2 : undefined
)
......
......@@ -1713,7 +1713,7 @@ export async function renderToHTMLOrFlight(
const actionData = (await parseBody(req, '1mb')) || {}
const actionHandler =
ComponentMod.__next_app_webpack_require__(actionModId).default
ComponentMod.__next_app_webpack_require__(actionModId)
try {
return new ActionRenderResult(
......
......@@ -7,32 +7,35 @@ createNextDescribe(
files: __dirname,
skipDeployment: true,
},
({ next, isNextDev }) => {
if (!isNextDev) {
it('should create the server reference manifest', async () => {
const content = await next.readFile(
'.next/server/server-reference-manifest.json'
)
// Make sure it's valid JSON
JSON.parse(content)
expect(content.length > 0).toBeTrue()
})
}
({ next }) => {
it('should handle basic actions correctly', async () => {
const browser = await next.browser('/server')
// TODO: Ensure this works in production.
if (isNextDev) {
it('should handle basic actions correctly', async () => {
const browser = await next.browser('/server')
const cnt = await browser.elementByCss('h1').text()
expect(cnt).toBe('0')
const cnt = await browser.elementByCss('h1').text()
expect(cnt).toBe('0')
await browser.elementByCss('#inc').click()
await check(() => browser.elementByCss('h1').text(), '1')
await browser.elementByCss('#inc').click()
await check(() => browser.elementByCss('h1').text(), '1')
await browser.elementByCss('#dec').click()
await check(() => browser.elementByCss('h1').text(), '0')
})
await browser.elementByCss('#dec').click()
await check(() => browser.elementByCss('h1').text(), '0')
})
}
it('should support headers and cookies', async () => {
const browser = await next.browser('/header')
await browser.elementByCss('#cookie').click()
await check(async () => {
const res = (await browser.elementByCss('h1').text()) || ''
const id = res.split(':')
return id[0] === id[1] && id[0] ? 'same' : 'different'
}, 'same')
await browser.elementByCss('#header').click()
await check(async () => {
const res = (await browser.elementByCss('h1').text()) || ''
return res.includes('Mozilla') ? 'UA' : ''
}, 'UA')
})
}
)
'use server'
import { headers, cookies } from 'next/headers'
export async function getCookie(name) {
return cookies().get(name)
}
export async function getHeader(name) {
return headers().get(name)
}
import UI from './ui'
import { getCookie, getHeader } from './actions'
export default function Page() {
return <UI getCookie={getCookie} getHeader={getHeader} />
}
'use client'
import { useState } from 'react'
export default function UI({ getCookie, getHeader }) {
const [result, setResult] = useState('')
return (
<div>
<h1>{result}</h1>
<button
id="cookie"
onClick={async () => {
// set cookie
const random = Math.random()
document.cookie = `random=${random}`
const res = await getCookie('random')
setResult(random + ':' + res.value)
}}
>
getCookie
</button>
<button
id="header"
onClick={async () => {
const res = await getHeader('User-Agent')
setResult(res)
}}
>
getHeader
</button>
</div>
)
}
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