Unverified Commit 35f1a350 authored by Damien Simonin Feugas's avatar Damien Simonin Feugas Committed by GitHub

feat: enables 'edge' as a possible runtime for API routes (#44045)

parent 6aae39c7
...@@ -8,21 +8,6 @@ Next.js has two **server runtimes** where you can render parts of your applicati ...@@ -8,21 +8,6 @@ Next.js has two **server runtimes** where you can render parts of your applicati
By default, Next.js uses the Node.js runtime. [Middleware](https://nextjs.org/docs/advanced-features/middleware) and [Edge API Routes](https://nextjs.org/docs/api-routes/edge-api-routes) use the Edge runtime. By default, Next.js uses the Node.js runtime. [Middleware](https://nextjs.org/docs/advanced-features/middleware) and [Edge API Routes](https://nextjs.org/docs/api-routes/edge-api-routes) use the Edge runtime.
## Global Runtime Option
To configure the runtime for your whole application, you can set the experimental option `runtime` in your `next.config.js` file:
```js
// next.config.js
module.exports = {
experimental: {
runtime: 'experimental-edge', // 'node.js' (default) | experimental-edge
},
}
```
You can detect which runtime you're using by looking at the `process.env.NEXT_RUNTIME` Environment Variable during runtime, and examining the `options.nextRuntime` variable during compilation.
## Page Runtime Option ## Page Runtime Option
On each page, you can optionally export a `runtime` config set to either `'nodejs'` or `'experimental-edge'`: On each page, you can optionally export a `runtime` config set to either `'nodejs'` or `'experimental-edge'`:
...@@ -38,22 +23,21 @@ export const config = { ...@@ -38,22 +23,21 @@ export const config = {
} }
``` ```
When both the per-page runtime and global runtime are set, the per-page runtime overrides the global runtime. If the per-page runtime is _not_ set, the global runtime option will be used.
## Runtime Differences ## Runtime Differences
|   | Node (Server) | Node (Serverless) | Edge | |   | Node (Server) | Node (Serverless) | Edge |
| --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ----------------- | ---------------- | | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ----------------- | -------------------------------------------------------- |
| [Cold Boot](https://vercel.com/docs/concepts/get-started/compute#cold-and-hot-boots?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) | / | ~250ms | Instant | | Name | `nodejs` | `nodejs` | `edge` or `experimental-edge` if using Next.js Rendering |
| HTTP Streaming | Yes | Yes | Yes | | [Cold Boot](https://vercel.com/docs/concepts/get-started/compute#cold-and-hot-boots?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) | / | ~250ms | Instant |
| IO | All | All | `fetch` | | HTTP Streaming | Yes | Yes | Yes |
| Scalability | / | High | Highest | | IO | All | All | `fetch` |
| Security | Normal | High | High | | Scalability | / | High | Highest |
| Latency | Normal | Low | Lowest | | Security | Normal | High | High |
| Code Size | / | 50MB | 1MB | | Latency | Normal | Low | Lowest |
| NPM Packages | All | All | A smaller subset | | Code Size | / | 50 MB | 4 MB |
| NPM Packages | All | All | A smaller subset |
Next.js' default runtime configuration is good for most use cases, but there’re still many reasons to change to one runtime over the other one. Next.js' default runtime configuration is good for most use cases, but there are still many reasons to change to one runtime over the other one.
For example, for API routes that rely on native Node.js APIs, they need to run with the Node.js Runtime. However, if an API only uses something like cookie-based authentication, using Middleware and the Edge Runtime will be a better choice due to its lower latency as well as better scalability. For example, for API routes that rely on native Node.js APIs, they need to run with the Node.js Runtime. However, if an API only uses something like cookie-based authentication, using Middleware and the Edge Runtime will be a better choice due to its lower latency as well as better scalability.
...@@ -63,7 +47,7 @@ For example, for API routes that rely on native Node.js APIs, they need to run w ...@@ -63,7 +47,7 @@ For example, for API routes that rely on native Node.js APIs, they need to run w
```typescript ```typescript
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default (req) => new Response('Hello world!') export default (req) => new Response('Hello world!')
......
...@@ -144,7 +144,7 @@ You can relax the check to allow specific files with your Middleware or Edge API ...@@ -144,7 +144,7 @@ You can relax the check to allow specific files with your Middleware or Edge API
```javascript ```javascript
export const config = { export const config = {
runtime: 'experimental-edge', // for Edge API Routes only runtime: 'edge', // for Edge API Routes only
unstable_allowDynamic: [ unstable_allowDynamic: [
'/lib/utilities.js', // allows a single file '/lib/utilities.js', // allows a single file
'/node_modules/function-bind/**', // use a glob to allow anything in the function-bind 3rd party module '/node_modules/function-bind/**', // use a glob to allow anything in the function-bind 3rd party module
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
description: Edge API Routes enable you to build high performance APIs directly inside your Next.js application. description: Edge API Routes enable you to build high performance APIs directly inside your Next.js application.
--- ---
# Edge API Routes (Beta) # Edge API Routes
Edge API Routes enable you to build high performance APIs with Next.js. Using the [Edge Runtime](/docs/api-reference/edge-runtime.md), they are often faster than Node.js-based API Routes. This performance improvement does come with [constraints](/docs/api-reference/edge-runtime.md#unsupported-apis), like not having access to native Node.js APIs. Instead, Edge API Routes are built on standard Web APIs. Edge API Routes enable you to build high performance APIs with Next.js. Using the [Edge Runtime](/docs/api-reference/edge-runtime.md), they are often faster than Node.js-based API Routes. This performance improvement does come with [constraints](/docs/api-reference/edge-runtime.md#unsupported-apis), like not having access to native Node.js APIs. Instead, Edge API Routes are built on standard Web APIs.
...@@ -14,7 +14,7 @@ Any file inside the folder `pages/api` is mapped to `/api/*` and will be treated ...@@ -14,7 +14,7 @@ Any file inside the folder `pages/api` is mapped to `/api/*` and will be treated
```typescript ```typescript
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default (req) => new Response('Hello world!') export default (req) => new Response('Hello world!')
...@@ -26,7 +26,7 @@ export default (req) => new Response('Hello world!') ...@@ -26,7 +26,7 @@ export default (req) => new Response('Hello world!')
import type { NextRequest } from 'next/server' import type { NextRequest } from 'next/server'
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default async function handler(req: NextRequest) { export default async function handler(req: NextRequest) {
...@@ -50,7 +50,7 @@ export default async function handler(req: NextRequest) { ...@@ -50,7 +50,7 @@ export default async function handler(req: NextRequest) {
import type { NextRequest } from 'next/server' import type { NextRequest } from 'next/server'
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default async function handler(req: NextRequest) { export default async function handler(req: NextRequest) {
...@@ -75,7 +75,7 @@ export default async function handler(req: NextRequest) { ...@@ -75,7 +75,7 @@ export default async function handler(req: NextRequest) {
import type { NextRequest } from 'next/server' import type { NextRequest } from 'next/server'
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default async function handler(req: NextRequest) { export default async function handler(req: NextRequest) {
...@@ -91,7 +91,7 @@ export default async function handler(req: NextRequest) { ...@@ -91,7 +91,7 @@ export default async function handler(req: NextRequest) {
import { type NextRequest } from 'next/server' import { type NextRequest } from 'next/server'
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default async function handler(req: NextRequest) { export default async function handler(req: NextRequest) {
...@@ -131,4 +131,6 @@ Edge API Routes use the [Edge Runtime](/docs/api-reference/edge-runtime.md), whe ...@@ -131,4 +131,6 @@ Edge API Routes use the [Edge Runtime](/docs/api-reference/edge-runtime.md), whe
Edge API Routes can [stream responses](/docs/api-reference/edge-runtime.md#web-stream-apis) from the server and run _after_ cached files (e.g. HTML, CSS, JavaScript) have been accessed. Server-side streaming can help improve performance with faster [Time To First Byte (TTFB)](https://web.dev/ttfb/). Edge API Routes can [stream responses](/docs/api-reference/edge-runtime.md#web-stream-apis) from the server and run _after_ cached files (e.g. HTML, CSS, JavaScript) have been accessed. Server-side streaming can help improve performance with faster [Time To First Byte (TTFB)](https://web.dev/ttfb/).
> Note: Using [Edge Runtime](/docs/api-reference/edge-runtime.md) with `getServerSideProps` does not give you access to the response object. If you need access to `res`, you should use the [Node.js runtime](/docs/advanced-features/react-18/switchable-runtime.md) by setting `runtime: 'nodejs'`.
View the [supported APIs](/docs/api-reference/edge-runtime.md) and [unsupported APIs](/docs/api-reference/edge-runtime.md#unsupported-apis) for the Edge Runtime. View the [supported APIs](/docs/api-reference/edge-runtime.md) and [unsupported APIs](/docs/api-reference/edge-runtime.md#unsupported-apis) for the Edge Runtime.
...@@ -45,6 +45,18 @@ It can be tempting to reach for an [API Route](/docs/api-routes/introduction.md) ...@@ -45,6 +45,18 @@ It can be tempting to reach for an [API Route](/docs/api-routes/introduction.md)
Take the following example. An API route is used to fetch some data from a CMS. That API route is then called directly from `getServerSideProps`. This produces an additional call, reducing performance. Instead, directly import the logic used inside your API Route into `getServerSideProps`. This could mean calling a CMS, database, or other API directly from inside `getServerSideProps`. Take the following example. An API route is used to fetch some data from a CMS. That API route is then called directly from `getServerSideProps`. This produces an additional call, reducing performance. Instead, directly import the logic used inside your API Route into `getServerSideProps`. This could mean calling a CMS, database, or other API directly from inside `getServerSideProps`.
### getServerSideProps with Edge API Routes
`getServerSideProps` can be used with both Serverless and Edge Runtimes, and you can set props in both. However, currently in Edge Runtime, you do not have access to the response object. This means that you cannot — for example — add cookies in `getServerSideProps`. To have access to the response object, you should **continue to use the Node.js runtime**, which is the default runtime.
You can explicitly set the runtime on a [per-page basis](https://nextjs.org/docs/advanced-features/react-18/switchable-runtime#page-runtime-option) by modifying the `config`, for example:
```js
export const config = {
runtime: 'nodejs',
}
```
## Fetching data on the client side ## Fetching data on the client side
If your page contains frequently updating data, and you don’t need to pre-render the data, you can fetch the data on the [client side](/docs/basic-features/data-fetching/client-side.md). An example of this is user-specific data: If your page contains frequently updating data, and you don’t need to pre-render the data, you can fetch the data on the [client side](/docs/basic-features/data-fetching/client-side.md). An example of this is user-specific data:
......
...@@ -27,7 +27,7 @@ description: 'Learn how to create or update static pages at runtime with Increme ...@@ -27,7 +27,7 @@ description: 'Learn how to create or update static pages at runtime with Increme
Next.js allows you to create or update static pages _after_ you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, **without needing to rebuild the entire site**. With ISR, you can retain the benefits of static while scaling to millions of pages. Next.js allows you to create or update static pages _after_ you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, **without needing to rebuild the entire site**. With ISR, you can retain the benefits of static while scaling to millions of pages.
> Note: the `experimental-edge` runtime (https://nextjs.org/docs/api-reference/edge-runtime) is currently not compatible with ISR although can leverage `stale-while-revalidate` by setting the `cache-control` header manually. > Note: The [`experimental-edge` runtime](https://nextjs.org/docs/api-reference/edge-runtime) is currently not compatible with ISR, although can leverage `stale-while-revalidate` by setting the `cache-control` header manually.
To use ISR, add the `revalidate` prop to `getStaticProps`: To use ISR, add the `revalidate` prop to `getStaticProps`:
......
...@@ -151,7 +151,7 @@ ...@@ -151,7 +151,7 @@
"path": "/docs/api-routes/response-helpers.md" "path": "/docs/api-routes/response-helpers.md"
}, },
{ {
"title": "Edge API Routes (Beta)", "title": "Edge API Routes",
"path": "/docs/api-routes/edge-api-routes.md" "path": "/docs/api-routes/edge-api-routes.md"
} }
] ]
......
...@@ -33,7 +33,7 @@ You can relax the check to allow specific files with your Middleware or Edge API ...@@ -33,7 +33,7 @@ You can relax the check to allow specific files with your Middleware or Edge API
```typescript ```typescript
export const config = { export const config = {
runtime: 'experimental-edge', // for Edge API Routes only runtime: 'edge', // for Edge API Routes only
unstable_allowDynamic: [ unstable_allowDynamic: [
'/lib/utilities.js', // allows a single file '/lib/utilities.js', // allows a single file
'/node_modules/function-bind/**', // use a glob to allow anything in the function-bind 3rd party module '/node_modules/function-bind/**', // use a glob to allow anything in the function-bind 3rd party module
......
...@@ -175,7 +175,7 @@ If you were previously using Middleware to forward headers to an external API, y ...@@ -175,7 +175,7 @@ If you were previously using Middleware to forward headers to an external API, y
import { type NextRequest } from 'next/server' import { type NextRequest } from 'next/server'
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default async function handler(req: NextRequest) { export default async function handler(req: NextRequest) {
......
# Returning response body in Middleware # Returning response body in Middleware
> Note: In Next.js v13.0.0 you can now respond to Middleware directly by returning a `NextResponse`. For more information, see [Producing a Response](https://nextjs.org/docs/advanced-features/middleware#producing-a-response).
#### Why This Error Occurred #### Why This Error Occurred
[Middleware](https://nextjs.org/docs/advanced-features/middleware) can no longer produce a response body as of `v12.2+`. [Middleware](https://nextjs.org/docs/advanced-features/middleware) can no longer produce a response body as of `v12.2+`.
......
...@@ -13,4 +13,4 @@ export default async function handler() { ...@@ -13,4 +13,4 @@ export default async function handler() {
return new Response(`got: ${number}`) return new Response(`got: ${number}`)
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
...@@ -204,7 +204,7 @@ function extractValue(node: Node, path?: string[]): any { ...@@ -204,7 +204,7 @@ function extractValue(node: Node, path?: string[]): any {
/** /**
* Extracts the value of an exported const variable named `exportedName` * Extracts the value of an exported const variable named `exportedName`
* (e.g. "export const config = { runtime: 'experimental-edge' }") from swc's AST. * (e.g. "export const config = { runtime: 'edge' }") from swc's AST.
* The value must be one of (or throws UnsupportedValueError): * The value must be one of (or throws UnsupportedValueError):
* - string * - string
* - boolean * - boolean
......
import { isServerRuntime } from '../../server/config-shared'
import type { NextConfig } from '../../server/config-shared' import type { NextConfig } from '../../server/config-shared'
import type { Middleware, RouteHas } from '../../lib/load-custom-routes' import type { Middleware, RouteHas } from '../../lib/load-custom-routes'
import { promises as fs } from 'fs'
import { matcher } from 'next/dist/compiled/micromatch'
import { ServerRuntime } from 'next/types'
import { import {
extractExportedConstValue, extractExportedConstValue,
UnsupportedValueError, UnsupportedValueError,
} from './extract-const-value' } from './extract-const-value'
import { parseModule } from './parse-module' import { parseModule } from './parse-module'
import { promises as fs } from 'fs'
import { tryToParsePath } from '../../lib/try-to-parse-path'
import * as Log from '../output/log' import * as Log from '../output/log'
import { SERVER_RUNTIME } from '../../lib/constants' import { SERVER_RUNTIME } from '../../lib/constants'
import { ServerRuntime } from 'next/types'
import { checkCustomRoutes } from '../../lib/load-custom-routes' import { checkCustomRoutes } from '../../lib/load-custom-routes'
import { matcher } from 'next/dist/compiled/micromatch' import { tryToParsePath } from '../../lib/try-to-parse-path'
import { isAPIRoute } from '../../lib/is-api-route'
import { isEdgeRuntime } from '../../lib/is-edge-runtime'
import { RSC_MODULE_TYPES } from '../../shared/lib/constants' import { RSC_MODULE_TYPES } from '../../shared/lib/constants'
export interface MiddlewareConfig { export interface MiddlewareConfig {
...@@ -229,13 +231,13 @@ function getMiddlewareConfig( ...@@ -229,13 +231,13 @@ function getMiddlewareConfig(
return result return result
} }
let warnedAboutExperimentalEdgeApiFunctions = false let warnedAboutExperimentalEdge = false
function warnAboutExperimentalEdgeApiFunctions() { function warnAboutExperimentalEdge() {
if (warnedAboutExperimentalEdgeApiFunctions) { if (warnedAboutExperimentalEdge) {
return return
} }
Log.warn(`You are using an experimental edge runtime, the API might change.`) Log.warn(`You are using an experimental edge runtime, the API might change.`)
warnedAboutExperimentalEdgeApiFunctions = true warnedAboutExperimentalEdge = true
} }
const warnedUnsupportedValueMap = new Map<string, boolean>() const warnedUnsupportedValueMap = new Map<string, boolean>()
...@@ -307,7 +309,8 @@ export async function getPageStaticInfo(params: { ...@@ -307,7 +309,8 @@ export async function getPageStaticInfo(params: {
if ( if (
typeof resolvedRuntime !== 'undefined' && typeof resolvedRuntime !== 'undefined' &&
!isServerRuntime(resolvedRuntime) resolvedRuntime !== SERVER_RUNTIME.nodejs &&
!isEdgeRuntime(resolvedRuntime)
) { ) {
const options = Object.values(SERVER_RUNTIME).join(', ') const options = Object.values(SERVER_RUNTIME).join(', ')
if (typeof resolvedRuntime !== 'string') { if (typeof resolvedRuntime !== 'string') {
...@@ -326,15 +329,28 @@ export async function getPageStaticInfo(params: { ...@@ -326,15 +329,28 @@ export async function getPageStaticInfo(params: {
const requiresServerRuntime = ssr || ssg || pageType === 'app' const requiresServerRuntime = ssr || ssg || pageType === 'app'
resolvedRuntime = resolvedRuntime = isEdgeRuntime(resolvedRuntime)
SERVER_RUNTIME.edge === resolvedRuntime ? resolvedRuntime
? SERVER_RUNTIME.edge : requiresServerRuntime
: requiresServerRuntime ? resolvedRuntime || nextConfig.experimental?.runtime
? resolvedRuntime || nextConfig.experimental?.runtime : undefined
: undefined
if (resolvedRuntime === SERVER_RUNTIME.edge) { if (resolvedRuntime === SERVER_RUNTIME.experimentalEdge) {
warnAboutExperimentalEdgeApiFunctions() warnAboutExperimentalEdge()
}
if (
resolvedRuntime === SERVER_RUNTIME.edge &&
pageType === 'pages' &&
page &&
!isAPIRoute(page.replace(/^\/pages\//, '/'))
) {
const message = `Page ${page} provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.`
Log.error(message)
if (!isDev) {
process.exit(1)
}
} }
const middlewareConfig = getMiddlewareConfig( const middlewareConfig = getMiddlewareConfig(
......
...@@ -12,13 +12,13 @@ import chalk from 'next/dist/compiled/chalk' ...@@ -12,13 +12,13 @@ import chalk from 'next/dist/compiled/chalk'
import { posix, join } from 'path' import { posix, join } from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { import {
API_ROUTE,
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
ROOT_DIR_ALIAS, ROOT_DIR_ALIAS,
APP_DIR_ALIAS, APP_DIR_ALIAS,
SERVER_RUNTIME,
WEBPACK_LAYERS, WEBPACK_LAYERS,
} from '../lib/constants' } from '../lib/constants'
import { isAPIRoute } from '../lib/is-api-route'
import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { APP_CLIENT_INTERNALS, RSC_MODULE_TYPES } from '../shared/lib/constants' import { APP_CLIENT_INTERNALS, RSC_MODULE_TYPES } from '../shared/lib/constants'
import { import {
CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_AMP,
...@@ -175,7 +175,7 @@ export function getEdgeServerEntry(opts: { ...@@ -175,7 +175,7 @@ export function getEdgeServerEntry(opts: {
return `next-middleware-loader?${stringify(loaderParams)}!` return `next-middleware-loader?${stringify(loaderParams)}!`
} }
if (opts.page.startsWith('/api/') || opts.page === '/api') { if (isAPIRoute(opts.page)) {
const loaderParams: EdgeFunctionLoaderOptions = { const loaderParams: EdgeFunctionLoaderOptions = {
absolutePagePath: opts.absolutePagePath, absolutePagePath: opts.absolutePagePath,
page: opts.page, page: opts.page,
...@@ -257,8 +257,8 @@ export async function runDependingOnPageType<T>(params: { ...@@ -257,8 +257,8 @@ export async function runDependingOnPageType<T>(params: {
await params.onEdgeServer() await params.onEdgeServer()
return return
} }
if (params.page.match(API_ROUTE)) { if (isAPIRoute(params.page)) {
if (params.pageRuntime === SERVER_RUNTIME.edge) { if (isEdgeRuntime(params.pageRuntime)) {
await params.onEdgeServer() await params.onEdgeServer()
return return
} }
...@@ -279,7 +279,7 @@ export async function runDependingOnPageType<T>(params: { ...@@ -279,7 +279,7 @@ export async function runDependingOnPageType<T>(params: {
await Promise.all([params.onClient(), params.onServer()]) await Promise.all([params.onClient(), params.onServer()])
return return
} }
if (params.pageRuntime === SERVER_RUNTIME.edge) { if (isEdgeRuntime(params.pageRuntime)) {
await Promise.all([params.onClient(), params.onEdgeServer()]) await Promise.all([params.onClient(), params.onEdgeServer()])
return return
} }
......
...@@ -18,7 +18,6 @@ import { ...@@ -18,7 +18,6 @@ import {
PUBLIC_DIR_MIDDLEWARE_CONFLICT, PUBLIC_DIR_MIDDLEWARE_CONFLICT,
MIDDLEWARE_FILENAME, MIDDLEWARE_FILENAME,
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
SERVER_RUNTIME,
} from '../lib/constants' } from '../lib/constants'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { findPagesDir } from '../lib/find-pages-dir' import { findPagesDir } from '../lib/find-pages-dir'
...@@ -109,6 +108,7 @@ import { writeBuildId } from './write-build-id' ...@@ -109,6 +108,7 @@ import { writeBuildId } from './write-build-id'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { NextConfigComplete } from '../server/config-shared' import { NextConfigComplete } from '../server/config-shared'
import isError, { NextError } from '../lib/is-error' import isError, { NextError } from '../lib/is-error'
import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { TelemetryPlugin } from './webpack/plugins/telemetry-plugin' import { TelemetryPlugin } from './webpack/plugins/telemetry-plugin'
import { MiddlewareManifest } from './webpack/plugins/middleware-plugin' import { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import { recursiveCopy } from '../lib/recursive-copy' import { recursiveCopy } from '../lib/recursive-copy'
...@@ -1428,7 +1428,7 @@ export default async function build( ...@@ -1428,7 +1428,7 @@ export default async function build(
try { try {
let edgeInfo: any let edgeInfo: any
if (pageRuntime === SERVER_RUNTIME.edge) { if (isEdgeRuntime(pageRuntime)) {
if (pageType === 'app') { if (pageType === 'app') {
edgeRuntimeAppCount++ edgeRuntimeAppCount++
} else { } else {
...@@ -1467,7 +1467,7 @@ export default async function build( ...@@ -1467,7 +1467,7 @@ export default async function build(
if (pageType === 'app' && originalAppPath) { if (pageType === 'app' && originalAppPath) {
appNormalizedPaths.set(originalAppPath, page) appNormalizedPaths.set(originalAppPath, page)
// TODO-APP: handle prerendering with edge // TODO-APP: handle prerendering with edge
if (pageRuntime === 'experimental-edge') { if (isEdgeRuntime(pageRuntime)) {
isStatic = false isStatic = false
isSsg = false isSsg = false
} else { } else {
...@@ -1505,7 +1505,7 @@ export default async function build( ...@@ -1505,7 +1505,7 @@ export default async function build(
) )
} }
} else { } else {
if (pageRuntime === SERVER_RUNTIME.edge) { if (isEdgeRuntime(pageRuntime)) {
if (workerResult.hasStaticProps) { if (workerResult.hasStaticProps) {
console.warn( console.warn(
`"getStaticProps" is not yet supported fully with "experimental-edge", detected on ${page}` `"getStaticProps" is not yet supported fully with "experimental-edge", detected on ${page}`
......
...@@ -20,7 +20,6 @@ import { ...@@ -20,7 +20,6 @@ import {
SERVER_PROPS_GET_INIT_PROPS_CONFLICT, SERVER_PROPS_GET_INIT_PROPS_CONFLICT,
SERVER_PROPS_SSG_CONFLICT, SERVER_PROPS_SSG_CONFLICT,
MIDDLEWARE_FILENAME, MIDDLEWARE_FILENAME,
SERVER_RUNTIME,
} from '../lib/constants' } from '../lib/constants'
import { MODERN_BROWSERSLIST_TARGET } from '../shared/lib/constants' import { MODERN_BROWSERSLIST_TARGET } from '../shared/lib/constants'
import prettyBytes from '../lib/pretty-bytes' import prettyBytes from '../lib/pretty-bytes'
...@@ -33,6 +32,7 @@ import { GetStaticPaths, PageConfig, ServerRuntime } from 'next/types' ...@@ -33,6 +32,7 @@ import { GetStaticPaths, PageConfig, ServerRuntime } from 'next/types'
import { BuildManifest } from '../server/get-page-files' import { BuildManifest } from '../server/get-page-files'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { UnwrapPromise } from '../lib/coalesced-function' import { UnwrapPromise } from '../lib/coalesced-function'
import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import * as Log from './output/log' import * as Log from './output/log'
import { import {
...@@ -423,7 +423,7 @@ export async function printTreeView( ...@@ -423,7 +423,7 @@ export async function printTreeView(
? '○' ? '○'
: pageInfo?.isSsg : pageInfo?.isSsg
? '●' ? '●'
: pageInfo?.runtime === SERVER_RUNTIME.edge : isEdgeRuntime(pageInfo?.runtime)
? 'ℇ' ? 'ℇ'
: 'λ' : 'λ'
...@@ -1267,7 +1267,7 @@ export async function isPageStatic({ ...@@ -1267,7 +1267,7 @@ export async function isPageStatic({
let prerenderFallback: boolean | 'blocking' | undefined let prerenderFallback: boolean | 'blocking' | undefined
let appConfig: AppConfig = {} let appConfig: AppConfig = {}
if (pageRuntime === SERVER_RUNTIME.edge) { if (isEdgeRuntime(pageRuntime)) {
const runtime = await getRuntimeContext({ const runtime = await getRuntimeContext({
paths: edgeInfo.files.map((file: string) => path.join(distDir, file)), paths: edgeInfo.files.map((file: string) => path.join(distDir, file)),
env: edgeInfo.env, env: edgeInfo.env,
......
...@@ -10,13 +10,13 @@ import { ...@@ -10,13 +10,13 @@ import {
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
ROOT_DIR_ALIAS, ROOT_DIR_ALIAS,
APP_DIR_ALIAS, APP_DIR_ALIAS,
SERVER_RUNTIME,
WEBPACK_LAYERS, WEBPACK_LAYERS,
RSC_MOD_REF_PROXY_ALIAS, RSC_MOD_REF_PROXY_ALIAS,
} from '../lib/constants' } from '../lib/constants'
import { EXTERNAL_PACKAGES } from '../lib/server-external-packages' import { EXTERNAL_PACKAGES } from '../lib/server-external-packages'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { CustomRoutes } from '../lib/load-custom-routes.js' import { CustomRoutes } from '../lib/load-custom-routes.js'
import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { import {
CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
...@@ -628,7 +628,7 @@ export default async function getBaseWebpackConfig( ...@@ -628,7 +628,7 @@ export default async function getBaseWebpackConfig(
const disableOptimizedLoading = true const disableOptimizedLoading = true
if (isClient) { if (isClient) {
if (config.experimental.runtime === SERVER_RUNTIME.edge) { if (isEdgeRuntime(config.experimental.runtime)) {
Log.warn( Log.warn(
'You are using the experimental Edge Runtime with `experimental.runtime`.' 'You are using the experimental Edge Runtime with `experimental.runtime`.'
) )
......
...@@ -72,7 +72,7 @@ export function getRender({ ...@@ -72,7 +72,7 @@ export function getRender({
pagesType, pagesType,
extendRenderOpts: { extendRenderOpts: {
buildId, buildId,
runtime: SERVER_RUNTIME.edge, runtime: SERVER_RUNTIME.experimentalEdge,
supportsDynamicHTML: true, supportsDynamicHTML: true,
disableOptimizedLoading: true, disableOptimizedLoading: true,
serverComponentManifest, serverComponentManifest,
......
...@@ -2,7 +2,7 @@ import devalue from 'next/dist/compiled/devalue' ...@@ -2,7 +2,7 @@ import devalue from 'next/dist/compiled/devalue'
import { join } from 'path' import { join } from 'path'
import { parse } from 'querystring' import { parse } from 'querystring'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
import { API_ROUTE } from '../../../../lib/constants' import { isAPIRoute } from '../../../../lib/is-api-route'
import { isDynamicRoute } from '../../../../shared/lib/router/utils' import { isDynamicRoute } from '../../../../shared/lib/router/utils'
import { escapeStringRegexp } from '../../../../shared/lib/escape-regexp' import { escapeStringRegexp } from '../../../../shared/lib/escape-regexp'
import { __ApiPreviewProps } from '../../../../server/api-utils' import { __ApiPreviewProps } from '../../../../server/api-utils'
...@@ -88,7 +88,7 @@ const nextServerlessLoader: webpack.LoaderDefinitionFunction = function () { ...@@ -88,7 +88,7 @@ const nextServerlessLoader: webpack.LoaderDefinitionFunction = function () {
` `
: 'const runtimeConfig = {}' : 'const runtimeConfig = {}'
if (page.match(API_ROUTE)) { if (isAPIRoute(page)) {
return ` return `
${envLoading} ${envLoading}
${runtimeConfigImports} ${runtimeConfigImports}
......
...@@ -58,7 +58,11 @@ interface IEntry { ...@@ -58,7 +58,11 @@ interface IEntry {
dynamicParams?: boolean dynamicParams?: boolean
fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache' fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache'
preferredRegion?: 'auto' | 'home' | 'edge' preferredRegion?: 'auto' | 'home' | 'edge'
${options.type === 'page' ? "runtime?: 'nodejs' | 'experimental-edge'" : ''} ${
options.type === 'page'
? "runtime?: 'nodejs' | 'experimental-edge' | 'edge'"
: ''
}
} }
// ============= // =============
......
...@@ -13,7 +13,7 @@ import { promisify } from 'util' ...@@ -13,7 +13,7 @@ import { promisify } from 'util'
import { AmpPageStatus, formatAmpMessages } from '../build/output/index' import { AmpPageStatus, formatAmpMessages } from '../build/output/index'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
import createSpinner from '../build/spinner' import createSpinner from '../build/spinner'
import { API_ROUTE, SSG_FALLBACK_EXPORT_ERROR } from '../lib/constants' import { SSG_FALLBACK_EXPORT_ERROR } from '../lib/constants'
import { recursiveCopy } from '../lib/recursive-copy' import { recursiveCopy } from '../lib/recursive-copy'
import { recursiveDelete } from '../lib/recursive-delete' import { recursiveDelete } from '../lib/recursive-delete'
import { import {
...@@ -40,6 +40,7 @@ import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-pa ...@@ -40,6 +40,7 @@ import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-pa
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import { PrerenderManifest } from '../build' import { PrerenderManifest } from '../build'
import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin' import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import { isAPIRoute } from '../lib/is-api-route'
import { getPagePath } from '../server/require' import { getPagePath } from '../server/require'
import { Span } from '../trace' import { Span } from '../trace'
import { FontConfig } from '../server/font-utils' import { FontConfig } from '../server/font-utils'
...@@ -243,7 +244,7 @@ export default async function exportApp( ...@@ -243,7 +244,7 @@ export default async function exportApp(
// _error is exported as 404.html later on // _error is exported as 404.html later on
// API Routes are Node.js functions // API Routes are Node.js functions
if (page.match(API_ROUTE)) { if (isAPIRoute(page)) {
hasApiRoutes = true hasApiRoutes = true
continue continue
} }
...@@ -475,7 +476,7 @@ export default async function exportApp( ...@@ -475,7 +476,7 @@ export default async function exportApp(
const filteredPaths = exportPaths.filter( const filteredPaths = exportPaths.filter(
// Remove API routes // Remove API routes
(route) => !exportPathMap[route].page.match(API_ROUTE) (route) => !isAPIRoute(exportPathMap[route].page)
) )
if (filteredPaths.length !== exportPaths.length) { if (filteredPaths.length !== exportPaths.length) {
......
import type { ServerRuntime } from '../types' import type { ServerRuntime } from '../types'
// Regex for API routes
export const API_ROUTE = /^\/api(?:\/|$)/
// Patterns to detect middleware files // Patterns to detect middleware files
export const MIDDLEWARE_FILENAME = 'middleware' export const MIDDLEWARE_FILENAME = 'middleware'
export const MIDDLEWARE_LOCATION_REGEXP = `(?:src/)?${MIDDLEWARE_FILENAME}` export const MIDDLEWARE_LOCATION_REGEXP = `(?:src/)?${MIDDLEWARE_FILENAME}`
...@@ -65,7 +62,8 @@ export const ESLINT_PROMPT_VALUES = [ ...@@ -65,7 +62,8 @@ export const ESLINT_PROMPT_VALUES = [
] ]
export const SERVER_RUNTIME: Record<string, ServerRuntime> = { export const SERVER_RUNTIME: Record<string, ServerRuntime> = {
edge: 'experimental-edge', edge: 'edge',
experimentalEdge: 'experimental-edge',
nodejs: 'nodejs', nodejs: 'nodejs',
} }
......
export function isAPIRoute(value?: string) {
return value === '/api' || Boolean(value?.startsWith('/api/'))
}
import { ServerRuntime } from '../types'
import { SERVER_RUNTIME } from './constants'
export function isEdgeRuntime(value?: string): value is ServerRuntime {
return (
value === SERVER_RUNTIME.experimentalEdge || value === SERVER_RUNTIME.edge
)
}
...@@ -33,6 +33,7 @@ import type { FontLoaderManifest } from '../build/webpack/plugins/font-loader-ma ...@@ -33,6 +33,7 @@ import type { FontLoaderManifest } from '../build/webpack/plugins/font-loader-ma
import { parse as parseQs } from 'querystring' import { parse as parseQs } from 'querystring'
import { format as formatUrl, parse as parseUrl } from 'url' import { format as formatUrl, parse as parseUrl } from 'url'
import { getRedirectStatus } from '../lib/redirect-status' import { getRedirectStatus } from '../lib/redirect-status'
import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { import {
NEXT_BUILTIN_DOCUMENT, NEXT_BUILTIN_DOCUMENT,
STATIC_STATUS_PAGES, STATIC_STATUS_PAGES,
...@@ -1080,7 +1081,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1080,7 +1081,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} }
// strip header so we generate HTML still // strip header so we generate HTML still
if ( if (
opts.runtime !== 'experimental-edge' || !isEdgeRuntime(opts.runtime) ||
(this.serverOptions as any).webServerConfig (this.serverOptions as any).webServerConfig
) { ) {
for (const param of FLIGHT_PARAMETERS) { for (const param of FLIGHT_PARAMETERS) {
...@@ -1293,7 +1294,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1293,7 +1294,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}) })
if ( if (
this.nextConfig.experimental.fetchCache && this.nextConfig.experimental.fetchCache &&
(opts.runtime !== 'experimental-edge' || (!isEdgeRuntime(opts.runtime) ||
(this.serverOptions as any).webServerConfig) (this.serverOptions as any).webServerConfig)
) { ) {
delete req.headers[FETCH_CACHE_HEADER] delete req.headers[FETCH_CACHE_HEADER]
......
import { NextConfig } from './config' import { NextConfig } from './config'
import type { JSONSchemaType } from 'ajv' import type { JSONSchemaType } from 'ajv'
import { VALID_LOADERS } from '../shared/lib/image-config' import { VALID_LOADERS } from '../shared/lib/image-config'
import { SERVER_RUNTIME } from '../lib/constants'
const configSchema = { const configSchema = {
type: 'object', type: 'object',
...@@ -353,7 +354,7 @@ const configSchema = { ...@@ -353,7 +354,7 @@ const configSchema = {
}, },
runtime: { runtime: {
// automatic typing doesn't like enum // automatic typing doesn't like enum
enum: ['experimental-edge', 'nodejs'] as any, enum: Object.values(SERVER_RUNTIME) as any,
type: 'string', type: 'string',
}, },
serverComponentsExternalPackages: { serverComponentsExternalPackages: {
......
...@@ -623,12 +623,6 @@ export async function normalizeConfig(phase: string, config: any) { ...@@ -623,12 +623,6 @@ export async function normalizeConfig(phase: string, config: any) {
return await config return await config
} }
export function isServerRuntime(value?: string): value is ServerRuntime {
return (
value === undefined || value === 'nodejs' || value === 'experimental-edge'
)
}
export function validateConfig(userConfig: NextConfig): { export function validateConfig(userConfig: NextConfig): {
errors?: Array<any> | null errors?: Array<any> | null
} { } {
......
...@@ -31,6 +31,7 @@ import fs from 'fs' ...@@ -31,6 +31,7 @@ import fs from 'fs'
import { join, relative, resolve, sep } from 'path' import { join, relative, resolve, sep } from 'path'
import { IncomingMessage, ServerResponse } from 'http' import { IncomingMessage, ServerResponse } from 'http'
import { addRequestMeta, getRequestMeta } from './request-meta' import { addRequestMeta, getRequestMeta } from './request-meta'
import { isAPIRoute } from '../lib/is-api-route'
import { isDynamicRoute } from '../shared/lib/router/utils' import { isDynamicRoute } from '../shared/lib/router/utils'
import { import {
PAGES_MANIFEST, PAGES_MANIFEST,
...@@ -1199,7 +1200,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1199,7 +1200,7 @@ export default class NextNodeServer extends BaseServer {
} }
const bubbleNoFallback = !!query._nextBubbleNoFallback const bubbleNoFallback = !!query._nextBubbleNoFallback
if (pathname === '/api' || pathname.startsWith('/api/')) { if (isAPIRoute(pathname)) {
delete query._nextBubbleNoFallback delete query._nextBubbleNoFallback
const handled = await this.handleApiRequest(req, res, pathname, query) const handled = await this.handleApiRequest(req, res, pathname, query)
...@@ -1268,7 +1269,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1268,7 +1269,7 @@ export default class NextNodeServer extends BaseServer {
if (!pageFound && this.dynamicRoutes) { if (!pageFound && this.dynamicRoutes) {
for (const dynamicRoute of this.dynamicRoutes) { for (const dynamicRoute of this.dynamicRoutes) {
params = dynamicRoute.match(pathname) || undefined params = dynamicRoute.match(pathname) || undefined
if (dynamicRoute.page.startsWith('/api') && params) { if (isAPIRoute(dynamicRoute.page) && params) {
page = dynamicRoute.page page = dynamicRoute.page
pageFound = true pageFound = true
break break
......
...@@ -132,6 +132,7 @@ const API_DOCS: Record< ...@@ -132,6 +132,7 @@ const API_DOCS: Record<
'The `runtime` option controls the preferred runtime to render this route.', 'The `runtime` option controls the preferred runtime to render this route.',
options: { options: {
'"nodejs"': 'Prefer the Node.js runtime.', '"nodejs"': 'Prefer the Node.js runtime.',
'"edge"': 'Prefer the Edge runtime.',
'"experimental-edge"': 'Prefer the experimental Edge runtime.', '"experimental-edge"': 'Prefer the experimental Edge runtime.',
}, },
link: 'https://beta.nextjs.org/docs/api-reference/segment-config#runtime', link: 'https://beta.nextjs.org/docs/api-reference/segment-config#runtime',
......
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
getNextInternalQuery, getNextInternalQuery,
NextUrlWithParsedQuery, NextUrlWithParsedQuery,
} from './request-meta' } from './request-meta'
import { isAPIRoute } from '../lib/is-api-route'
import { getPathMatch } from '../shared/lib/router/utils/path-match' import { getPathMatch } from '../shared/lib/router/utils/path-match'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
...@@ -374,7 +375,7 @@ export default class Router { ...@@ -374,7 +375,7 @@ export default class Router {
if ( if (
pathnameInfo.locale && pathnameInfo.locale &&
!route.matchesLocaleAPIRoutes && !route.matchesLocaleAPIRoutes &&
pathnameInfo.pathname.match(/^\/api(?:\/|$)/) isAPIRoute(pathnameInfo.pathname)
) { ) {
continue continue
} }
......
...@@ -5,17 +5,17 @@ import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta' ...@@ -5,17 +5,17 @@ import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta'
import type { Params } from '../shared/lib/router/utils/route-matcher' import type { Params } from '../shared/lib/router/utils/route-matcher'
import type { PayloadOptions } from './send-payload' import type { PayloadOptions } from './send-payload'
import type { LoadComponentsReturnType } from './load-components' import type { LoadComponentsReturnType } from './load-components'
import { NoFallbackError, Options } from './base-server'
import type { DynamicRoutes, PageChecker, Route } from './router' import type { DynamicRoutes, PageChecker, Route } from './router'
import type { NextConfig } from './config-shared' import type { NextConfig } from './config-shared'
import type { BaseNextRequest, BaseNextResponse } from './base-http' import type { BaseNextRequest, BaseNextResponse } from './base-http'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import BaseServer from './base-server'
import { byteLength } from './api-utils/web' import { byteLength } from './api-utils/web'
import BaseServer, { NoFallbackError, Options } from './base-server'
import { generateETag } from './lib/etag' import { generateETag } from './lib/etag'
import { addRequestMeta } from './request-meta' import { addRequestMeta } from './request-meta'
import WebResponseCache from './response-cache/web' import WebResponseCache from './response-cache/web'
import { isAPIRoute } from '../lib/is-api-route'
import { getPathMatch } from '../shared/lib/router/utils/path-match' import { getPathMatch } from '../shared/lib/router/utils/path-match'
import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path' import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path'
import { detectDomainLocale } from '../shared/lib/i18n/detect-domain-locale' import { detectDomainLocale } from '../shared/lib/i18n/detect-domain-locale'
...@@ -307,7 +307,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -307,7 +307,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
} }
const bubbleNoFallback = !!query._nextBubbleNoFallback const bubbleNoFallback = !!query._nextBubbleNoFallback
if (pathname === '/api' || pathname.startsWith('/api/')) { if (isAPIRoute(pathname)) {
delete query._nextBubbleNoFallback delete query._nextBubbleNoFallback
} }
......
...@@ -44,6 +44,7 @@ import { removeLocale } from '../../../client/remove-locale' ...@@ -44,6 +44,7 @@ import { removeLocale } from '../../../client/remove-locale'
import { removeBasePath } from '../../../client/remove-base-path' import { removeBasePath } from '../../../client/remove-base-path'
import { addBasePath } from '../../../client/add-base-path' import { addBasePath } from '../../../client/add-base-path'
import { hasBasePath } from '../../../client/has-base-path' import { hasBasePath } from '../../../client/has-base-path'
import { isAPIRoute } from '../../../lib/is-api-route'
import { getNextPathnameInfo } from './utils/get-next-pathname-info' import { getNextPathnameInfo } from './utils/get-next-pathname-info'
import { formatNextPathnameInfo } from './utils/format-next-pathname-info' import { formatNextPathnameInfo } from './utils/format-next-pathname-info'
import { compareRouterStates } from './utils/compare-states' import { compareRouterStates } from './utils/compare-states'
...@@ -2135,7 +2136,7 @@ export default class Router implements BaseRouter { ...@@ -2135,7 +2136,7 @@ export default class Router implements BaseRouter {
} }
} }
if (route === '/api' || route.startsWith('/api/')) { if (isAPIRoute(route)) {
handleHardNavigation({ url: as, router: this }) handleHardNavigation({ url: as, router: this })
return new Promise<never>(() => {}) return new Promise<never>(() => {})
} }
......
...@@ -23,7 +23,7 @@ import { ...@@ -23,7 +23,7 @@ import {
// @ts-ignore This path is generated at build time and conflicts otherwise // @ts-ignore This path is generated at build time and conflicts otherwise
import next from '../dist/server/next' import next from '../dist/server/next'
export type ServerRuntime = 'nodejs' | 'experimental-edge' | undefined export type ServerRuntime = 'nodejs' | 'experimental-edge' | 'edge' | undefined
// @ts-ignore This path is generated at build time and conflicts otherwise // @ts-ignore This path is generated at build time and conflicts otherwise
export { NextConfig } from '../dist/server/config' export { NextConfig } from '../dist/server/config'
......
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default (req) => { export default (req) => {
......
...@@ -3,5 +3,5 @@ export default function api(req) { ...@@ -3,5 +3,5 @@ export default function api(req) {
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
...@@ -7,5 +7,5 @@ export default async (req) => { ...@@ -7,5 +7,5 @@ export default async (req) => {
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
...@@ -7,5 +7,5 @@ export default async (req) => { ...@@ -7,5 +7,5 @@ export default async (req) => {
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
...@@ -10,7 +10,7 @@ describe('edge api can use async local storage', () => { ...@@ -10,7 +10,7 @@ describe('edge api can use async local storage', () => {
{ {
title: 'a single instance', title: 'a single instance',
code: ` code: `
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
const storage = new AsyncLocalStorage() const storage = new AsyncLocalStorage()
export default async function handler(request) { export default async function handler(request) {
...@@ -36,7 +36,7 @@ describe('edge api can use async local storage', () => { ...@@ -36,7 +36,7 @@ describe('edge api can use async local storage', () => {
{ {
title: 'multiple instances', title: 'multiple instances',
code: ` code: `
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
const topStorage = new AsyncLocalStorage() const topStorage = new AsyncLocalStorage()
export default async function handler(request) { export default async function handler(request) {
......
...@@ -49,7 +49,7 @@ describe('edge api endpoints can use wasm files', () => { ...@@ -49,7 +49,7 @@ describe('edge api endpoints can use wasm files', () => {
const value = await increment(input); const value = await increment(input);
return new Response(null, { headers: { data: JSON.stringify({ input, value }) } }); return new Response(null, { headers: { data: JSON.stringify({ input, value }) } });
} }
export const config = { runtime: 'experimental-edge' }; export const config = { runtime: 'edge' };
`, `,
'src/add.wasm': new FileRef(path.join(__dirname, './add.wasm')), 'src/add.wasm': new FileRef(path.join(__dirname, './add.wasm')),
'src/add.js': ` 'src/add.js': `
......
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
/** /**
* @param {import('next/server').NextRequest} req * @param {import('next/server').NextRequest} req
......
export default () => new Response('ok')
export const config = { runtime: 'edge' }
export default () => <p>hello world</p>
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP, File, nextBuild } from 'next-test-utils'
import { join } from 'path'
const appDir = join(__dirname, './app')
const pagePath = 'pages/index.jsx'
const apiPath = 'pages/api/edge.js'
const page = new File(join(appDir, pagePath))
const api = new File(join(appDir, apiPath))
describe('Configurable runtime for pages and API routes', () => {
let next: NextInstance
if ((global as any).isNextDev) {
describe('In dev mode', () => {
beforeAll(async () => {
next = await createNext({
files: new FileRef(appDir),
dependencies: {},
skipStart: true,
})
})
afterEach(async () => {
await next.stop()
await next.patchFile(pagePath, page.originalContent)
await next.patchFile(apiPath, api.originalContent)
})
afterAll(() => next.destroy())
it('runs with no warning API route on the edge runtime', async () => {
await next.start()
const res = await fetchViaHTTP(next.url, `/api/edge`)
expect(res.status).toEqual(200)
expect(next.cliOutput).not.toInclude('error')
expect(next.cliOutput).not.toInclude('warn')
})
it('warns about API route using experimental-edge runtime', async () => {
await next.patchFile(
apiPath,
`
export default () => new Response('ok');
export const config = { runtime: 'experimental-edge' };
`
)
await next.start()
const res = await fetchViaHTTP(next.url, `/api/edge`)
expect(res.status).toEqual(200)
expect(next.cliOutput).not.toInclude('error')
expect(next.cliOutput).toInclude(
'warn - You are using an experimental edge runtime, the API might change.'
)
})
it('warns about page using edge runtime', async () => {
await next.patchFile(
pagePath,
`
export default () => (<p>hello world</p>);
export const runtime = 'experimental-edge';
`
)
await next.start()
const res = await fetchViaHTTP(next.url, `/`)
expect(res.status).toEqual(200)
expect(next.cliOutput).not.toInclude('error')
expect(next.cliOutput).toInclude(
'warn - You are using an experimental edge runtime, the API might change.'
)
})
it('errors about page using edge runtime', async () => {
await next.patchFile(
pagePath,
`
export default () => (<p>hello world</p>);
export const runtime = 'edge';
`
)
await next.start()
const res = await fetchViaHTTP(next.url, `/`)
expect(res.status).toEqual(200)
expect(next.cliOutput).toInclude(
`error - Page /pages provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.`
)
expect(next.cliOutput).not.toInclude('warn')
})
})
} else if ((global as any).isNextStart) {
describe('In start mode', () => {
// TODO because createNext runs process.exit() without any log info on build failure, rely on good old nextBuild()
afterEach(async () => {
page.restore()
api.restore()
})
it('builds with API route on the edge runtime and page on the experimental edge runtime', async () => {
page.write(`
export default () => (<p>hello world</p>);
export const runtime = 'experimental-edge';
`)
const output = await nextBuild(appDir, undefined, {
stdout: true,
stderr: true,
})
expect(output.code).toBe(0)
expect(output.stderr).not.toContain(`error`)
expect(output.stdout).not.toContain(`warn`)
})
it('does not build with page on the edge runtime', async () => {
page.write(`
export default () => (<p>hello world</p>);
export const runtime = 'edge';
`)
const output = await nextBuild(appDir, undefined, {
stdout: true,
stderr: true,
})
expect(output.code).toBe(1)
expect(output.stderr).not.toContain(`Build failed`)
expect(output.stderr).toContain(
`error - Page / provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.`
)
})
})
} else {
it.skip('no deploy tests', () => {})
}
})
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export const config = { runtime: 'experimental-edge', regions: 'default' } export const config = { runtime: 'edge', regions: 'default' }
/** /**
* @param {import('next/server').NextRequest} * @param {import('next/server').NextRequest}
......
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default (req) => { export default (req) => {
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import { ImageResponse } from '@vercel/og' import { ImageResponse } from '@vercel/og'
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default function () { export default function () {
......
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default function handler(req) { export default function handler(req) {
......
...@@ -3,5 +3,5 @@ export default async function handler() { ...@@ -3,5 +3,5 @@ export default async function handler() {
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
...@@ -45,15 +45,10 @@ describe('Switchable runtime', () => { ...@@ -45,15 +45,10 @@ describe('Switchable runtime', () => {
beforeAll(async () => { beforeAll(async () => {
next = await createNext({ next = await createNext({
files: { files: new FileRef(__dirname),
app: new FileRef(join(__dirname, './app')),
pages: new FileRef(join(__dirname, './pages')),
utils: new FileRef(join(__dirname, './utils')),
'next.config.js': new FileRef(join(__dirname, './next.config.js')),
},
dependencies: { dependencies: {
react: 'experimental', react: 'latest',
'react-dom': 'experimental', 'react-dom': 'latest',
}, },
}) })
context = { context = {
...@@ -229,7 +224,7 @@ describe('Switchable runtime', () => { ...@@ -229,7 +224,7 @@ describe('Switchable runtime', () => {
'pages/api/switch-in-dev.js', 'pages/api/switch-in-dev.js',
` `
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default () => new Response('edge response') export default () => new Response('edge response')
...@@ -259,7 +254,7 @@ describe('Switchable runtime', () => { ...@@ -259,7 +254,7 @@ describe('Switchable runtime', () => {
'pages/api/switch-in-dev.js', 'pages/api/switch-in-dev.js',
` `
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default () => new Response('edge response again') export default () => new Response('edge response again')
...@@ -340,7 +335,7 @@ describe('Switchable runtime', () => { ...@@ -340,7 +335,7 @@ describe('Switchable runtime', () => {
'pages/api/switch-in-dev-same-content.js', 'pages/api/switch-in-dev-same-content.js',
` `
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default () => new Response('edge response') export default () => new Response('edge response')
...@@ -373,7 +368,7 @@ describe('Switchable runtime', () => { ...@@ -373,7 +368,7 @@ describe('Switchable runtime', () => {
'pages/api/syntax-error-in-dev.js', 'pages/api/syntax-error-in-dev.js',
` `
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default => new Response('edge response') export default => new Response('edge response')
...@@ -391,7 +386,7 @@ describe('Switchable runtime', () => { ...@@ -391,7 +386,7 @@ describe('Switchable runtime', () => {
export default () => new Response('edge response again') export default () => new Response('edge response again')
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
` `
......
...@@ -3,5 +3,5 @@ export default (req) => { ...@@ -3,5 +3,5 @@ export default (req) => {
} }
export const config = { export const config = {
runtime: `experimental-edge`, runtime: `edge`,
} }
...@@ -3,5 +3,5 @@ export default (req) => { ...@@ -3,5 +3,5 @@ export default (req) => {
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default () => new Response('edge response') export default () => new Response('edge response')
export const config = { export const config = {
runtime: `experimental-edge`, runtime: `edge`,
} }
...@@ -4,5 +4,5 @@ export default () => { ...@@ -4,5 +4,5 @@ export default () => {
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
...@@ -72,7 +72,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -72,7 +72,7 @@ describe('Edge runtime configurable guards', () => {
return Response.json({ result: true }) return Response.json({ result: true })
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
unstable_allowDynamic: '/lib/**' unstable_allowDynamic: '/lib/**'
} }
`) `)
...@@ -125,7 +125,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -125,7 +125,7 @@ describe('Edge runtime configurable guards', () => {
return Response.json({ result: true }) return Response.json({ result: true })
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
unstable_allowDynamic: '**' unstable_allowDynamic: '**'
} }
`) `)
...@@ -159,7 +159,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -159,7 +159,7 @@ describe('Edge runtime configurable guards', () => {
return Response.json({ result: true }) return Response.json({ result: true })
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
unstable_allowDynamic: '/lib/**' unstable_allowDynamic: '/lib/**'
} }
`) `)
...@@ -221,7 +221,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -221,7 +221,7 @@ describe('Edge runtime configurable guards', () => {
return Response.json({ result: true }) return Response.json({ result: true })
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
unstable_allowDynamic: '**' unstable_allowDynamic: '**'
} }
`) `)
...@@ -257,7 +257,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -257,7 +257,7 @@ describe('Edge runtime configurable guards', () => {
return Response.json({ result: true }) return Response.json({ result: true })
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
unstable_allowDynamic: '/lib/**' unstable_allowDynamic: '/lib/**'
} }
`) `)
...@@ -328,7 +328,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -328,7 +328,7 @@ describe('Edge runtime configurable guards', () => {
return Response.json({ result: true }) return Response.json({ result: true })
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
unstable_allowDynamic: '/pages/**' unstable_allowDynamic: '/pages/**'
} }
`) `)
...@@ -397,7 +397,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -397,7 +397,7 @@ describe('Edge runtime configurable guards', () => {
export default async function handler(request) { export default async function handler(request) {
return Response.json({ result: (() => {}) instanceof Function }) return Response.json({ result: (() => {}) instanceof Function })
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
`) `)
}, },
}, },
......
...@@ -23,4 +23,4 @@ export default async function handler(request) { ...@@ -23,4 +23,4 @@ export default async function handler(request) {
) )
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
...@@ -2,4 +2,4 @@ export default async function handler(request) { ...@@ -2,4 +2,4 @@ export default async function handler(request) {
return Response.json({ ok: true }) return Response.json({ ok: true })
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
...@@ -68,7 +68,7 @@ describe('Edge runtime code with imports', () => { ...@@ -68,7 +68,7 @@ describe('Edge runtime code with imports', () => {
return Response.json({ ok: basename() }) return Response.json({ ok: basename() })
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
`) `)
}, },
}, },
...@@ -129,7 +129,7 @@ describe('Edge runtime code with imports', () => { ...@@ -129,7 +129,7 @@ describe('Edge runtime code with imports', () => {
return Response.json({ ok: writeFile() }) return Response.json({ ok: writeFile() })
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
`) `)
}, },
}, },
...@@ -188,7 +188,7 @@ describe('Edge runtime code with imports', () => { ...@@ -188,7 +188,7 @@ describe('Edge runtime code with imports', () => {
return Response.json({ ok: await throwAsync() }) return Response.json({ ok: await throwAsync() })
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
`) `)
}, },
}, },
...@@ -267,7 +267,7 @@ describe('Edge runtime code with imports', () => { ...@@ -267,7 +267,7 @@ describe('Edge runtime code with imports', () => {
return Response.json({ ok: true }) return Response.json({ ok: true })
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
`) `)
}, },
}, },
...@@ -325,7 +325,7 @@ describe('Edge runtime code with imports', () => { ...@@ -325,7 +325,7 @@ describe('Edge runtime code with imports', () => {
return Response.json({ ok: true }) return Response.json({ ok: true })
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
`) `)
}, },
}, },
...@@ -384,7 +384,7 @@ describe('Edge runtime code with imports', () => { ...@@ -384,7 +384,7 @@ describe('Edge runtime code with imports', () => {
return Response.json({ ok: true }) return Response.json({ ok: true })
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
`) `)
}, },
}, },
...@@ -445,7 +445,7 @@ describe('Edge runtime code with imports', () => { ...@@ -445,7 +445,7 @@ describe('Edge runtime code with imports', () => {
return Response.json({ ok: true }) return Response.json({ ok: true })
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
`) `)
}, },
}, },
...@@ -503,7 +503,7 @@ describe('Edge runtime code with imports', () => { ...@@ -503,7 +503,7 @@ describe('Edge runtime code with imports', () => {
return response return response
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
`) `)
}, },
}, },
...@@ -564,7 +564,7 @@ describe('Edge runtime code with imports', () => { ...@@ -564,7 +564,7 @@ describe('Edge runtime code with imports', () => {
return response return response
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
`) `)
}, },
}, },
......
...@@ -2,4 +2,4 @@ export default async function handler(request) { ...@@ -2,4 +2,4 @@ export default async function handler(request) {
return 'Boom' return 'Boom'
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
export default function () { export default function () {
return new Response( return new Response(
new ReadableStream({ new ReadableStream({
......
...@@ -5,4 +5,4 @@ export default async function handler(request) { ...@@ -5,4 +5,4 @@ export default async function handler(request) {
return Response.json({ ok: true }) return Response.json({ ok: true })
} }
export const config = { runtime: 'experimental-edge' } export const config = { runtime: 'edge' }
...@@ -5,5 +5,5 @@ export default async () => { ...@@ -5,5 +5,5 @@ export default async () => {
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
...@@ -5,5 +5,5 @@ export default async () => { ...@@ -5,5 +5,5 @@ export default async () => {
} }
export const config = { export const config = {
runtime: 'experimental-edge', runtime: 'edge',
} }
...@@ -13,7 +13,7 @@ describe('Middleware source maps', () => { ...@@ -13,7 +13,7 @@ describe('Middleware source maps', () => {
export default function () { return <div>Hello, world!</div> } export default function () { return <div>Hello, world!</div> }
`, `,
'pages/api/edge.js': ` 'pages/api/edge.js': `
export const config = { runtime: 'experimental-edge' }; export const config = { runtime: 'edge' };
export default function (req) { export default function (req) {
return new Response("Hello from " + req.url); return new Response("Hello from " + req.url);
} }
......
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