Unverified Commit cc684d02 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Add export runtime test for pages and fully remove experimental.runtime (#48630)

### What 

`export const runtime = 'experimental-edge'` also work for pages. This
PR add tests for that.

Closes NEXT-426

Follow up for #46631 that to fully remove all related code of the
`experimental.runtime`
parent 682fb27a
......@@ -312,8 +312,8 @@ function warnAboutUnsupportedValue(
* Related discussion: https://github.com/vercel/next.js/discussions/34179
*/
export async function getPageStaticInfo(params: {
nextConfig: Partial<NextConfig>
pageFilePath: string
nextConfig: Partial<NextConfig>
isDev?: boolean
page?: string
pageType: 'pages' | 'app' | 'root'
......@@ -382,11 +382,10 @@ export async function getPageStaticInfo(params: {
const isAnAPIRoute = isAPIRoute(page?.replace(/^(?:\/src)?\/pages\//, '/'))
resolvedRuntime = isEdgeRuntime(resolvedRuntime)
? resolvedRuntime
: requiresServerRuntime
? resolvedRuntime || nextConfig.experimental?.runtime
: undefined
resolvedRuntime =
isEdgeRuntime(resolvedRuntime) || requiresServerRuntime
? resolvedRuntime
: undefined
if (resolvedRuntime === SERVER_RUNTIME.experimentalEdge) {
warnAboutExperimentalEdge(isAnAPIRoute ? page! : null)
......@@ -425,6 +424,6 @@ export async function getPageStaticInfo(params: {
ssr: false,
ssg: false,
rsc: RSC_MODULE_TYPES.server,
runtime: nextConfig.experimental?.runtime,
runtime: undefined,
}
}
......@@ -705,7 +705,10 @@ export default async function getBaseWebpackConfig(
const enableTypedRoutes = !!config.experimental.typedRoutes && hasAppDir
if (isClient) {
if (isEdgeRuntime(config.experimental.runtime)) {
if (
// @ts-expect-error: experimental.runtime is deprecated
isEdgeRuntime(config.experimental.runtime)
) {
Log.warn(
'You are using `experimental.runtime` which was removed. Check https://nextjs.org/docs/api-routes/edge-api-routes on how to use edge runtime.'
)
......
import { NextConfig } from './config'
import type { JSONSchemaType } from 'ajv'
import { VALID_LOADERS } from '../shared/lib/image-config'
import { SERVER_RUNTIME } from '../lib/constants'
const configSchema = {
type: 'object',
......@@ -373,11 +372,6 @@ const configSchema = {
minimum: 0,
type: 'number',
},
runtime: {
// automatic typing doesn't like enum
enum: Object.values(SERVER_RUNTIME) as any,
type: 'string',
},
serverComponentsExternalPackages: {
items: {
type: 'string',
......
......@@ -6,7 +6,6 @@ import {
ImageConfigComplete,
imageConfigDefault,
} from '../shared/lib/image-config'
import { ServerRuntime } from 'next/types'
import { SubresourceIntegrityAlgorithm } from '../build/webpack/plugins/subresource-integrity-plugin'
import { WEB_VITALS } from '../shared/lib/utils'
import type { NextParsedUrlQuery } from './request-meta'
......@@ -195,7 +194,6 @@ export interface ExperimentalConfig {
craCompat?: boolean
esmExternals?: boolean | 'loose'
isrMemoryCacheSize?: number
runtime?: Exclude<ServerRuntime, undefined>
fullySpecified?: boolean
urlImports?: NonNullable<webpack.Configuration['experiments']>['buildHttp']
outputFileTracingRoot?: string
......@@ -662,7 +660,6 @@ export const defaultConfig: NextConfig = {
fetchCacheKeyPrefix: '',
middlewarePrefetch: 'flexible',
optimisticClientCache: true,
runtime: undefined,
manualClientBasePath: false,
legacyBrowsers: false,
newNextLinkBehavior: true,
......
......@@ -2,6 +2,4 @@ export default function page() {
return 'edge-ssr'
}
export const config = {
runtime: 'experimental-edge',
}
export const runtime = 'experimental-edge'
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'app-dir global edge configuration',
{
files: __dirname,
skipDeployment: true,
},
({ next }) => {
it('should handle edge only routes', async () => {
const html = await next.render('/app-edge')
expect(html).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"]
}
......@@ -2,4 +2,4 @@ export default function Page() {
return <p>pages-edge-ssr</p>
}
export const config = { runtime: 'experimental-edge' }
export const runtime = 'experimental-edge'
export const config = {
runtime: 'edge',
}
export const runtime = 'experimental-edge'
export default (req) => {
return Response.json(Object.fromEntries(req.headers.entries()), {
......
......@@ -2,6 +2,4 @@ export default function api(req) {
return new Response('hello')
}
export const config = {
runtime: 'edge',
}
export const runtime = 'edge'
......@@ -2,7 +2,7 @@ import B from 'node:buffer'
import B2 from 'buffer'
import { NextResponse } from 'next/server'
export const config = { runtime: 'edge' }
export const runtime = 'edge'
/**
* @param {Request} req
......
export const config = { runtime: 'edge' }
export const runtime = 'edge'
import cookies from '../../../cookies'
......
export const config = { runtime: 'experimental-edge' }
import cookies from '../../../cookies'
export const runtime = 'edge'
export default async function handler() {
const headers = new Headers()
for (const cookie of cookies) {
......
......@@ -157,9 +157,6 @@ if (isNextProd) {
}`,
},
nextConfig: {
experimental: {
runtime: 'nodejs',
},
webpack(config, { nextRuntime }) {
const path = require('path')
const fs = require('fs')
......
......@@ -3,7 +3,4 @@ module.exports = {
loader: 'custom',
loaderFile: './dummy-loader.js',
},
experimental: {
runtime: 'experimental-edge',
},
}
module.exports = {
// reactStrictMode: true,
experimental: {
// runtime: 'experimental-edge',
},
reactStrictMode: true,
images: {
deviceSizes: [480, 1024, 1600, 2000],
imageSizes: [16, 32, 48, 64],
......
......@@ -2,65 +2,24 @@
import { join } from 'path'
import {
File,
findPort,
killApp,
launchApp,
renderViaHTTP,
hasRedbox,
getRedboxHeader,
runDevSuite,
runProdSuite,
} from 'next-test-utils'
import { File, renderViaHTTP, runDevSuite, runProdSuite } from 'next-test-utils'
import concurrent from './concurrent'
import basics from './basics'
import strictMode from './strict-mode'
import webdriver from 'next-webdriver'
const appDir = join(__dirname, '../app')
const nextConfig = new File(join(appDir, 'next.config.js'))
const invalidPage = new File(join(appDir, 'pages/invalid.js'))
const indexPage = new File(join(appDir, 'pages/index.js'))
describe('Basics', () => {
runTests('default setting with react 18', basics)
})
// React 18 with Strict Mode enabled might cause double invocation of lifecycle methods.
describe('Strict mode - dev', () => {
const context = { appDir }
beforeAll(async () => {
nextConfig.replace('// reactStrictMode: true,', 'reactStrictMode: true,')
context.appPort = await findPort()
context.server = await launchApp(context.appDir, context.appPort)
})
afterAll(() => {
nextConfig.restore()
killApp(context.server)
})
strictMode(context)
})
function runTestsAgainstRuntime(runtime) {
runTests(
`Concurrent mode in the ${runtime} runtime`,
(context, env) => {
concurrent(context, (p, q) => renderViaHTTP(context.appPort, p, q))
if (env === 'dev') {
it('should recover after undefined exported as default', async () => {
const browser = await webdriver(context.appPort, '/invalid')
expect(await hasRedbox(browser, true)).toBe(true)
expect(await getRedboxHeader(browser)).toMatch(
`Error: The default export is not a React Component in page: "/invalid"`
)
})
}
strictMode(context)
it('should not have invalid config warning', async () => {
await renderViaHTTP(context.appPort, '/')
......@@ -69,23 +28,12 @@ function runTestsAgainstRuntime(runtime) {
},
{
beforeAll: (env) => {
if (env === 'dev') {
invalidPage.write(`export const value = 1`)
}
nextConfig.replace(
"// runtime: 'experimental-edge'",
`runtime: '${runtime}'`
)
indexPage.replace(
"// runtime: 'experimental-edge'",
`runtime: '${runtime}'`
)
},
afterAll: (env) => {
if (env === 'dev') {
invalidPage.delete()
}
nextConfig.restore()
indexPage.restore()
},
}
......
module.exports = {
// reactStrictMode: true,
// onDemandEntries: {
// maxInactiveAge: 1000 * 60 * 60,
// },
// pageExtensions: ['js', 'ts', 'jsx'], // .tsx won't be treat as page,
experimental: {
runtime: 'nodejs',
},
}
import { Suspense } from 'react'
let result
let promise
function Data() {
if (result) return result
if (!promise)
promise = new Promise((res) => {
setTimeout(() => {
result = 'next_streaming_data'
res()
}, 500)
})
throw promise
}
export default function Page() {
return (
<Suspense fallback="next_streaming_fallback">
<Data />
</Suspense>
)
}
export const runtime = 'experimental-edge'
......@@ -22,6 +22,7 @@ export default function Page() {
)
}
// Use config export
export const config = {
runtime: 'experimental-edge',
}
......@@ -12,11 +12,10 @@ export default function Page500() {
const appDir = join(__dirname, '../app')
const error500Page = new File(join(appDir, 'pages/500.js'))
const nextConfig = new File(join(appDir, 'next.config.js'))
const edgeRuntimeBasicSuite = {
const testSuite = {
runTests: (context, env) => {
const options = { runtime: 'experimental-edge', env }
const options = { env }
streaming(context, options)
},
beforeAll: () => {
......@@ -27,21 +26,5 @@ const edgeRuntimeBasicSuite = {
},
}
const nodejsRuntimeBasicSuite = {
runTests: (context, env) => {
const options = { runtime: 'nodejs', env }
streaming(context, options)
},
beforeAll: () => {
error500Page.write(page500)
},
afterAll: () => {
error500Page.delete()
nextConfig.restore()
},
}
runDevSuite('Node.js runtime', appDir, nodejsRuntimeBasicSuite)
runProdSuite('Node.js runtime', appDir, nodejsRuntimeBasicSuite)
runDevSuite('Edge runtime', appDir, edgeRuntimeBasicSuite)
runProdSuite('Edge runtime', appDir, edgeRuntimeBasicSuite)
runDevSuite('streaming dev', appDir, testSuite)
runProdSuite('streaming prod', appDir, testSuite)
......@@ -22,33 +22,38 @@ async function resolveStreamResponse(response, onData) {
return result
}
export default function (context, { env, runtime }) {
export default function (context, { env }) {
it('should support streaming for fizz response', async () => {
await fetchViaHTTP(context.appPort, '/streaming', null, {}).then(
async (response) => {
let gotFallback = false
let gotData = false
async function testStreamingResponse(pathname) {
await fetchViaHTTP(context.appPort, pathname, null, {}).then(
async (response) => {
let gotFallback = false
let gotData = false
await resolveStreamResponse(response, (_, result) => {
gotData = result.includes('next_streaming_data')
if (!gotFallback) {
gotFallback = result.includes('next_streaming_fallback')
if (gotFallback) {
expect(gotData).toBe(false)
await resolveStreamResponse(response, (_, result) => {
gotData = result.includes('next_streaming_data')
if (!gotFallback) {
gotFallback = result.includes('next_streaming_fallback')
if (gotFallback) {
expect(gotData).toBe(false)
}
}
}
})
})
// Streaming is disabled for pages, no fallback should be rendered.
expect(gotFallback).toBe(false)
expect(gotData).toBe(true)
}
)
// Streaming is disabled for pages, no fallback should be rendered.
expect(gotFallback).toBe(false)
expect(gotData).toBe(true)
}
)
// Should end up with "next_streaming_data".
const browser = await webdriver(context.appPort, '/streaming')
const content = await browser.eval(`window.document.body.innerText`)
expect(content).toMatchInlineSnapshot('"next_streaming_data"')
// Should end up with "next_streaming_data".
const browser = await webdriver(context.appPort, pathname)
const content = await browser.eval(`window.document.body.innerText`)
expect(content).toMatchInlineSnapshot('"next_streaming_data"')
}
await testStreamingResponse('/streaming')
await testStreamingResponse('/streaming-single-export')
})
it('should not stream to crawlers or google pagerender bot', async () => {
......@@ -84,10 +89,8 @@ export default function (context, { env, runtime }) {
// Resolve data instead of fallback
expect(body.text()).toBe('next_streaming_data')
if (runtime === 'nodejs') {
expect(res1.headers.get('etag')).toBeDefined()
expect(res2.headers.get('etag')).toBeDefined()
}
expect(res1.headers.get('etag')).toBeDefined()
expect(res2.headers.get('etag')).toBeDefined()
})
it('should render 500 error correctly', async () => {
......
......@@ -3,10 +3,8 @@ import { join } from 'path'
const fixtureDir = join(__dirname, 'fixtures')
function createNextConfig(runtime?: 'experimental-edge' | 'nodejs') {
return {
experimental: { runtime },
}
function createNextConfig() {
return {}
}
describe('parse page static info', () => {
......@@ -60,38 +58,3 @@ describe('parse page static info', () => {
expect(ssg).toBe(false)
})
})
describe('fallback to the global runtime configuration', () => {
it('should fallback when gSP is defined and exported', async () => {
const { runtime, ssr, ssg } = await getPageStaticInfo({
pageFilePath: join(fixtureDir, 'page-runtime/fallback-with-gsp.js'),
nextConfig: createNextConfig('experimental-edge'),
pageType: 'pages',
})
expect(runtime).toBe('experimental-edge')
expect(ssr).toBe(false)
expect(ssg).toBe(true)
})
it('should fallback when gSP is re-exported from other module', async () => {
const { runtime, ssr, ssg } = await getPageStaticInfo({
pageFilePath: join(fixtureDir, 'page-runtime/fallback-re-export-gsp.js'),
nextConfig: createNextConfig('experimental-edge'),
pageType: 'pages',
})
expect(runtime).toBe('experimental-edge')
expect(ssr).toBe(false)
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