Unverified Commit c8983a6b authored by Shu Ding's avatar Shu Ding Committed by GitHub

Fix page static info extractor for app dir (#42001)

We currently only fallback to the global `runtime` option if the page
actually **needs** a runtime (not statically optimizable). That happens
for SSG (ISR) and SSR for pages/. But for app/, we will always need a
`runtime` to render server components.

Also in this PR, I improved the tests to actually **test** the runtime
to ensure it has `globalThis.EdgeRuntime` so it's not running in the
Node.js runtime
([ref](https://edge-runtime.vercel.app/features/available-apis#addressing-the-runtime)).

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see `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`
- [ ] Integration 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`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 5d2e2783
...@@ -273,8 +273,9 @@ export async function getPageStaticInfo(params: { ...@@ -273,8 +273,9 @@ export async function getPageStaticInfo(params: {
pageFilePath: string pageFilePath: string
isDev?: boolean isDev?: boolean
page?: string page?: string
pageType?: 'pages' | 'app'
}): Promise<PageStaticInfo> { }): Promise<PageStaticInfo> {
const { isDev, pageFilePath, nextConfig, page } = params const { isDev, pageFilePath, nextConfig, page, pageType } = params
const fileContent = (await tryToReadFile(pageFilePath, !isDev)) || '' const fileContent = (await tryToReadFile(pageFilePath, !isDev)) || ''
if ( if (
...@@ -322,10 +323,12 @@ export async function getPageStaticInfo(params: { ...@@ -322,10 +323,12 @@ export async function getPageStaticInfo(params: {
} }
} }
const requiresServerRuntime = ssr || ssg || pageType === 'app'
resolvedRuntime = resolvedRuntime =
SERVER_RUNTIME.edge === resolvedRuntime SERVER_RUNTIME.edge === resolvedRuntime
? SERVER_RUNTIME.edge ? SERVER_RUNTIME.edge
: ssr || ssg : requiresServerRuntime
? resolvedRuntime || nextConfig.experimental?.runtime ? resolvedRuntime || nextConfig.experimental?.runtime
: undefined : undefined
......
...@@ -374,6 +374,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -374,6 +374,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
pageFilePath, pageFilePath,
isDev, isDev,
page, page,
pageType: isInsideAppDir ? 'app' : 'pages',
}) })
const isServerComponent = const isServerComponent =
......
...@@ -1339,6 +1339,7 @@ export default async function build( ...@@ -1339,6 +1339,7 @@ export default async function build(
pagePath pagePath
), ),
nextConfig: config, nextConfig: config,
pageType,
}) })
: undefined : undefined
......
...@@ -600,6 +600,7 @@ export default class HotReloader { ...@@ -600,6 +600,7 @@ export default class HotReloader {
pageFilePath: entryData.absolutePagePath, pageFilePath: entryData.absolutePagePath,
nextConfig: this.config, nextConfig: this.config,
isDev: true, isDev: true,
pageType: isAppPath ? 'app' : 'pages',
}) })
: {} : {}
const isServerComponent = const isServerComponent =
......
...@@ -381,6 +381,7 @@ export default class DevServer extends Server { ...@@ -381,6 +381,7 @@ export default class DevServer extends Server {
nextConfig: this.nextConfig, nextConfig: this.nextConfig,
page: rootFile, page: rootFile,
isDev: true, isDev: true,
pageType: isAppPath ? 'app' : 'pages',
}) })
if (isMiddlewareFile(rootFile)) { if (isMiddlewareFile(rootFile)) {
......
...@@ -630,6 +630,7 @@ export function onDemandEntryHandler({ ...@@ -630,6 +630,7 @@ export function onDemandEntryHandler({
pageFilePath: pagePathData.absolutePagePath, pageFilePath: pagePathData.absolutePagePath,
nextConfig, nextConfig,
isDev: true, isDev: true,
pageType: isInsideAppDir ? 'app' : 'pages',
}) })
const added = new Map<CompilerNameValues, ReturnType<typeof addEntry>>() const added = new Map<CompilerNameValues, ReturnType<typeof addEntry>>()
......
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { renderViaHTTP } from 'next-test-utils'
import path from 'path'
describe('app-dir global edge configuration', () => {
if ((global as any).isNextDeploy) {
it('should skip next deploy for now', () => {})
return
}
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: new FileRef(path.join(__dirname, 'app-edge-global')),
dependencies: {
react: 'latest',
'react-dom': 'latest',
typescript: 'latest',
'@types/react': 'latest',
'@types/node': 'latest',
},
})
})
afterAll(() => next.destroy())
it('should handle edge only routes', async () => {
const appHtml = await renderViaHTTP(next.url, '/app-edge')
expect(appHtml).toContain('<p>Edge!</p>')
})
})
'use client'
// TODO-APP: support typing for useSelectedLayoutSegment
// @ts-ignore
import { useSelectedLayoutSegments } from 'next/navigation'
export default function Layout({ children }: { children: React.ReactNode }) {
// useSelectedLayoutSegment should not be thrown
useSelectedLayoutSegments()
return children
}
export default function Page() {
if ('EdgeRuntime' in globalThis) {
return <p>Edge!</p>
}
return <p>Node!</p>
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
module.exports = {
experimental: {
appDir: true,
runtime: 'experimental-edge',
},
}
{
"compilerOptions": {
"target": "ES6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"paths": {
"@/ui/*": ["ui/*"]
},
"plugins": [
{
"name": "next"
}
]
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
...@@ -27,7 +27,7 @@ describe('app-dir edge SSR', () => { ...@@ -27,7 +27,7 @@ describe('app-dir edge SSR', () => {
it('should handle edge only routes', async () => { it('should handle edge only routes', async () => {
const appHtml = await renderViaHTTP(next.url, '/app-edge') const appHtml = await renderViaHTTP(next.url, '/app-edge')
expect(appHtml).toContain('<p>app-edge-ssr</p>') expect(appHtml).toContain('<p>Edge!</p>')
const pageHtml = await renderViaHTTP(next.url, '/pages-edge') const pageHtml = await renderViaHTTP(next.url, '/pages-edge')
expect(pageHtml).toContain('<p>pages-edge-ssr</p>') expect(pageHtml).toContain('<p>pages-edge-ssr</p>')
...@@ -39,7 +39,7 @@ describe('app-dir edge SSR', () => { ...@@ -39,7 +39,7 @@ describe('app-dir edge SSR', () => {
const content = await next.readFile(pageFile) const content = await next.readFile(pageFile)
// Update rendered content // Update rendered content
const updatedContent = content.replace('app-edge-ssr', 'edge-hmr') const updatedContent = content.replace('Edge!', 'edge-hmr')
await next.patchFile(pageFile, updatedContent) await next.patchFile(pageFile, updatedContent)
await check(async () => { await check(async () => {
const html = await renderViaHTTP(next.url, '/app-edge') const html = await renderViaHTTP(next.url, '/app-edge')
...@@ -51,7 +51,7 @@ describe('app-dir edge SSR', () => { ...@@ -51,7 +51,7 @@ describe('app-dir edge SSR', () => {
await check(async () => { await check(async () => {
const html = await renderViaHTTP(next.url, '/app-edge') const html = await renderViaHTTP(next.url, '/app-edge')
return html return html
}, /app-edge-ssr/) }, /Edge!/)
}) })
} }
}) })
export default function Page() { export default function Page() {
return <p>app-edge-ssr</p> if ('EdgeRuntime' in globalThis) {
return <p>Edge!</p>
}
return <p>Node!</p>
} }
export const runtime = 'experimental-edge' export const runtime = 'experimental-edge'
...@@ -14,6 +14,7 @@ describe('parse page static info', () => { ...@@ -14,6 +14,7 @@ describe('parse page static info', () => {
const { runtime, ssr, ssg } = await getPageStaticInfo({ const { runtime, ssr, ssg } = await getPageStaticInfo({
pageFilePath: join(fixtureDir, 'page-runtime/nodejs-ssr.js'), pageFilePath: join(fixtureDir, 'page-runtime/nodejs-ssr.js'),
nextConfig: createNextConfig(), nextConfig: createNextConfig(),
pageType: 'pages',
}) })
expect(runtime).toBe('nodejs') expect(runtime).toBe('nodejs')
expect(ssr).toBe(true) expect(ssr).toBe(true)
...@@ -24,6 +25,7 @@ describe('parse page static info', () => { ...@@ -24,6 +25,7 @@ describe('parse page static info', () => {
const { runtime, ssr, ssg } = await getPageStaticInfo({ const { runtime, ssr, ssg } = await getPageStaticInfo({
pageFilePath: join(fixtureDir, 'page-runtime/nodejs.js'), pageFilePath: join(fixtureDir, 'page-runtime/nodejs.js'),
nextConfig: createNextConfig(), nextConfig: createNextConfig(),
pageType: 'pages',
}) })
expect(runtime).toBe(undefined) expect(runtime).toBe(undefined)
expect(ssr).toBe(false) expect(ssr).toBe(false)
...@@ -34,6 +36,7 @@ describe('parse page static info', () => { ...@@ -34,6 +36,7 @@ describe('parse page static info', () => {
const { runtime } = await getPageStaticInfo({ const { runtime } = await getPageStaticInfo({
pageFilePath: join(fixtureDir, 'page-runtime/edge.js'), pageFilePath: join(fixtureDir, 'page-runtime/edge.js'),
nextConfig: createNextConfig(), nextConfig: createNextConfig(),
pageType: 'pages',
}) })
expect(runtime).toBe('experimental-edge') expect(runtime).toBe('experimental-edge')
}) })
...@@ -42,6 +45,7 @@ describe('parse page static info', () => { ...@@ -42,6 +45,7 @@ describe('parse page static info', () => {
const { runtime } = await getPageStaticInfo({ const { runtime } = await getPageStaticInfo({
pageFilePath: join(fixtureDir, 'page-runtime/static.js'), pageFilePath: join(fixtureDir, 'page-runtime/static.js'),
nextConfig: createNextConfig(), nextConfig: createNextConfig(),
pageType: 'pages',
}) })
expect(runtime).toBe(undefined) expect(runtime).toBe(undefined)
}) })
...@@ -50,6 +54,7 @@ describe('parse page static info', () => { ...@@ -50,6 +54,7 @@ describe('parse page static info', () => {
const { ssr, ssg } = await getPageStaticInfo({ const { ssr, ssg } = await getPageStaticInfo({
pageFilePath: join(fixtureDir, 'page-runtime/ssr-variable-gssp.js'), pageFilePath: join(fixtureDir, 'page-runtime/ssr-variable-gssp.js'),
nextConfig: createNextConfig(), nextConfig: createNextConfig(),
pageType: 'pages',
}) })
expect(ssr).toBe(true) expect(ssr).toBe(true)
expect(ssg).toBe(false) expect(ssg).toBe(false)
...@@ -61,6 +66,7 @@ describe('fallback to the global runtime configuration', () => { ...@@ -61,6 +66,7 @@ describe('fallback to the global runtime configuration', () => {
const { runtime, ssr, ssg } = await getPageStaticInfo({ const { runtime, ssr, ssg } = await getPageStaticInfo({
pageFilePath: join(fixtureDir, 'page-runtime/fallback-with-gsp.js'), pageFilePath: join(fixtureDir, 'page-runtime/fallback-with-gsp.js'),
nextConfig: createNextConfig('experimental-edge'), nextConfig: createNextConfig('experimental-edge'),
pageType: 'pages',
}) })
expect(runtime).toBe('experimental-edge') expect(runtime).toBe('experimental-edge')
expect(ssr).toBe(false) expect(ssr).toBe(false)
...@@ -71,9 +77,21 @@ describe('fallback to the global runtime configuration', () => { ...@@ -71,9 +77,21 @@ describe('fallback to the global runtime configuration', () => {
const { runtime, ssr, ssg } = await getPageStaticInfo({ const { runtime, ssr, ssg } = await getPageStaticInfo({
pageFilePath: join(fixtureDir, 'page-runtime/fallback-re-export-gsp.js'), pageFilePath: join(fixtureDir, 'page-runtime/fallback-re-export-gsp.js'),
nextConfig: createNextConfig('experimental-edge'), nextConfig: createNextConfig('experimental-edge'),
pageType: 'pages',
}) })
expect(runtime).toBe('experimental-edge') expect(runtime).toBe('experimental-edge')
expect(ssr).toBe(false) expect(ssr).toBe(false)
expect(ssg).toBe(true) expect(ssg).toBe(true)
}) })
it('should always fallback to the global runtime for app', async () => {
const { runtime, ssr, ssg } = await getPageStaticInfo({
pageFilePath: join(fixtureDir, 'page-runtime/static.js'),
nextConfig: createNextConfig('experimental-edge'),
pageType: 'app',
})
expect(runtime).toBe('experimental-edge')
expect(ssr).toBe(false)
expect(ssg).toBe(false)
})
}) })
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