rsnext/packages/next/server/dev/next-dev-server.ts

1432 lines
44 KiB
TypeScript
Raw Normal View History

import type { __ApiPreviewProps } from '../api-utils'
import type { CustomRoutes } from '../../lib/load-custom-routes'
import type { FindComponentsResult } from '../next-server'
import type { LoadComponentsReturnType } from '../load-components'
import type { Options as ServerOptions } from '../next-server'
import type { Params } from '../../shared/lib/router/utils/route-matcher'
import type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'
import type { ParsedUrlQuery } from 'querystring'
import type { Server as HTTPServer } from 'http'
import type { UrlWithParsedQuery } from 'url'
import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { MiddlewareRoutingItem, RoutingItem } from '../base-server'
import type { MiddlewareMatcher } from '../../build/analysis/get-page-static-info'
import crypto from 'crypto'
import fs from 'fs'
import { Worker } from 'next/dist/compiled/jest-worker'
import findUp from 'next/dist/compiled/find-up'
import { join as pathJoin, relative, resolve as pathResolve, sep } from 'path'
import React from 'react'
import Watchpack from 'next/dist/compiled/watchpack'
import { ampValidation } from '../../build/output'
import { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'
import { fileExists } from '../../lib/file-exists'
import { findPagesDir } from '../../lib/find-pages-dir'
import loadCustomRoutes from '../../lib/load-custom-routes'
import { verifyTypeScriptSetup } from '../../lib/verifyTypeScriptSetup'
Adds web worker support to `<Script />` using Partytown (#34244) ## Summary This PR adds a new `worker` strategy to the `<Script />` component that automatically relocates and executes the script in a web worker. ```jsx <Script strategy="worker" ... /> ``` [Partytown](https://partytown.builder.io/) is used under the hood to provide this functionality. ## Behavior - This will land as an experimental feature and will only work behind an opt-in flag in `next.config.js`: ```js experimental: { nextScriptWorkers: true } ``` - This setup use a similar approach to how ESLint and Typescript is used in Next.js by showing an error to the user to install the dependency locally themselves if they've enabled the experimental `nextScriptWorkers` flag. <img width="1068" alt="Screen Shot 2022-03-03 at 2 33 13 PM" src="https://user-images.githubusercontent.com/12476932/156639227-42af5353-a2a6-4126-936e-269112809651.png"> - For Partytown to work, a number of static files must be served directly from the site (see [docs](https://partytown.builder.io/copy-library-files)). In this PR, these files are automatically copied to a `~partytown` directory in `.next/static` during `next build` and `next dev` if the `nextScriptWorkers` flag is set to true. ## Checklist - [X] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. - [X] Related issues linked using `fixes #number` - [X] Integration tests added - [X] Documentation added - [ ] Telemetry added. In case of a feature if it's used or not. This PR fixes #31517.
2022-03-11 23:26:46 +01:00
import { verifyPartytownSetup } from '../../lib/verify-partytown-setup'
import {
PHASE_DEVELOPMENT_SERVER,
CLIENT_STATIC_FILES_PATH,
DEV_CLIENT_PAGES_MANIFEST,
DEV_MIDDLEWARE_MANIFEST,
COMPILER_NAMES,
} from '../../shared/lib/constants'
import Server, { WrappedBuildError } from '../next-server'
import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher'
import { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'
Refactor Page Paths utils and Middleware Plugin (#36576) This PR brings some significant refactoring in preparation for upcoming middleware changes. Each commit can be reviewed independently, here is a summary of what each one does and the reasoning behind it: - [Move pagesDir to next-dev-server](https://github.com/javivelasco/next.js/pull/12/commits/f2fe154c007379f71c14960ddc553eaaaf786ffa) simply moves the `pagesDir` property to the dev server which is the only place where it is needed. Having it for every server is misleading. - [Move (de)normalize page path utils to a file page-path-utils.ts](https://github.com/javivelasco/next.js/pull/12/commits/27cedf087187b9632ef82a34b3af9cc4fe05d98b) Moves the functions to normalize and denormalize page paths to a single file that is intended to hold every utility function that transforms page paths. Since those are complementary it makes sense to have them together. I also added explanatory comments on why they are not idempotent and examples for input -> output that I find very useful. - [Extract removePagePathTail](https://github.com/javivelasco/next.js/pull/12/commits/6b121332aa9d3e50bd0f28b691fb7faea1b95f51) This extracts a function to remove the tail on a page path (absolute or relative). I'm sure there will be other contexts where we can use it. - [Extract getPagePaths and refactor findPageFile](https://github.com/javivelasco/next.js/pull/12/commits/cf2c7b842eebd8c02f23e79345681a794516b646) This extracts a function `getPagePaths` that is used to generate an array of paths to inspect when looking for a page file from `findPageFile`. Then it refactors such function to use it parallelizing lookups. This will allow us to print every path we look at when looking for a file which can be useful for debugging. It also adds a `flatten` helper. - [Refactor onDemandEntryHandler](https://github.com/javivelasco/next.js/pull/12/commits/4be685c37e3d1b797e929ea4f31495ed7b00e1cc) I've found this one quite difficult to understand so it is refactored to use some of the previously mentioned functions and make it easier to read. - [Extract absolutePagePath util](https://github.com/javivelasco/next.js/pull/12/commits/3bc078347426c73491a076d54ef4de977d9da073) Extracts yet another util from the `next-dev-server` that transforms an absolute path into a page name. Of course it adds comments, parameters and examples. - [Refactor MiddlewarePlugin](https://github.com/javivelasco/next.js/pull/12/commits/c595a2cc629b358cc61861a8a4848b7890d0a15b) This is the most significant change. The logic here was very hard to understand so it is totally redistributed with comments. This also removes a global variable `ssrEntries` that was deprecated in favour of module metadata added to Webpack from loaders keeping less dependencies. It also adds types and makes a clear distinction between phases where we statically analyze the code, find metadata and generate the manifest file cc @shuding @huozhi EDIT: - [Split page path utils](https://github.com/vercel/next.js/pull/36576/commits/158fb002d02887d7ce4be6747cf550a825a426eb) After seeing one of the utils was being used by the client while it was defined originally in the server, with this PR we are splitting the util into multiple files and moving it to `shared/lib` in order to make explicit that those can be also imported from client.
2022-04-30 13:19:27 +02:00
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
import { absolutePathToPage } from '../../shared/lib/page-path/absolute-path-to-page'
import Router from '../router'
import { getPathMatch } from '../../shared/lib/router/utils/path-match'
import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'
import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'
import { eventCliSession } from '../../telemetry/events'
import { Telemetry } from '../../telemetry/storage'
import { setGlobal } from '../../trace'
import HotReloader from './hot-reloader'
import { findPageFile, isLayoutsLeafPage } from '../lib/find-page-file'
import { getNodeOptionsWithoutInspect } from '../lib/utils'
import {
UnwrapPromise,
withCoalescedInvoke,
} from '../../lib/coalesced-function'
import { loadDefaultErrorComponents } from '../load-components'
import { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'
import {
createOriginalStackFrame,
getErrorSource,
getSourceById,
parseStack,
} from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import * as Log from '../../build/output/log'
import isError, { getProperError } from '../../lib/is-error'
import { getRouteRegex } from '../../shared/lib/router/utils/route-regex'
import { getSortedRoutes, isDynamicRoute } from '../../shared/lib/router/utils'
import { runDependingOnPageType } from '../../build/entries'
import { NodeNextResponse, NodeNextRequest } from '../base-http/node'
import { getPageStaticInfo } from '../../build/analysis/get-page-static-info'
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
2022-05-25 11:46:26 +02:00
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import {
getPossibleMiddlewareFilenames,
isMiddlewareFile,
NestedMiddlewareError,
} from '../../build/utils'
2022-08-13 18:55:55 +02:00
import { getDefineEnv } from '../../build/webpack-config'
import loadJsConfig from '../../build/load-jsconfig'
// Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: React.FunctionComponent
const ReactDevOverlay = (props: any) => {
if (ReactDevOverlayImpl === undefined) {
ReactDevOverlayImpl =
require('next/dist/compiled/@next/react-dev-overlay/dist/client').ReactDevOverlay
}
return ReactDevOverlayImpl(props)
}
export interface Options extends ServerOptions {
/**
* Tells of Next.js is running from the `next dev` command
*/
isNextDevCommand?: boolean
}
export default class DevServer extends Server {
private devReady: Promise<void>
private setDevReady?: Function
private webpackWatcher?: Watchpack | null
private hotReloader?: HotReloader
private isCustomServer: boolean
protected sortedRoutes?: string[]
private addedUpgradeListener = false
private pagesDir?: string
2022-05-25 11:46:26 +02:00
private appDir?: string
private actualMiddlewareFile?: string
private middleware?: MiddlewareRoutingItem
private edgeFunctions?: RoutingItem[]
private verifyingTypeScript?: boolean
private usingTypeScript?: boolean
protected staticPathsWorker?: { [key: string]: any } & {
loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths
}
private getStaticPathsWorker(): { [key: string]: any } & {
loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths
} {
if (this.staticPathsWorker) {
return this.staticPathsWorker
}
this.staticPathsWorker = new Worker(
require.resolve('./static-paths-worker'),
{
maxRetries: 1,
numWorkers: this.nextConfig.experimental.cpus,
enableWorkerThreads: this.nextConfig.experimental.workerThreads,
forkOptions: {
env: {
...process.env,
// discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers
// would be started if user launch Next.js in debugging mode. The number of debuggers is linked to
// the number of workers Next.js tries to launch. The only worker users are interested in debugging
// is the main Next.js one
NODE_OPTIONS: getNodeOptionsWithoutInspect(),
},
},
}
) as Worker & {
loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths
}
this.staticPathsWorker.getStdout().pipe(process.stdout)
this.staticPathsWorker.getStderr().pipe(process.stderr)
return this.staticPathsWorker
}
constructor(options: Options) {
Add experimental SPR support (#8832) * initial commit for SPRv2 * Add initial SPR cache handling * update SPR handling * Implement SPR handling in render * Update tests, handle caching with serverless next start, add TODOs, and update manifest generating * Handle no prerender-manifest from not being used * Fix url.parse error * Apply suggestions from code review Co-Authored-By: Joe Haddad <joe.haddad@zeit.co> * Replace set with constants in next-page-config * simplify sprStatus.used * Add error if getStaticProps is used with getInitialProps * Remove stale TODO * Update revalidate values in SPR cache for non-seeded routes * Apply suggestions from code review * Remove concurrency type * Rename variable for clarity * Add copying prerender files during export * Add comment for clarity * Fix exporting * Update comment * Add additional note * Rename variable * Update to not re-export SPR pages from build * Hard navigate when fetching data fails * Remove default extension * Add brackets * Add checking output files to prerender tests * Adjust export move logic * Clarify behavior of export aggregation * Update variable names for clarity * Update tests * Add comment * s/an oxymoron/contradictory/ * rename * Extract error case * Add tests for exporting SPR pages and update /_next/data endpoint to end with .json * Relocate variable * Adjust route building * Rename to unstable * Rename unstable_getStaticParams * Fix linting * Only add this when a data request * Update prerender data tests * s/isServerless/isLikeServerless/ * Don't rely on query for `next start` in serverless mode * Rename var * Update renderedDuringBuild check * Add test for dynamic param with bracket * Fix serverless next start handling * remove todo * Adjust comment * Update calculateRevalidate * Remove cache logic from render.tsx * Remove extra imports * Move SPR cache logic to next-server * Remove old isDynamic prop * Add calling App getInitialProps for SPR pages * Update revalidate logic * Add isStale to SprCacheValue * Update headers for SPR * add awaiting pendingRevalidation * Dont return null for revalidation render * Adjust logic * Be sure to remove coalesced render * Fix data for serverless * Create a method coalescing utility * Remove TODO * Extract send payload helper * Wrap in-line * Move around some code * Add tests for de-duping and revalidating * Update prerender manifest test
2019-09-24 10:50:04 +02:00
super({ ...options, dev: true })
this.renderOpts.dev = true
2020-05-15 20:14:44 +02:00
;(this.renderOpts as any).ErrorDebug = ReactDevOverlay
2020-05-18 21:24:37 +02:00
this.devReady = new Promise((resolve) => {
Improve dev experience by listening faster (#5902) As I detailed in [this thread on Spectrum](https://spectrum.chat/?t=3df7b1fb-7331-4ca4-af35-d9a8b1cacb2c), the dev experience would be a lot nicer if the server started listening as soon as possible, before the slow initialization steps. That way, instead of manually polling the dev URL until the server's up (this can take a long time!), I can open it right away and the responses will be delivered when the dev server is done initializing. This makes a few changes to the dev server: * Move `HotReloader` creation to `prepare`. Ideally, more things (from the non-dev `Server`) would be moved to a later point as well, because creating `next({ ... })` is quite slow. * In `run`, wait for a promise to resolve before doing anything. This promise automatically gets resolved whenever `prepare` finishes successfully. And the `next dev` and `next start` scripts: * Since we want to log that the server is ready/listening before the intensive build process kicks off, we return the app instance from `startServer` and the scripts call `app.prepare()`. This should all be backwards compatible, including with all existing custom server recommendations that essentially say `app.prepare().then(listen)`. But now, we could make an even better recommendation: start listening right away, then call `app.prepare()` in the `listen` callback. Users would be free to make that change and get better DX. Try it and I doubt you'll want to go back to the old way. :)
2018-12-17 12:09:44 +01:00
this.setDevReady = resolve
})
;(this.renderOpts as any).ampSkipValidation =
this.nextConfig.experimental?.amp?.skipValidation ?? false
;(this.renderOpts as any).ampValidator = (
html: string,
pathname: string
) => {
const validatorPath =
this.nextConfig.experimental &&
this.nextConfig.experimental.amp &&
this.nextConfig.experimental.amp.validator
const AmpHtmlValidator =
require('next/dist/compiled/amphtml-validator') as typeof import('next/dist/compiled/amphtml-validator')
2020-05-18 21:24:37 +02:00
return AmpHtmlValidator.getInstance(validatorPath).then((validator) => {
const result = validator.validateString(html)
ampValidation(
pathname,
result.errors
2020-05-18 21:24:37 +02:00
.filter((e) => e.severity === 'ERROR')
.filter((e) => this._filterAmpDevelopmentScript(html, e)),
result.errors.filter((e) => e.severity !== 'ERROR')
)
})
}
if (fs.existsSync(pathJoin(this.dir, 'static'))) {
console.warn(
`The static directory has been deprecated in favor of the public directory. https://nextjs.org/docs/messages/static-dir-deprecated`
)
}
// setup upgrade listener eagerly when we can otherwise
// it will be done on the first request via req.socket.server
if (options.httpServer) {
this.setupWebSocketHandler(options.httpServer)
}
this.isCustomServer = !options.isNextDevCommand
// TODO: hot-reload root/pages dirs?
2022-05-25 11:46:26 +02:00
const { pages: pagesDir, appDir } = findPagesDir(
this.dir,
2022-05-25 11:46:26 +02:00
this.nextConfig.experimental.appDir
)
this.pagesDir = pagesDir
2022-05-25 11:46:26 +02:00
this.appDir = appDir
}
protected getBuildId(): string {
return 'development'
}
async addExportPathMapRoutes() {
// Makes `next export` exportPathMap work in development mode.
// So that the user doesn't have to define a custom server reading the exportPathMap
if (this.nextConfig.exportPathMap) {
console.log('Defining routes from exportPathMap')
const exportPathMap = await this.nextConfig.exportPathMap(
{},
{
dev: true,
dir: this.dir,
outDir: null,
distDir: this.distDir,
buildId: this.buildId,
}
) // In development we can't give a default path mapping
for (const path in exportPathMap) {
const { page, query = {} } = exportPathMap[path]
this.router.addFsRoute({
match: getPathMatch(path),
type: 'route',
name: `${path} exportpathmap route`,
fn: async (req, res, _params, parsedUrl) => {
const { query: urlQuery } = parsedUrl
Object.keys(urlQuery)
2020-05-18 21:24:37 +02:00
.filter((key) => query[key] === undefined)
.forEach((key) =>
console.warn(
`Url '${path}' defines a query parameter '${key}' that is missing in exportPathMap`
)
)
const mergedQuery = { ...urlQuery, ...query }
await this.render(req, res, page, mergedQuery, parsedUrl, true)
return {
finished: true,
}
},
})
}
}
}
async startWatcher(): Promise<void> {
2019-06-25 16:28:48 +02:00
if (this.webpackWatcher) {
return
}
const regexPageExtension = new RegExp(
`\\.+(?:${this.nextConfig.pageExtensions.join('|')})$`
)
let resolved = false
return new Promise(async (resolve, reject) => {
if (this.pagesDir) {
// Watchpack doesn't emit an event for an empty directory
fs.readdir(this.pagesDir, (_, files) => {
if (files?.length) {
return
}
if (!resolved) {
resolve()
resolved = true
}
})
}
const wp = (this.webpackWatcher = new Watchpack({
ignored: /([/\\]node_modules[/\\]|[/\\]\.next[/\\]|[/\\]\.git[/\\])/,
}))
const pages = this.pagesDir ? [this.pagesDir] : []
2022-05-25 11:46:26 +02:00
const app = this.appDir ? [this.appDir] : []
const directories = [...pages, ...app]
const files = this.pagesDir
? getPossibleMiddlewareFilenames(
pathJoin(this.pagesDir, '..'),
this.nextConfig.pageExtensions
)
: []
let nestedMiddleware: string[] = []
const envFiles = [
'.env.development.local',
'.env.local',
'.env.development',
'.env',
].map((file) => pathJoin(this.dir, file))
files.push(...envFiles)
// tsconfig/jsonfig paths hot-reloading
const tsconfigPaths = [
pathJoin(this.dir, 'tsconfig.json'),
pathJoin(this.dir, 'jsconfig.json'),
]
files.push(...tsconfigPaths)
wp.watch({ directories: [this.dir], startTime: 0 })
const fileWatchTimes = new Map()
let enabledTypeScript = this.usingTypeScript
wp.on('aggregated', async () => {
let middlewareMatchers: MiddlewareMatcher[] | undefined
const routedPages: string[] = []
const knownFiles = wp.getTimeInfoEntries()
const appPaths: Record<string, string[]> = {}
const edgeRoutesSet = new Set<string>()
let envChange = false
let tsconfigChange = false
for (const [fileName, meta] of knownFiles) {
if (
!files.includes(fileName) &&
!directories.some((dir) => fileName.startsWith(dir))
) {
continue
}
const watchTime = fileWatchTimes.get(fileName)
const watchTimeChange = watchTime && watchTime !== meta?.timestamp
fileWatchTimes.set(fileName, meta.timestamp)
if (envFiles.includes(fileName)) {
if (watchTimeChange) {
envChange = true
}
continue
}
if (tsconfigPaths.includes(fileName)) {
if (fileName.endsWith('tsconfig.json')) {
enabledTypeScript = true
}
if (watchTimeChange) {
tsconfigChange = true
}
continue
}
if (
meta?.accuracy === undefined ||
!regexPageExtension.test(fileName)
) {
continue
}
2022-05-25 11:46:26 +02:00
const isAppPath = Boolean(
this.appDir &&
normalizePathSep(fileName).startsWith(
2022-05-25 11:46:26 +02:00
normalizePathSep(this.appDir)
)
)
const rootFile = absolutePathToPage(fileName, {
pagesDir: this.dir,
extensions: this.nextConfig.pageExtensions,
})
const staticInfo = await getPageStaticInfo({
pageFilePath: fileName,
nextConfig: this.nextConfig,
page: rootFile,
isDev: true,
})
if (isMiddlewareFile(rootFile)) {
this.actualMiddlewareFile = rootFile
middlewareMatchers = staticInfo.middleware?.matchers || [
{ regexp: '.*' },
]
continue
}
if (fileName.endsWith('.ts') || fileName.endsWith('.tsx')) {
enabledTypeScript = true
}
let pageName = absolutePathToPage(fileName, {
pagesDir: isAppPath ? this.appDir! : this.pagesDir!,
extensions: this.nextConfig.pageExtensions,
2022-05-25 11:46:26 +02:00
keepIndex: isAppPath,
})
2022-05-25 11:46:26 +02:00
if (isAppPath) {
if (!isLayoutsLeafPage(fileName)) {
continue
}
const originalPageName = pageName
pageName = normalizeAppPath(pageName) || '/'
if (!appPaths[pageName]) {
appPaths[pageName] = []
}
appPaths[pageName].push(originalPageName)
if (routedPages.includes(pageName)) {
continue
}
} else {
// /index is preserved for root folder
pageName = pageName.replace(/\/index$/, '') || '/'
}
Refactor Page Paths utils and Middleware Plugin (#36576) This PR brings some significant refactoring in preparation for upcoming middleware changes. Each commit can be reviewed independently, here is a summary of what each one does and the reasoning behind it: - [Move pagesDir to next-dev-server](https://github.com/javivelasco/next.js/pull/12/commits/f2fe154c007379f71c14960ddc553eaaaf786ffa) simply moves the `pagesDir` property to the dev server which is the only place where it is needed. Having it for every server is misleading. - [Move (de)normalize page path utils to a file page-path-utils.ts](https://github.com/javivelasco/next.js/pull/12/commits/27cedf087187b9632ef82a34b3af9cc4fe05d98b) Moves the functions to normalize and denormalize page paths to a single file that is intended to hold every utility function that transforms page paths. Since those are complementary it makes sense to have them together. I also added explanatory comments on why they are not idempotent and examples for input -> output that I find very useful. - [Extract removePagePathTail](https://github.com/javivelasco/next.js/pull/12/commits/6b121332aa9d3e50bd0f28b691fb7faea1b95f51) This extracts a function to remove the tail on a page path (absolute or relative). I'm sure there will be other contexts where we can use it. - [Extract getPagePaths and refactor findPageFile](https://github.com/javivelasco/next.js/pull/12/commits/cf2c7b842eebd8c02f23e79345681a794516b646) This extracts a function `getPagePaths` that is used to generate an array of paths to inspect when looking for a page file from `findPageFile`. Then it refactors such function to use it parallelizing lookups. This will allow us to print every path we look at when looking for a file which can be useful for debugging. It also adds a `flatten` helper. - [Refactor onDemandEntryHandler](https://github.com/javivelasco/next.js/pull/12/commits/4be685c37e3d1b797e929ea4f31495ed7b00e1cc) I've found this one quite difficult to understand so it is refactored to use some of the previously mentioned functions and make it easier to read. - [Extract absolutePagePath util](https://github.com/javivelasco/next.js/pull/12/commits/3bc078347426c73491a076d54ef4de977d9da073) Extracts yet another util from the `next-dev-server` that transforms an absolute path into a page name. Of course it adds comments, parameters and examples. - [Refactor MiddlewarePlugin](https://github.com/javivelasco/next.js/pull/12/commits/c595a2cc629b358cc61861a8a4848b7890d0a15b) This is the most significant change. The logic here was very hard to understand so it is totally redistributed with comments. This also removes a global variable `ssrEntries` that was deprecated in favour of module metadata added to Webpack from loaders keeping less dependencies. It also adds types and makes a clear distinction between phases where we statically analyze the code, find metadata and generate the manifest file cc @shuding @huozhi EDIT: - [Split page path utils](https://github.com/vercel/next.js/pull/36576/commits/158fb002d02887d7ce4be6747cf550a825a426eb) After seeing one of the utils was being used by the client while it was defined originally in the server, with this PR we are splitting the util into multiple files and moving it to `shared/lib` in order to make explicit that those can be also imported from client.
2022-04-30 13:19:27 +02:00
/**
* If there is a middleware that is not declared in the root we will
* warn without adding it so it doesn't make its way into the system.
*/
if (/[\\\\/]_middleware$/.test(pageName)) {
nestedMiddleware.push(pageName)
continue
}
await runDependingOnPageType({
page: pageName,
pageRuntime: staticInfo.runtime,
onClient: () => {},
onServer: () => {
routedPages.push(pageName)
},
onEdgeServer: () => {
routedPages.push(pageName)
edgeRoutesSet.add(pageName)
},
})
}
if (!this.usingTypeScript && enabledTypeScript) {
// we tolerate the error here as this is best effort
// and the manual install command will be shown
await this.verifyTypeScript()
.then(() => {
tsconfigChange = true
})
.catch(() => {})
}
if (envChange || tsconfigChange) {
if (envChange) {
this.loadEnvConfig({ dev: true, forceReload: true })
}
let tsconfigResult:
| UnwrapPromise<ReturnType<typeof loadJsConfig>>
| undefined
if (tsconfigChange) {
try {
tsconfigResult = await loadJsConfig(this.dir, this.nextConfig)
} catch (_) {
/* do we want to log if there are syntax errors in tsconfig while editing? */
}
}
2022-08-13 18:55:55 +02:00
this.hotReloader?.activeConfigs?.forEach((config, idx) => {
const isClient = idx === 0
const isNodeServer = idx === 1
const isEdgeServer = idx === 2
const hasRewrites =
this.customRoutes.rewrites.afterFiles.length > 0 ||
this.customRoutes.rewrites.beforeFiles.length > 0 ||
this.customRoutes.rewrites.fallback.length > 0
if (tsconfigChange) {
config.resolve?.plugins?.forEach((plugin: any) => {
// look for the JsConfigPathsPlugin and update with
// the latest paths/baseUrl config
if (plugin && plugin.jsConfigPlugin && tsconfigResult) {
const { resolvedBaseUrl, jsConfig } = tsconfigResult
const currentResolvedBaseUrl = plugin.resolvedBaseUrl
const resolvedUrlIndex = config.resolve?.modules?.findIndex(
(item) => item === currentResolvedBaseUrl
)
if (
resolvedBaseUrl &&
resolvedBaseUrl !== currentResolvedBaseUrl
) {
// remove old baseUrl and add new one
if (resolvedUrlIndex && resolvedUrlIndex > -1) {
config.resolve?.modules?.splice(resolvedUrlIndex, 1)
}
config.resolve?.modules?.push(resolvedBaseUrl)
2022-08-13 18:55:55 +02:00
}
if (jsConfig?.compilerOptions?.paths && resolvedBaseUrl) {
Object.keys(plugin.paths).forEach((key) => {
delete plugin.paths[key]
})
Object.assign(plugin.paths, jsConfig.compilerOptions.paths)
plugin.resolvedBaseUrl = resolvedBaseUrl
}
}
})
}
if (envChange) {
config.plugins?.forEach((plugin: any) => {
// we look for the DefinePlugin definitions so we can
// update them on the active compilers
if (
plugin &&
typeof plugin.definitions === 'object' &&
plugin.definitions.__NEXT_DEFINE_ENV
) {
const newDefine = getDefineEnv({
dev: true,
config: this.nextConfig,
distDir: this.distDir,
isClient,
hasRewrites,
hasReactRoot: this.hotReloader?.hasReactRoot,
isNodeServer,
isEdgeServer,
hasServerComponents: this.hotReloader?.hasServerComponents,
})
Object.keys(plugin.definitions).forEach((key) => {
if (!(key in newDefine)) {
delete plugin.definitions[key]
}
})
Object.assign(plugin.definitions, newDefine)
}
})
}
2022-08-13 18:55:55 +02:00
})
this.hotReloader?.invalidate()
}
if (nestedMiddleware.length > 0) {
Log.error(
new NestedMiddlewareError(
nestedMiddleware,
this.dir,
this.pagesDir!
).message
)
nestedMiddleware = []
}
// Make sure to sort parallel routes to make the result deterministic.
this.appPathRoutes = Object.fromEntries(
Object.entries(appPaths).map(([k, v]) => [k, v.sort()])
)
const edgeRoutes = Array.from(edgeRoutesSet)
this.edgeFunctions = getSortedRoutes(edgeRoutes).map((page) => {
const matchedAppPaths = this.getOriginalAppPaths(page)
if (Array.isArray(matchedAppPaths)) {
page = matchedAppPaths[0]
}
const edgeRegex = getRouteRegex(page)
return {
match: getRouteMatcher(edgeRegex),
page,
re: edgeRegex.re,
}
})
this.middleware = middlewareMatchers
? {
match: getMiddlewareRouteMatcher(middlewareMatchers),
page: '/',
matchers: middlewareMatchers,
}
: undefined
try {
// we serve a separate manifest with all pages for the client in
// dev mode so that we can match a page after a rewrite on the client
// before it has been built and is populated in the _buildManifest
const sortedRoutes = getSortedRoutes(routedPages)
if (
!this.sortedRoutes?.every((val, idx) => val === sortedRoutes[idx])
) {
// emit the change so clients fetch the update
this.hotReloader!.send(undefined, { devPagesManifest: true })
}
this.sortedRoutes = sortedRoutes
this.dynamicRoutes = this.sortedRoutes
.filter(isDynamicRoute)
.map((page) => ({
page,
match: getRouteMatcher(getRouteRegex(page)),
}))
this.router.setDynamicRoutes(this.dynamicRoutes)
this.router.setCatchallMiddleware(
this.generateCatchAllMiddlewareRoute(true)
)
if (!resolved) {
resolve()
resolved = true
}
} catch (e) {
if (!resolved) {
reject(e)
resolved = true
} else {
console.warn('Failed to reload dynamic routes:', e)
}
}
})
})
}
async stopWatcher(): Promise<void> {
if (!this.webpackWatcher) {
return
}
this.webpackWatcher.close()
this.webpackWatcher = null
}
private async verifyTypeScript() {
if (this.verifyingTypeScript) {
return
}
try {
this.verifyingTypeScript = true
const verifyResult = await verifyTypeScriptSetup({
dir: this.dir,
intentDirs: [this.pagesDir, this.appDir].filter(Boolean) as string[],
typeCheckPreflight: false,
tsconfigPath: this.nextConfig.typescript.tsconfigPath,
disableStaticImages: this.nextConfig.images.disableStaticImages,
})
if (verifyResult.version) {
this.usingTypeScript = true
}
} finally {
this.verifyingTypeScript = false
}
}
async prepare(): Promise<void> {
setGlobal('distDir', this.distDir)
setGlobal('phase', PHASE_DEVELOPMENT_SERVER)
2019-11-09 23:34:53 +01:00
await this.verifyTypeScript()
this.customRoutes = await loadCustomRoutes(this.nextConfig)
2019-11-09 23:34:53 +01:00
// reload router
const { redirects, rewrites, headers } = this.customRoutes
if (
rewrites.beforeFiles.length ||
rewrites.afterFiles.length ||
rewrites.fallback.length ||
redirects.length ||
headers.length
) {
this.router = new Router(this.generateRoutes())
2019-11-09 23:34:53 +01:00
}
this.hotReloader = new HotReloader(this.dir, {
Refactor Page Paths utils and Middleware Plugin (#36576) This PR brings some significant refactoring in preparation for upcoming middleware changes. Each commit can be reviewed independently, here is a summary of what each one does and the reasoning behind it: - [Move pagesDir to next-dev-server](https://github.com/javivelasco/next.js/pull/12/commits/f2fe154c007379f71c14960ddc553eaaaf786ffa) simply moves the `pagesDir` property to the dev server which is the only place where it is needed. Having it for every server is misleading. - [Move (de)normalize page path utils to a file page-path-utils.ts](https://github.com/javivelasco/next.js/pull/12/commits/27cedf087187b9632ef82a34b3af9cc4fe05d98b) Moves the functions to normalize and denormalize page paths to a single file that is intended to hold every utility function that transforms page paths. Since those are complementary it makes sense to have them together. I also added explanatory comments on why they are not idempotent and examples for input -> output that I find very useful. - [Extract removePagePathTail](https://github.com/javivelasco/next.js/pull/12/commits/6b121332aa9d3e50bd0f28b691fb7faea1b95f51) This extracts a function to remove the tail on a page path (absolute or relative). I'm sure there will be other contexts where we can use it. - [Extract getPagePaths and refactor findPageFile](https://github.com/javivelasco/next.js/pull/12/commits/cf2c7b842eebd8c02f23e79345681a794516b646) This extracts a function `getPagePaths` that is used to generate an array of paths to inspect when looking for a page file from `findPageFile`. Then it refactors such function to use it parallelizing lookups. This will allow us to print every path we look at when looking for a file which can be useful for debugging. It also adds a `flatten` helper. - [Refactor onDemandEntryHandler](https://github.com/javivelasco/next.js/pull/12/commits/4be685c37e3d1b797e929ea4f31495ed7b00e1cc) I've found this one quite difficult to understand so it is refactored to use some of the previously mentioned functions and make it easier to read. - [Extract absolutePagePath util](https://github.com/javivelasco/next.js/pull/12/commits/3bc078347426c73491a076d54ef4de977d9da073) Extracts yet another util from the `next-dev-server` that transforms an absolute path into a page name. Of course it adds comments, parameters and examples. - [Refactor MiddlewarePlugin](https://github.com/javivelasco/next.js/pull/12/commits/c595a2cc629b358cc61861a8a4848b7890d0a15b) This is the most significant change. The logic here was very hard to understand so it is totally redistributed with comments. This also removes a global variable `ssrEntries` that was deprecated in favour of module metadata added to Webpack from loaders keeping less dependencies. It also adds types and makes a clear distinction between phases where we statically analyze the code, find metadata and generate the manifest file cc @shuding @huozhi EDIT: - [Split page path utils](https://github.com/vercel/next.js/pull/36576/commits/158fb002d02887d7ce4be6747cf550a825a426eb) After seeing one of the utils was being used by the client while it was defined originally in the server, with this PR we are splitting the util into multiple files and moving it to `shared/lib` in order to make explicit that those can be also imported from client.
2022-04-30 13:19:27 +02:00
pagesDir: this.pagesDir,
distDir: this.distDir,
config: this.nextConfig,
previewProps: this.getPreviewProps(),
buildId: this.buildId,
rewrites,
2022-05-25 11:46:26 +02:00
appDir: this.appDir,
})
await super.prepare()
await this.addExportPathMapRoutes()
2022-08-13 18:55:55 +02:00
await this.hotReloader.start(true)
await this.startWatcher()
this.setDevReady!()
Adds web worker support to `<Script />` using Partytown (#34244) ## Summary This PR adds a new `worker` strategy to the `<Script />` component that automatically relocates and executes the script in a web worker. ```jsx <Script strategy="worker" ... /> ``` [Partytown](https://partytown.builder.io/) is used under the hood to provide this functionality. ## Behavior - This will land as an experimental feature and will only work behind an opt-in flag in `next.config.js`: ```js experimental: { nextScriptWorkers: true } ``` - This setup use a similar approach to how ESLint and Typescript is used in Next.js by showing an error to the user to install the dependency locally themselves if they've enabled the experimental `nextScriptWorkers` flag. <img width="1068" alt="Screen Shot 2022-03-03 at 2 33 13 PM" src="https://user-images.githubusercontent.com/12476932/156639227-42af5353-a2a6-4126-936e-269112809651.png"> - For Partytown to work, a number of static files must be served directly from the site (see [docs](https://partytown.builder.io/copy-library-files)). In this PR, these files are automatically copied to a `~partytown` directory in `.next/static` during `next build` and `next dev` if the `nextScriptWorkers` flag is set to true. ## Checklist - [X] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. - [X] Related issues linked using `fixes #number` - [X] Integration tests added - [X] Documentation added - [ ] Telemetry added. In case of a feature if it's used or not. This PR fixes #31517.
2022-03-11 23:26:46 +01:00
if (this.nextConfig.experimental.nextScriptWorkers) {
await verifyPartytownSetup(
this.dir,
pathJoin(this.distDir, CLIENT_STATIC_FILES_PATH)
)
}
const telemetry = new Telemetry({ distDir: this.distDir })
telemetry.record(
eventCliSession(this.distDir, this.nextConfig, {
webpackVersion: 5,
cliCommand: 'dev',
isSrcDir:
(!!this.pagesDir &&
relative(this.dir, this.pagesDir).startsWith('src')) ||
(!!this.appDir && relative(this.dir, this.appDir).startsWith('src')),
hasNowJson: !!(await findUp('now.json', { cwd: this.dir })),
isCustomServer: this.isCustomServer,
})
)
// This is required by the tracing subsystem.
setGlobal('telemetry', telemetry)
process.on('unhandledRejection', (reason) => {
this.logErrorWithOriginalStack(reason, 'unhandledRejection').catch(
() => {}
)
})
process.on('uncaughtException', (err) => {
this.logErrorWithOriginalStack(err, 'uncaughtException').catch(() => {})
})
}
protected async close(): Promise<void> {
await this.stopWatcher()
await this.getStaticPathsWorker().end()
Improve dev experience by listening faster (#5902) As I detailed in [this thread on Spectrum](https://spectrum.chat/?t=3df7b1fb-7331-4ca4-af35-d9a8b1cacb2c), the dev experience would be a lot nicer if the server started listening as soon as possible, before the slow initialization steps. That way, instead of manually polling the dev URL until the server's up (this can take a long time!), I can open it right away and the responses will be delivered when the dev server is done initializing. This makes a few changes to the dev server: * Move `HotReloader` creation to `prepare`. Ideally, more things (from the non-dev `Server`) would be moved to a later point as well, because creating `next({ ... })` is quite slow. * In `run`, wait for a promise to resolve before doing anything. This promise automatically gets resolved whenever `prepare` finishes successfully. And the `next dev` and `next start` scripts: * Since we want to log that the server is ready/listening before the intensive build process kicks off, we return the app instance from `startServer` and the scripts call `app.prepare()`. This should all be backwards compatible, including with all existing custom server recommendations that essentially say `app.prepare().then(listen)`. But now, we could make an even better recommendation: start listening right away, then call `app.prepare()` in the `listen` callback. Users would be free to make that change and get better DX. Try it and I doubt you'll want to go back to the old way. :)
2018-12-17 12:09:44 +01:00
if (this.hotReloader) {
await this.hotReloader.stop()
}
}
protected async hasPage(pathname: string): Promise<boolean> {
let normalizedPath: string
try {
normalizedPath = normalizePagePath(pathname)
} catch (err) {
console.error(err)
// if normalizing the page fails it means it isn't valid
// so it doesn't exist so don't throw and return false
// to ensure we return 404 instead of 500
return false
}
if (isMiddlewareFile(normalizedPath)) {
return findPageFile(
this.dir,
normalizedPath,
this.nextConfig.pageExtensions,
false
).then(Boolean)
}
2022-05-25 11:46:26 +02:00
// check appDir first if enabled
if (this.appDir) {
const pageFile = await findPageFile(
2022-05-25 11:46:26 +02:00
this.appDir,
normalizedPath,
this.nextConfig.pageExtensions,
true
)
if (pageFile) return true
}
if (this.pagesDir) {
const pageFile = await findPageFile(
this.pagesDir,
normalizedPath,
this.nextConfig.pageExtensions,
false
)
return !!pageFile
}
return false
}
protected async _beforeCatchAllRender(
req: BaseNextRequest,
res: BaseNextResponse,
params: Params,
parsedUrl: UrlWithParsedQuery
): Promise<boolean> {
const { pathname } = parsedUrl
const pathParts = params.path || []
const path = `/${pathParts.join('/')}`
// check for a public file, throwing error if there's a
// conflicting page
let decodedPath: string
try {
decodedPath = decodeURIComponent(path)
} catch (_) {
2021-07-05 18:31:32 +02:00
throw new DecodeError('failed to decode param')
}
if (await this.hasPublicFile(decodedPath)) {
if (await this.hasPage(pathname!)) {
const err = new Error(
`A conflicting public file and page file was found for path ${pathname} https://nextjs.org/docs/messages/conflicting-public-file-page`
)
res.statusCode = 500
await this.renderError(err, req, res, pathname!, {})
return true
}
await this.servePublic(req, res, pathParts)
return true
}
return false
}
private setupWebSocketHandler(server?: HTTPServer, _req?: NodeNextRequest) {
if (!this.addedUpgradeListener) {
this.addedUpgradeListener = true
server = server || (_req?.originalRequest.socket as any)?.server
if (!server) {
// this is very unlikely to happen but show an error in case
// it does somehow
Log.error(
`Invalid IncomingMessage received, make sure http.createServer is being used to handle requests.`
)
} else {
const { basePath } = this.nextConfig
server.on('upgrade', (req, socket, head) => {
let assetPrefix = (this.nextConfig.assetPrefix || '').replace(
/^\/+/,
''
)
// assetPrefix can be a proxy server with a url locally
// if so, it's needed to send these HMR requests with a rewritten url directly to /_next/webpack-hmr
// otherwise account for a path-like prefix when listening to socket events
if (assetPrefix.startsWith('http')) {
assetPrefix = ''
} else if (assetPrefix) {
assetPrefix = `/${assetPrefix}`
}
if (
req.url?.startsWith(
`${basePath || assetPrefix || ''}/_next/webpack-hmr`
)
) {
this.hotReloader?.onHMR(req, socket, head)
} else {
this.handleUpgrade(req, socket, head)
}
})
}
}
}
async runMiddleware(params: {
request: BaseNextRequest
response: BaseNextResponse
parsedUrl: ParsedUrl
parsed: UrlWithParsedQuery
middlewareList: MiddlewareRoutingItem[]
}) {
try {
const result = await super.runMiddleware({
...params,
onWarning: (warn) => {
this.logErrorWithOriginalStack(warn, 'warning')
},
})
if ('finished' in result) {
return result
}
result.waitUntil.catch((error) => {
this.logErrorWithOriginalStack(error, 'unhandledRejection')
})
return result
} catch (error) {
if (error instanceof DecodeError) {
throw error
}
/**
* We only log the error when it is not a MiddlewareNotFound error as
* in that case we should be already displaying a compilation error
* which is what makes the module not found.
*/
if (!(error instanceof MiddlewareNotFoundError)) {
this.logErrorWithOriginalStack(error)
}
const err = getProperError(error)
;(err as any).middleware = true
const { request, response, parsedUrl } = params
/**
* When there is a failure for an internal Next.js request from
* middleware we bypass the error without finishing the request
* so we can serve the required chunks to render the error.
*/
if (
request.url.includes('/_next/static') ||
request.url.includes('/__nextjs_original-stack-frame')
) {
return { finished: false }
}
response.statusCode = 500
this.renderError(err, request, response, parsedUrl.pathname)
return { finished: true }
}
}
async runEdgeFunction(params: {
req: BaseNextRequest
res: BaseNextResponse
query: ParsedUrlQuery
params: Params | undefined
page: string
appPaths: string[] | null
isAppPath: boolean
}) {
try {
fix(edge): error handling for edge route and middleware is inconsistent (#38401) ## What’s in there? This PR brings more consistency in how errors and warnings are reported when running code in the Edge Runtime: - Dynamic code evaluation (`eval()`, `new Function()`, `WebAssembly.instantiate()`, `WebAssembly.compile()`…) - Usage of Node.js global APIs (`BroadcastChannel`, `Buffer`, `TextDecoderStream`, `setImmediate()`...) - Usage of Node.js modules (`fs`, `path`, `child_process`…) The new error messages should mention *Edge Runtime* instead of *Middleware*, so they are valid in both cases. It also fixes a bug where the process polyfill would issue a warning for `process.cwd` (which is `undefined` but legit). Now, one has to invoke the function `process.cwd()` to trigger the error. It finally fixes the react-dev-overlay, where links from middleware and Edge API route files could not be opened because of the `(middleware)/` prefix in their name. About the later, please note that we can’t easily remove the prefix or change it for Edge API routes. It comes from the Webpack layer, which is the same for both. We may consider renaming it to *edge* instead in the future. ## How to test? These changes are almost fully covered with tests: ```bash pnpm testheadless --testPathPattern runtime-dynamic pnpm testheadless --testPathPattern runtime-with-node pnpm testheadless --testPathPattern runtime-module pnpm testheadless --testPathPattern middleware-dev-errors ``` To try them out manually, you can write a middleware and Edge route files like these: ```jsx // middleware.js import { NextResponse } from 'next/server' import { basename } from 'path' export default async function middleware() { eval('2+2') setImmediate(() => {}) basename() return NextResponse.next() } export const config = { matcher: '/' } ``` ```jsx // pages/api/route.js import { basename } from 'path' export default async function handle() { eval('2+2') setImmediate(() => {}) basename() return Response.json({ ok: true }) } export const config = { runtime: 'experimental-edge' } ``` The expected behaviours are: - [x] dev, middleware/edge route is using a node.js module: error at runtime (logs + read-dev-overlay): ```bash error - (middleware)/pages/api/route.js (1:0) @ Object.handle [as handler] error - The edge runtime does not support Node.js 'path' module. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime > 1 | import { basename } from "path"; 2 | export default async function handle() { ``` - [x] build, middleware/edge route is using a node.js module: warning but succeeds ```bash warn - Compiled with warnings ./middleware.js A Node.js module is loaded ('path' at line 4) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime ./pages/api/route.js A Node.js module is loaded ('path' at line 1) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime ``` - [x] production, middleware/edge route is using a node.js module: error at runtime (logs + 500 error) ```bash Error: The edge runtime does not support Node.js 'path' module. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime at <unknown> (file:///Users/damien/dev/next.js/packages/next/server/web/sandbox/context.ts:149) ``` - [x] dev, middleware/edge route is using a node.js global API: error at runtime (logs + read-dev-overlay): ```bash error - (middleware)/pages/api/route.js (4:2) @ Object.handle [as handler] error - A Node.js API is used (setImmediate) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime 2 | 3 | export default async function handle() { > 4 | setImmediate(() => {}) | ^ ``` - [x] build, middleware/edge route is using a node.js global API: warning but succeeds ```bash warn - Compiled with warnings ./middleware.js A Node.js API is used (setImmediate at line: 6) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime ./pages/api/route.js A Node.js API is used (setImmediate at line: 3) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime ``` - [x] production, middleware/edge route is using a node.js module: error at runtime (logs + 500 error) ```bash Error: A Node.js API is used (setImmediate) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime at <unknown> (file:///Users/damien/dev/next.js/packages/next/server/web/sandbox/context.ts:330) ``` - [x] dev, middleware/edge route is loading dynamic code: warning at runtime (logs + read-dev-overlay) and request succeeds (we allow dynamic code in dev only): ```bash warn - (middleware)/middleware.js (7:2) @ Object.middleware [as handler] warn - Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime 5 | 6 | export default async function middleware() { > 7 | eval('2+2') ``` - [x] build, middleware/edge route is loading dynamic code: build fails with error: ```bash Failed to compile. ./middleware.js Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Used by default ./pages/api/route.js Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Used by default ``` ## Notes to reviewers Edge-related errors are either issued from `next/server/web/sandbox/context.ts` file (runtime errors) or from `next/build/webpack/plugins/middleware-plugin.ts` (webpack compilation). The previous implementation (I’m pleading guilty here) was way too verbose: some errors (Node.js global APIs like using `process.cwd()`) could be reported several times, and the previous mechanism to dedupe them (in middleware-plugin) wasn’t really effective. Changes in tests are due to renaming existing tests such as `test/integration/middleware-with-node.js-apis` into `test/integration/edge-runtime-with-node.js-apis`. I extended them to cover Edge API route. @hanneslund I’ve pushed the improvement you did in https://github.com/vercel/next.js/pull/38289/ one step further to avoid duplication.
2022-07-21 16:53:23 +02:00
return super.runEdgeFunction({
...params,
onWarning: (warn) => {
this.logErrorWithOriginalStack(warn, 'warning')
},
})
} catch (error) {
if (error instanceof DecodeError) {
throw error
}
this.logErrorWithOriginalStack(error, 'warning')
const err = getProperError(error)
const { req, res, page } = params
res.statusCode = 500
this.renderError(err, req, res, page)
return null
}
}
async run(
req: NodeNextRequest,
res: NodeNextResponse,
parsedUrl: UrlWithParsedQuery
): Promise<void> {
await this.devReady
this.setupWebSocketHandler(undefined, req)
const { basePath } = this.nextConfig
let originalPathname: string | null = null
if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {
// strip basePath before handling dev bundles
// If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`
originalPathname = parsedUrl.pathname
parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)
}
const { pathname } = parsedUrl
if (pathname!.startsWith('/_next')) {
if (await fileExists(pathJoin(this.publicDir, '_next'))) {
throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)
}
}
const { finished = false } = await this.hotReloader!.run(
req.originalRequest,
res.originalResponse,
parsedUrl
)
if (finished) {
return
}
if (originalPathname) {
// restore the path before continuing so that custom-routes can accurately determine
// if they should match against the basePath or not
parsedUrl.pathname = originalPathname
}
try {
return await super.run(req, res, parsedUrl)
} catch (error) {
res.statusCode = 500
const err = getProperError(error)
try {
this.logErrorWithOriginalStack(err).catch(() => {})
return await this.renderError(err, req, res, pathname!, {
__NEXT_PAGE: (isError(err) && err.page) || pathname || '',
})
} catch (internalErr) {
console.error(internalErr)
res.body('Internal Server Error').send()
}
}
}
private async logErrorWithOriginalStack(
err?: unknown,
type?: 'unhandledRejection' | 'uncaughtException' | 'warning'
) {
let usedOriginalStack = false
if (isError(err) && err.stack) {
try {
const frames = parseStack(err.stack!)
feat: build edge functions with node.js modules and fail at runtime (#38234) ## What's in there? The Edge runtime [does not support Node.js modules](https://edge-runtime.vercel.app/features/available-apis#unsupported-apis). When building Next.js application, we currently fail the build when detecting node.js module imported from middleware. This is an blocker for using code that is conditionally loading node.js modules (based on platform/env detection), as @cramforce reported. This PR implements a new strategy where: - we can build such middleware/Edge API route code **with a warning** - we fail at run time, with graceful errors in dev (console & react-dev-overlay error) - we fail at run time, with console errors in production ## How to test? All cases are covered with integration tests. To try them live, create a simple app with a page, a `middleware.js` file and a `pages/api/route.js`file. Here are iconic examples: ### node.js modules ```js // middleware.js import { NextResponse } from 'next/server' // static import { basename } from 'path' export default async function middleware() { // dynamic const { basename } = await import('path') basename() return NextResponse.next() } export const config = { matcher: '/' } ``` ```js // pags/api/route.js // static import { isAbsolute } from 'path' export default async function handle() { // dynamic const { isAbsolute } = await import('path') return Response.json({ useNodeModule: isAbsolute('/test') }) } export const config = { runtime: 'experimental-edge' } ``` Desired error (+ source code highlight in dev): > The edge runtime does not support Node.js 'path' module Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime Desired warning at build time: > A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime - [x] in dev middleware, static, shows desired error on stderr - [x] in dev route, static, shows desired error on stderr - [x] in dev middleware, dynamic, shows desired error on stderr - [x] in dev route, dynamic, shows desired error on stderr - [x] in dev middleware, static, shows desired error on react error overlay - [x] in dev route, static, shows desired error on react error overlay - [x] in dev middleware, dynamic, shows desired error on react error overlay - [x] in dev route, dynamic, shows desired error on react error overlay - [x] builds middleware successfully, shows build warning, shows desired error on stderr on call - [x] builds route successfully, shows build warning, shows desired error on stderr on call ### 3rd party modules not found ```js // middleware.js import { NextResponse } from 'next/server' // static import Unknown from 'unknown' export default async function middleware() { // dynamic const Unknown = await import('unknown') new Unknown() return NextResponse.next() } ``` export const config = { matcher: '/' } ``` ```js // pags/api/route.js // static import Unknown from 'unknown' export default async function handle() { // dynamic const Unknown = await import('unknown') return Response.json({ use3rdPartyModule: Unknown() }) } export const config = { runtime: 'experimental-edge' } ``` Desired error (+ source code highlight in dev): > Module not found: Can't resolve 'does-not-exist' Learn More: https://nextjs.org/docs/messages/module-not-found - [x] in dev middleware, static, shows desired error on stderr - [x] in dev route, static, shows desired error on stderr - [x] in dev middleware, dynamic, shows desired error on stderr - [x] in dev route, dynamic, shows desired error on stderr - [x] in dev middleware, static, shows desired error on react error overlay - [x] in dev route, static, shows desired error on react error overlay - [x] in dev middleware, dynamic, shows desired error on react error overlay - [x] in dev route, dynamic, shows desired error on react error overlay - [x] fails to build middleware, with desired error on stderr - [x] fails to build route, with desired error on stderr ### unused node.js modules ```js // middleware.js import { NextResponse } from 'next/server' export default async function middleware() { if (process.exit) { const { basename } = await import('path') basename() } return NextResponse.next() } ``` ```js // pags/api/route.js export default async function handle() { if (process.exit) { const { basename } = await import('path') basename() } return Response.json({ useNodeModule: false }) } export const config = { runtime: 'experimental-edge' } ``` Desired warning at build time: > A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime - [x] invoke middleware in dev with no error - [x] invoke route in dev with no error - [x] builds successfully, shows build warning, invoke middleware with no error - [x] builds successfully, shows build warning, invoke api-route with no error ## Notes to reviewers The strategy to implement this feature is to leverages webpack [externals](https://webpack.js.org/configuration/externals/#externals) and run a global `__unsupported_module()` function when using a node.js module from edge function's code. For the record, I tried using [webpack resolve.fallback](https://webpack.js.org/configuration/resolve/#resolvefallback) and [Webpack.IgnorePlugin](https://webpack.js.org/plugins/ignore-plugin/) but they do not allow throwing proper errors at runtime that would contain the loaded module name for reporting. `__unsupported_module()` is defined in `EdgeRuntime`, and returns a proxy that's throw on use (whether it's property access, function call, new operator... synchronous & promise-based styles). However there's an issue with error reporting: webpack does not includes the import lines in the generated sourcemaps, preventing from displaying useful errors. I extended our middleware-plugin to supplement the sourcemaps (when analyzing edge function code, it saves which module is imported from which file, together with line/column/source) The react-dev-overlay was adapted to look for this additional information when the caught error relates to modules, instead of looking at sourcemaps. I removed the previous mechanism (built by @nkzawa ) which caught webpack errors at built time to change the displayed error message (files `next/build/index.js`, `next/build/utils.ts` and `wellknown-errors-plugin`)
2022-07-06 22:54:44 +02:00
const frame = frames.find(
({ file }) =>
fix(edge): error handling for edge route and middleware is inconsistent (#38401) ## What’s in there? This PR brings more consistency in how errors and warnings are reported when running code in the Edge Runtime: - Dynamic code evaluation (`eval()`, `new Function()`, `WebAssembly.instantiate()`, `WebAssembly.compile()`…) - Usage of Node.js global APIs (`BroadcastChannel`, `Buffer`, `TextDecoderStream`, `setImmediate()`...) - Usage of Node.js modules (`fs`, `path`, `child_process`…) The new error messages should mention *Edge Runtime* instead of *Middleware*, so they are valid in both cases. It also fixes a bug where the process polyfill would issue a warning for `process.cwd` (which is `undefined` but legit). Now, one has to invoke the function `process.cwd()` to trigger the error. It finally fixes the react-dev-overlay, where links from middleware and Edge API route files could not be opened because of the `(middleware)/` prefix in their name. About the later, please note that we can’t easily remove the prefix or change it for Edge API routes. It comes from the Webpack layer, which is the same for both. We may consider renaming it to *edge* instead in the future. ## How to test? These changes are almost fully covered with tests: ```bash pnpm testheadless --testPathPattern runtime-dynamic pnpm testheadless --testPathPattern runtime-with-node pnpm testheadless --testPathPattern runtime-module pnpm testheadless --testPathPattern middleware-dev-errors ``` To try them out manually, you can write a middleware and Edge route files like these: ```jsx // middleware.js import { NextResponse } from 'next/server' import { basename } from 'path' export default async function middleware() { eval('2+2') setImmediate(() => {}) basename() return NextResponse.next() } export const config = { matcher: '/' } ``` ```jsx // pages/api/route.js import { basename } from 'path' export default async function handle() { eval('2+2') setImmediate(() => {}) basename() return Response.json({ ok: true }) } export const config = { runtime: 'experimental-edge' } ``` The expected behaviours are: - [x] dev, middleware/edge route is using a node.js module: error at runtime (logs + read-dev-overlay): ```bash error - (middleware)/pages/api/route.js (1:0) @ Object.handle [as handler] error - The edge runtime does not support Node.js 'path' module. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime > 1 | import { basename } from "path"; 2 | export default async function handle() { ``` - [x] build, middleware/edge route is using a node.js module: warning but succeeds ```bash warn - Compiled with warnings ./middleware.js A Node.js module is loaded ('path' at line 4) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime ./pages/api/route.js A Node.js module is loaded ('path' at line 1) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime ``` - [x] production, middleware/edge route is using a node.js module: error at runtime (logs + 500 error) ```bash Error: The edge runtime does not support Node.js 'path' module. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime at <unknown> (file:///Users/damien/dev/next.js/packages/next/server/web/sandbox/context.ts:149) ``` - [x] dev, middleware/edge route is using a node.js global API: error at runtime (logs + read-dev-overlay): ```bash error - (middleware)/pages/api/route.js (4:2) @ Object.handle [as handler] error - A Node.js API is used (setImmediate) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime 2 | 3 | export default async function handle() { > 4 | setImmediate(() => {}) | ^ ``` - [x] build, middleware/edge route is using a node.js global API: warning but succeeds ```bash warn - Compiled with warnings ./middleware.js A Node.js API is used (setImmediate at line: 6) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime ./pages/api/route.js A Node.js API is used (setImmediate at line: 3) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime ``` - [x] production, middleware/edge route is using a node.js module: error at runtime (logs + 500 error) ```bash Error: A Node.js API is used (setImmediate) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime at <unknown> (file:///Users/damien/dev/next.js/packages/next/server/web/sandbox/context.ts:330) ``` - [x] dev, middleware/edge route is loading dynamic code: warning at runtime (logs + read-dev-overlay) and request succeeds (we allow dynamic code in dev only): ```bash warn - (middleware)/middleware.js (7:2) @ Object.middleware [as handler] warn - Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime 5 | 6 | export default async function middleware() { > 7 | eval('2+2') ``` - [x] build, middleware/edge route is loading dynamic code: build fails with error: ```bash Failed to compile. ./middleware.js Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Used by default ./pages/api/route.js Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Used by default ``` ## Notes to reviewers Edge-related errors are either issued from `next/server/web/sandbox/context.ts` file (runtime errors) or from `next/build/webpack/plugins/middleware-plugin.ts` (webpack compilation). The previous implementation (I’m pleading guilty here) was way too verbose: some errors (Node.js global APIs like using `process.cwd()`) could be reported several times, and the previous mechanism to dedupe them (in middleware-plugin) wasn’t really effective. Changes in tests are due to renaming existing tests such as `test/integration/middleware-with-node.js-apis` into `test/integration/edge-runtime-with-node.js-apis`. I extended them to cover Edge API route. @hanneslund I’ve pushed the improvement you did in https://github.com/vercel/next.js/pull/38289/ one step further to avoid duplication.
2022-07-21 16:53:23 +02:00
!file?.startsWith('eval') &&
!file?.includes('web/adapter') &&
!file?.includes('sandbox/context')
feat: build edge functions with node.js modules and fail at runtime (#38234) ## What's in there? The Edge runtime [does not support Node.js modules](https://edge-runtime.vercel.app/features/available-apis#unsupported-apis). When building Next.js application, we currently fail the build when detecting node.js module imported from middleware. This is an blocker for using code that is conditionally loading node.js modules (based on platform/env detection), as @cramforce reported. This PR implements a new strategy where: - we can build such middleware/Edge API route code **with a warning** - we fail at run time, with graceful errors in dev (console & react-dev-overlay error) - we fail at run time, with console errors in production ## How to test? All cases are covered with integration tests. To try them live, create a simple app with a page, a `middleware.js` file and a `pages/api/route.js`file. Here are iconic examples: ### node.js modules ```js // middleware.js import { NextResponse } from 'next/server' // static import { basename } from 'path' export default async function middleware() { // dynamic const { basename } = await import('path') basename() return NextResponse.next() } export const config = { matcher: '/' } ``` ```js // pags/api/route.js // static import { isAbsolute } from 'path' export default async function handle() { // dynamic const { isAbsolute } = await import('path') return Response.json({ useNodeModule: isAbsolute('/test') }) } export const config = { runtime: 'experimental-edge' } ``` Desired error (+ source code highlight in dev): > The edge runtime does not support Node.js 'path' module Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime Desired warning at build time: > A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime - [x] in dev middleware, static, shows desired error on stderr - [x] in dev route, static, shows desired error on stderr - [x] in dev middleware, dynamic, shows desired error on stderr - [x] in dev route, dynamic, shows desired error on stderr - [x] in dev middleware, static, shows desired error on react error overlay - [x] in dev route, static, shows desired error on react error overlay - [x] in dev middleware, dynamic, shows desired error on react error overlay - [x] in dev route, dynamic, shows desired error on react error overlay - [x] builds middleware successfully, shows build warning, shows desired error on stderr on call - [x] builds route successfully, shows build warning, shows desired error on stderr on call ### 3rd party modules not found ```js // middleware.js import { NextResponse } from 'next/server' // static import Unknown from 'unknown' export default async function middleware() { // dynamic const Unknown = await import('unknown') new Unknown() return NextResponse.next() } ``` export const config = { matcher: '/' } ``` ```js // pags/api/route.js // static import Unknown from 'unknown' export default async function handle() { // dynamic const Unknown = await import('unknown') return Response.json({ use3rdPartyModule: Unknown() }) } export const config = { runtime: 'experimental-edge' } ``` Desired error (+ source code highlight in dev): > Module not found: Can't resolve 'does-not-exist' Learn More: https://nextjs.org/docs/messages/module-not-found - [x] in dev middleware, static, shows desired error on stderr - [x] in dev route, static, shows desired error on stderr - [x] in dev middleware, dynamic, shows desired error on stderr - [x] in dev route, dynamic, shows desired error on stderr - [x] in dev middleware, static, shows desired error on react error overlay - [x] in dev route, static, shows desired error on react error overlay - [x] in dev middleware, dynamic, shows desired error on react error overlay - [x] in dev route, dynamic, shows desired error on react error overlay - [x] fails to build middleware, with desired error on stderr - [x] fails to build route, with desired error on stderr ### unused node.js modules ```js // middleware.js import { NextResponse } from 'next/server' export default async function middleware() { if (process.exit) { const { basename } = await import('path') basename() } return NextResponse.next() } ``` ```js // pags/api/route.js export default async function handle() { if (process.exit) { const { basename } = await import('path') basename() } return Response.json({ useNodeModule: false }) } export const config = { runtime: 'experimental-edge' } ``` Desired warning at build time: > A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime - [x] invoke middleware in dev with no error - [x] invoke route in dev with no error - [x] builds successfully, shows build warning, invoke middleware with no error - [x] builds successfully, shows build warning, invoke api-route with no error ## Notes to reviewers The strategy to implement this feature is to leverages webpack [externals](https://webpack.js.org/configuration/externals/#externals) and run a global `__unsupported_module()` function when using a node.js module from edge function's code. For the record, I tried using [webpack resolve.fallback](https://webpack.js.org/configuration/resolve/#resolvefallback) and [Webpack.IgnorePlugin](https://webpack.js.org/plugins/ignore-plugin/) but they do not allow throwing proper errors at runtime that would contain the loaded module name for reporting. `__unsupported_module()` is defined in `EdgeRuntime`, and returns a proxy that's throw on use (whether it's property access, function call, new operator... synchronous & promise-based styles). However there's an issue with error reporting: webpack does not includes the import lines in the generated sourcemaps, preventing from displaying useful errors. I extended our middleware-plugin to supplement the sourcemaps (when analyzing edge function code, it saves which module is imported from which file, together with line/column/source) The react-dev-overlay was adapted to look for this additional information when the caught error relates to modules, instead of looking at sourcemaps. I removed the previous mechanism (built by @nkzawa ) which caught webpack errors at built time to change the displayed error message (files `next/build/index.js`, `next/build/utils.ts` and `wellknown-errors-plugin`)
2022-07-06 22:54:44 +02:00
)!
if (frame.lineNumber && frame?.file) {
const moduleId = frame.file!.replace(
/^(webpack-internal:\/\/\/|file:\/\/)/,
''
)
feat: build edge functions with node.js modules and fail at runtime (#38234) ## What's in there? The Edge runtime [does not support Node.js modules](https://edge-runtime.vercel.app/features/available-apis#unsupported-apis). When building Next.js application, we currently fail the build when detecting node.js module imported from middleware. This is an blocker for using code that is conditionally loading node.js modules (based on platform/env detection), as @cramforce reported. This PR implements a new strategy where: - we can build such middleware/Edge API route code **with a warning** - we fail at run time, with graceful errors in dev (console & react-dev-overlay error) - we fail at run time, with console errors in production ## How to test? All cases are covered with integration tests. To try them live, create a simple app with a page, a `middleware.js` file and a `pages/api/route.js`file. Here are iconic examples: ### node.js modules ```js // middleware.js import { NextResponse } from 'next/server' // static import { basename } from 'path' export default async function middleware() { // dynamic const { basename } = await import('path') basename() return NextResponse.next() } export const config = { matcher: '/' } ``` ```js // pags/api/route.js // static import { isAbsolute } from 'path' export default async function handle() { // dynamic const { isAbsolute } = await import('path') return Response.json({ useNodeModule: isAbsolute('/test') }) } export const config = { runtime: 'experimental-edge' } ``` Desired error (+ source code highlight in dev): > The edge runtime does not support Node.js 'path' module Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime Desired warning at build time: > A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime - [x] in dev middleware, static, shows desired error on stderr - [x] in dev route, static, shows desired error on stderr - [x] in dev middleware, dynamic, shows desired error on stderr - [x] in dev route, dynamic, shows desired error on stderr - [x] in dev middleware, static, shows desired error on react error overlay - [x] in dev route, static, shows desired error on react error overlay - [x] in dev middleware, dynamic, shows desired error on react error overlay - [x] in dev route, dynamic, shows desired error on react error overlay - [x] builds middleware successfully, shows build warning, shows desired error on stderr on call - [x] builds route successfully, shows build warning, shows desired error on stderr on call ### 3rd party modules not found ```js // middleware.js import { NextResponse } from 'next/server' // static import Unknown from 'unknown' export default async function middleware() { // dynamic const Unknown = await import('unknown') new Unknown() return NextResponse.next() } ``` export const config = { matcher: '/' } ``` ```js // pags/api/route.js // static import Unknown from 'unknown' export default async function handle() { // dynamic const Unknown = await import('unknown') return Response.json({ use3rdPartyModule: Unknown() }) } export const config = { runtime: 'experimental-edge' } ``` Desired error (+ source code highlight in dev): > Module not found: Can't resolve 'does-not-exist' Learn More: https://nextjs.org/docs/messages/module-not-found - [x] in dev middleware, static, shows desired error on stderr - [x] in dev route, static, shows desired error on stderr - [x] in dev middleware, dynamic, shows desired error on stderr - [x] in dev route, dynamic, shows desired error on stderr - [x] in dev middleware, static, shows desired error on react error overlay - [x] in dev route, static, shows desired error on react error overlay - [x] in dev middleware, dynamic, shows desired error on react error overlay - [x] in dev route, dynamic, shows desired error on react error overlay - [x] fails to build middleware, with desired error on stderr - [x] fails to build route, with desired error on stderr ### unused node.js modules ```js // middleware.js import { NextResponse } from 'next/server' export default async function middleware() { if (process.exit) { const { basename } = await import('path') basename() } return NextResponse.next() } ``` ```js // pags/api/route.js export default async function handle() { if (process.exit) { const { basename } = await import('path') basename() } return Response.json({ useNodeModule: false }) } export const config = { runtime: 'experimental-edge' } ``` Desired warning at build time: > A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime - [x] invoke middleware in dev with no error - [x] invoke route in dev with no error - [x] builds successfully, shows build warning, invoke middleware with no error - [x] builds successfully, shows build warning, invoke api-route with no error ## Notes to reviewers The strategy to implement this feature is to leverages webpack [externals](https://webpack.js.org/configuration/externals/#externals) and run a global `__unsupported_module()` function when using a node.js module from edge function's code. For the record, I tried using [webpack resolve.fallback](https://webpack.js.org/configuration/resolve/#resolvefallback) and [Webpack.IgnorePlugin](https://webpack.js.org/plugins/ignore-plugin/) but they do not allow throwing proper errors at runtime that would contain the loaded module name for reporting. `__unsupported_module()` is defined in `EdgeRuntime`, and returns a proxy that's throw on use (whether it's property access, function call, new operator... synchronous & promise-based styles). However there's an issue with error reporting: webpack does not includes the import lines in the generated sourcemaps, preventing from displaying useful errors. I extended our middleware-plugin to supplement the sourcemaps (when analyzing edge function code, it saves which module is imported from which file, together with line/column/source) The react-dev-overlay was adapted to look for this additional information when the caught error relates to modules, instead of looking at sourcemaps. I removed the previous mechanism (built by @nkzawa ) which caught webpack errors at built time to change the displayed error message (files `next/build/index.js`, `next/build/utils.ts` and `wellknown-errors-plugin`)
2022-07-06 22:54:44 +02:00
const src = getErrorSource(err as Error)
const compilation = (
src === COMPILER_NAMES.edgeServer
feat: build edge functions with node.js modules and fail at runtime (#38234) ## What's in there? The Edge runtime [does not support Node.js modules](https://edge-runtime.vercel.app/features/available-apis#unsupported-apis). When building Next.js application, we currently fail the build when detecting node.js module imported from middleware. This is an blocker for using code that is conditionally loading node.js modules (based on platform/env detection), as @cramforce reported. This PR implements a new strategy where: - we can build such middleware/Edge API route code **with a warning** - we fail at run time, with graceful errors in dev (console & react-dev-overlay error) - we fail at run time, with console errors in production ## How to test? All cases are covered with integration tests. To try them live, create a simple app with a page, a `middleware.js` file and a `pages/api/route.js`file. Here are iconic examples: ### node.js modules ```js // middleware.js import { NextResponse } from 'next/server' // static import { basename } from 'path' export default async function middleware() { // dynamic const { basename } = await import('path') basename() return NextResponse.next() } export const config = { matcher: '/' } ``` ```js // pags/api/route.js // static import { isAbsolute } from 'path' export default async function handle() { // dynamic const { isAbsolute } = await import('path') return Response.json({ useNodeModule: isAbsolute('/test') }) } export const config = { runtime: 'experimental-edge' } ``` Desired error (+ source code highlight in dev): > The edge runtime does not support Node.js 'path' module Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime Desired warning at build time: > A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime - [x] in dev middleware, static, shows desired error on stderr - [x] in dev route, static, shows desired error on stderr - [x] in dev middleware, dynamic, shows desired error on stderr - [x] in dev route, dynamic, shows desired error on stderr - [x] in dev middleware, static, shows desired error on react error overlay - [x] in dev route, static, shows desired error on react error overlay - [x] in dev middleware, dynamic, shows desired error on react error overlay - [x] in dev route, dynamic, shows desired error on react error overlay - [x] builds middleware successfully, shows build warning, shows desired error on stderr on call - [x] builds route successfully, shows build warning, shows desired error on stderr on call ### 3rd party modules not found ```js // middleware.js import { NextResponse } from 'next/server' // static import Unknown from 'unknown' export default async function middleware() { // dynamic const Unknown = await import('unknown') new Unknown() return NextResponse.next() } ``` export const config = { matcher: '/' } ``` ```js // pags/api/route.js // static import Unknown from 'unknown' export default async function handle() { // dynamic const Unknown = await import('unknown') return Response.json({ use3rdPartyModule: Unknown() }) } export const config = { runtime: 'experimental-edge' } ``` Desired error (+ source code highlight in dev): > Module not found: Can't resolve 'does-not-exist' Learn More: https://nextjs.org/docs/messages/module-not-found - [x] in dev middleware, static, shows desired error on stderr - [x] in dev route, static, shows desired error on stderr - [x] in dev middleware, dynamic, shows desired error on stderr - [x] in dev route, dynamic, shows desired error on stderr - [x] in dev middleware, static, shows desired error on react error overlay - [x] in dev route, static, shows desired error on react error overlay - [x] in dev middleware, dynamic, shows desired error on react error overlay - [x] in dev route, dynamic, shows desired error on react error overlay - [x] fails to build middleware, with desired error on stderr - [x] fails to build route, with desired error on stderr ### unused node.js modules ```js // middleware.js import { NextResponse } from 'next/server' export default async function middleware() { if (process.exit) { const { basename } = await import('path') basename() } return NextResponse.next() } ``` ```js // pags/api/route.js export default async function handle() { if (process.exit) { const { basename } = await import('path') basename() } return Response.json({ useNodeModule: false }) } export const config = { runtime: 'experimental-edge' } ``` Desired warning at build time: > A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime - [x] invoke middleware in dev with no error - [x] invoke route in dev with no error - [x] builds successfully, shows build warning, invoke middleware with no error - [x] builds successfully, shows build warning, invoke api-route with no error ## Notes to reviewers The strategy to implement this feature is to leverages webpack [externals](https://webpack.js.org/configuration/externals/#externals) and run a global `__unsupported_module()` function when using a node.js module from edge function's code. For the record, I tried using [webpack resolve.fallback](https://webpack.js.org/configuration/resolve/#resolvefallback) and [Webpack.IgnorePlugin](https://webpack.js.org/plugins/ignore-plugin/) but they do not allow throwing proper errors at runtime that would contain the loaded module name for reporting. `__unsupported_module()` is defined in `EdgeRuntime`, and returns a proxy that's throw on use (whether it's property access, function call, new operator... synchronous & promise-based styles). However there's an issue with error reporting: webpack does not includes the import lines in the generated sourcemaps, preventing from displaying useful errors. I extended our middleware-plugin to supplement the sourcemaps (when analyzing edge function code, it saves which module is imported from which file, together with line/column/source) The react-dev-overlay was adapted to look for this additional information when the caught error relates to modules, instead of looking at sourcemaps. I removed the previous mechanism (built by @nkzawa ) which caught webpack errors at built time to change the displayed error message (files `next/build/index.js`, `next/build/utils.ts` and `wellknown-errors-plugin`)
2022-07-06 22:54:44 +02:00
? this.hotReloader?.edgeServerStats?.compilation
: this.hotReloader?.serverStats?.compilation
)!
const source = await getSourceById(
!!frame.file?.startsWith(sep) || !!frame.file?.startsWith('file:'),
moduleId,
compilation
)
const originalFrame = await createOriginalStackFrame({
line: frame.lineNumber!,
column: frame.column,
source,
frame,
modulePath: moduleId,
rootDirectory: this.dir,
feat: build edge functions with node.js modules and fail at runtime (#38234) ## What's in there? The Edge runtime [does not support Node.js modules](https://edge-runtime.vercel.app/features/available-apis#unsupported-apis). When building Next.js application, we currently fail the build when detecting node.js module imported from middleware. This is an blocker for using code that is conditionally loading node.js modules (based on platform/env detection), as @cramforce reported. This PR implements a new strategy where: - we can build such middleware/Edge API route code **with a warning** - we fail at run time, with graceful errors in dev (console & react-dev-overlay error) - we fail at run time, with console errors in production ## How to test? All cases are covered with integration tests. To try them live, create a simple app with a page, a `middleware.js` file and a `pages/api/route.js`file. Here are iconic examples: ### node.js modules ```js // middleware.js import { NextResponse } from 'next/server' // static import { basename } from 'path' export default async function middleware() { // dynamic const { basename } = await import('path') basename() return NextResponse.next() } export const config = { matcher: '/' } ``` ```js // pags/api/route.js // static import { isAbsolute } from 'path' export default async function handle() { // dynamic const { isAbsolute } = await import('path') return Response.json({ useNodeModule: isAbsolute('/test') }) } export const config = { runtime: 'experimental-edge' } ``` Desired error (+ source code highlight in dev): > The edge runtime does not support Node.js 'path' module Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime Desired warning at build time: > A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime - [x] in dev middleware, static, shows desired error on stderr - [x] in dev route, static, shows desired error on stderr - [x] in dev middleware, dynamic, shows desired error on stderr - [x] in dev route, dynamic, shows desired error on stderr - [x] in dev middleware, static, shows desired error on react error overlay - [x] in dev route, static, shows desired error on react error overlay - [x] in dev middleware, dynamic, shows desired error on react error overlay - [x] in dev route, dynamic, shows desired error on react error overlay - [x] builds middleware successfully, shows build warning, shows desired error on stderr on call - [x] builds route successfully, shows build warning, shows desired error on stderr on call ### 3rd party modules not found ```js // middleware.js import { NextResponse } from 'next/server' // static import Unknown from 'unknown' export default async function middleware() { // dynamic const Unknown = await import('unknown') new Unknown() return NextResponse.next() } ``` export const config = { matcher: '/' } ``` ```js // pags/api/route.js // static import Unknown from 'unknown' export default async function handle() { // dynamic const Unknown = await import('unknown') return Response.json({ use3rdPartyModule: Unknown() }) } export const config = { runtime: 'experimental-edge' } ``` Desired error (+ source code highlight in dev): > Module not found: Can't resolve 'does-not-exist' Learn More: https://nextjs.org/docs/messages/module-not-found - [x] in dev middleware, static, shows desired error on stderr - [x] in dev route, static, shows desired error on stderr - [x] in dev middleware, dynamic, shows desired error on stderr - [x] in dev route, dynamic, shows desired error on stderr - [x] in dev middleware, static, shows desired error on react error overlay - [x] in dev route, static, shows desired error on react error overlay - [x] in dev middleware, dynamic, shows desired error on react error overlay - [x] in dev route, dynamic, shows desired error on react error overlay - [x] fails to build middleware, with desired error on stderr - [x] fails to build route, with desired error on stderr ### unused node.js modules ```js // middleware.js import { NextResponse } from 'next/server' export default async function middleware() { if (process.exit) { const { basename } = await import('path') basename() } return NextResponse.next() } ``` ```js // pags/api/route.js export default async function handle() { if (process.exit) { const { basename } = await import('path') basename() } return Response.json({ useNodeModule: false }) } export const config = { runtime: 'experimental-edge' } ``` Desired warning at build time: > A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime - [x] invoke middleware in dev with no error - [x] invoke route in dev with no error - [x] builds successfully, shows build warning, invoke middleware with no error - [x] builds successfully, shows build warning, invoke api-route with no error ## Notes to reviewers The strategy to implement this feature is to leverages webpack [externals](https://webpack.js.org/configuration/externals/#externals) and run a global `__unsupported_module()` function when using a node.js module from edge function's code. For the record, I tried using [webpack resolve.fallback](https://webpack.js.org/configuration/resolve/#resolvefallback) and [Webpack.IgnorePlugin](https://webpack.js.org/plugins/ignore-plugin/) but they do not allow throwing proper errors at runtime that would contain the loaded module name for reporting. `__unsupported_module()` is defined in `EdgeRuntime`, and returns a proxy that's throw on use (whether it's property access, function call, new operator... synchronous & promise-based styles). However there's an issue with error reporting: webpack does not includes the import lines in the generated sourcemaps, preventing from displaying useful errors. I extended our middleware-plugin to supplement the sourcemaps (when analyzing edge function code, it saves which module is imported from which file, together with line/column/source) The react-dev-overlay was adapted to look for this additional information when the caught error relates to modules, instead of looking at sourcemaps. I removed the previous mechanism (built by @nkzawa ) which caught webpack errors at built time to change the displayed error message (files `next/build/index.js`, `next/build/utils.ts` and `wellknown-errors-plugin`)
2022-07-06 22:54:44 +02:00
errorMessage: err.message,
compilation,
})
if (originalFrame) {
const { originalCodeFrame, originalStackFrame } = originalFrame
const { file, lineNumber, column, methodName } = originalStackFrame
Log[type === 'warning' ? 'warn' : 'error'](
`${file} (${lineNumber}:${column}) @ ${methodName}`
)
if (src === COMPILER_NAMES.edgeServer) {
fix(edge): error handling for edge route and middleware is inconsistent (#38401) ## What’s in there? This PR brings more consistency in how errors and warnings are reported when running code in the Edge Runtime: - Dynamic code evaluation (`eval()`, `new Function()`, `WebAssembly.instantiate()`, `WebAssembly.compile()`…) - Usage of Node.js global APIs (`BroadcastChannel`, `Buffer`, `TextDecoderStream`, `setImmediate()`...) - Usage of Node.js modules (`fs`, `path`, `child_process`…) The new error messages should mention *Edge Runtime* instead of *Middleware*, so they are valid in both cases. It also fixes a bug where the process polyfill would issue a warning for `process.cwd` (which is `undefined` but legit). Now, one has to invoke the function `process.cwd()` to trigger the error. It finally fixes the react-dev-overlay, where links from middleware and Edge API route files could not be opened because of the `(middleware)/` prefix in their name. About the later, please note that we can’t easily remove the prefix or change it for Edge API routes. It comes from the Webpack layer, which is the same for both. We may consider renaming it to *edge* instead in the future. ## How to test? These changes are almost fully covered with tests: ```bash pnpm testheadless --testPathPattern runtime-dynamic pnpm testheadless --testPathPattern runtime-with-node pnpm testheadless --testPathPattern runtime-module pnpm testheadless --testPathPattern middleware-dev-errors ``` To try them out manually, you can write a middleware and Edge route files like these: ```jsx // middleware.js import { NextResponse } from 'next/server' import { basename } from 'path' export default async function middleware() { eval('2+2') setImmediate(() => {}) basename() return NextResponse.next() } export const config = { matcher: '/' } ``` ```jsx // pages/api/route.js import { basename } from 'path' export default async function handle() { eval('2+2') setImmediate(() => {}) basename() return Response.json({ ok: true }) } export const config = { runtime: 'experimental-edge' } ``` The expected behaviours are: - [x] dev, middleware/edge route is using a node.js module: error at runtime (logs + read-dev-overlay): ```bash error - (middleware)/pages/api/route.js (1:0) @ Object.handle [as handler] error - The edge runtime does not support Node.js 'path' module. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime > 1 | import { basename } from "path"; 2 | export default async function handle() { ``` - [x] build, middleware/edge route is using a node.js module: warning but succeeds ```bash warn - Compiled with warnings ./middleware.js A Node.js module is loaded ('path' at line 4) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime ./pages/api/route.js A Node.js module is loaded ('path' at line 1) which is not supported in the Edge Runtime. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime ``` - [x] production, middleware/edge route is using a node.js module: error at runtime (logs + 500 error) ```bash Error: The edge runtime does not support Node.js 'path' module. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime at <unknown> (file:///Users/damien/dev/next.js/packages/next/server/web/sandbox/context.ts:149) ``` - [x] dev, middleware/edge route is using a node.js global API: error at runtime (logs + read-dev-overlay): ```bash error - (middleware)/pages/api/route.js (4:2) @ Object.handle [as handler] error - A Node.js API is used (setImmediate) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime 2 | 3 | export default async function handle() { > 4 | setImmediate(() => {}) | ^ ``` - [x] build, middleware/edge route is using a node.js global API: warning but succeeds ```bash warn - Compiled with warnings ./middleware.js A Node.js API is used (setImmediate at line: 6) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime ./pages/api/route.js A Node.js API is used (setImmediate at line: 3) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime ``` - [x] production, middleware/edge route is using a node.js module: error at runtime (logs + 500 error) ```bash Error: A Node.js API is used (setImmediate) which is not supported in the Edge Runtime. Learn more: https://nextjs.org/docs/api-reference/edge-runtime at <unknown> (file:///Users/damien/dev/next.js/packages/next/server/web/sandbox/context.ts:330) ``` - [x] dev, middleware/edge route is loading dynamic code: warning at runtime (logs + read-dev-overlay) and request succeeds (we allow dynamic code in dev only): ```bash warn - (middleware)/middleware.js (7:2) @ Object.middleware [as handler] warn - Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime 5 | 6 | export default async function middleware() { > 7 | eval('2+2') ``` - [x] build, middleware/edge route is loading dynamic code: build fails with error: ```bash Failed to compile. ./middleware.js Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Used by default ./pages/api/route.js Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Used by default ``` ## Notes to reviewers Edge-related errors are either issued from `next/server/web/sandbox/context.ts` file (runtime errors) or from `next/build/webpack/plugins/middleware-plugin.ts` (webpack compilation). The previous implementation (I’m pleading guilty here) was way too verbose: some errors (Node.js global APIs like using `process.cwd()`) could be reported several times, and the previous mechanism to dedupe them (in middleware-plugin) wasn’t really effective. Changes in tests are due to renaming existing tests such as `test/integration/middleware-with-node.js-apis` into `test/integration/edge-runtime-with-node.js-apis`. I extended them to cover Edge API route. @hanneslund I’ve pushed the improvement you did in https://github.com/vercel/next.js/pull/38289/ one step further to avoid duplication.
2022-07-21 16:53:23 +02:00
err = err.message
}
if (type === 'warning') {
Log.warn(err)
} else if (type) {
Log.error(`${type}:`, err)
} else {
Log.error(err)
}
console[type === 'warning' ? 'warn' : 'error'](originalCodeFrame)
usedOriginalStack = true
}
}
} catch (_) {
// failed to load original stack using source maps
// this un-actionable by users so we don't show the
// internal error and only show the provided stack
}
}
if (!usedOriginalStack) {
if (type === 'warning') {
Log.warn(err)
} else if (type) {
Log.error(`${type}:`, err)
} else {
Log.error(err)
}
}
}
2019-11-09 23:34:53 +01:00
// override production loading of routes-manifest
protected getCustomRoutes(): CustomRoutes {
// actual routes will be loaded asynchronously during .prepare()
return {
redirects: [],
rewrites: { beforeFiles: [], afterFiles: [], fallback: [] },
headers: [],
}
2019-11-09 23:34:53 +01:00
}
private _devCachedPreviewProps: __ApiPreviewProps | undefined
protected getPreviewProps() {
if (this._devCachedPreviewProps) {
return this._devCachedPreviewProps
}
return (this._devCachedPreviewProps = {
previewModeId: crypto.randomBytes(16).toString('hex'),
previewModeSigningKey: crypto.randomBytes(32).toString('hex'),
previewModeEncryptionKey: crypto.randomBytes(32).toString('hex'),
})
}
protected getPagesManifest(): undefined {
return undefined
}
2022-05-25 11:46:26 +02:00
protected getAppPathsManifest(): undefined {
return undefined
}
protected getMiddleware() {
return this.middleware
}
protected getEdgeFunctions() {
return this.edgeFunctions ?? []
}
protected getServerComponentManifest() {
return undefined
}
protected getServerCSSManifest() {
return undefined
}
protected async hasMiddleware(): Promise<boolean> {
return this.hasPage(this.actualMiddlewareFile!)
}
protected async ensureMiddleware() {
return this.hotReloader!.ensurePage({
page: this.actualMiddlewareFile!,
clientOnly: false,
})
}
protected async ensureEdgeFunction({
page,
appPaths,
}: {
page: string
appPaths: string[] | null
}) {
return this.hotReloader!.ensurePage({ page, appPaths, clientOnly: false })
}
generateRoutes() {
const { fsRoutes, ...otherRoutes } = super.generateRoutes()
// In development we expose all compiled files for react-error-overlay's line show feature
// We use unshift so that we're sure the routes is defined before Next's default routes
fsRoutes.unshift({
match: getPathMatch('/_next/development/:path*'),
type: 'route',
name: '_next/development catchall',
fn: async (req, res, params) => {
const p = pathJoin(this.distDir, ...(params.path || []))
await this.serveStatic(req, res, p)
return {
finished: true,
}
},
})
fsRoutes.unshift({
match: getPathMatch(
`/_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_CLIENT_PAGES_MANIFEST}`
),
type: 'route',
name: `_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_CLIENT_PAGES_MANIFEST}`,
fn: async (_req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res
.body(
JSON.stringify({
pages: this.sortedRoutes,
})
)
.send()
return {
finished: true,
}
},
})
fsRoutes.unshift({
match: getPathMatch(
`/_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`
),
type: 'route',
name: `_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`,
fn: async (_req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.body(JSON.stringify(this.getMiddleware()?.matchers ?? [])).send()
return {
finished: true,
}
},
})
fsRoutes.push({
match: getPathMatch('/:path*'),
type: 'route',
name: 'catchall public directory route',
fn: async (req, res, params, parsedUrl) => {
const { pathname } = parsedUrl
if (!pathname) {
throw new Error('pathname is undefined')
}
// Used in development to check public directory paths
if (await this._beforeCatchAllRender(req, res, params, parsedUrl)) {
return {
finished: true,
}
}
return {
finished: false,
}
},
})
return { fsRoutes, ...otherRoutes }
}
2019-05-03 18:57:47 +02:00
// In development public files are not added to the router but handled as a fallback instead
protected generatePublicRoutes(): never[] {
2019-05-03 18:57:47 +02:00
return []
}
// In development dynamic routes cannot be known ahead of time
protected getDynamicRoutes(): never[] {
return []
}
_filterAmpDevelopmentScript(
html: string,
event: { line: number; col: number; code: string }
): boolean {
if (event.code !== 'DISALLOWED_SCRIPT_TAG') {
return true
}
const snippetChunks = html.split('\n')
let snippet
if (
!(snippet = html.split('\n')[event.line - 1]) ||
!(snippet = snippet.substring(event.col))
) {
return true
}
snippet = snippet + snippetChunks.slice(event.line).join('\n')
snippet = snippet.substring(0, snippet.indexOf('</script>'))
return !snippet.includes('data-amp-development-mode-only')
}
protected async getStaticPaths(pathname: string): Promise<{
staticPaths: string[] | undefined
fallbackMode: false | 'static' | 'blocking'
}> {
// we lazy load the staticPaths to prevent the user
// from waiting on them for the page to load in dev mode
const __getStaticPaths = async () => {
const {
configFileName,
publicRuntimeConfig,
serverRuntimeConfig,
httpAgentOptions,
} = this.nextConfig
2020-10-27 16:30:34 +01:00
const { locales, defaultLocale } = this.nextConfig.i18n || {}
const paths = await this.getStaticPathsWorker().loadStaticPaths(
this.distDir,
pathname,
!this.renderOpts.dev && this._isLikeServerless,
{
configFileName,
publicRuntimeConfig,
serverRuntimeConfig,
},
httpAgentOptions,
locales,
defaultLocale
)
return paths
}
const { paths: staticPaths, fallback } = (
await withCoalescedInvoke(__getStaticPaths)(`staticPaths-${pathname}`, [])
).value
return {
staticPaths,
fallbackMode:
fallback === 'blocking'
? 'blocking'
: fallback === true
? 'static'
: false,
}
}
protected async ensureApiPage(pathname: string): Promise<void> {
return this.hotReloader!.ensurePage({ page: pathname, clientOnly: false })
}
protected async findPageComponents({
pathname,
query,
params,
isAppPath,
appPaths,
}: {
pathname: string
query: ParsedUrlQuery
params: Params
isAppPath: boolean
appPaths?: string[] | null
}): Promise<FindComponentsResult | null> {
await this.devReady
const compilationErr = await this.getCompilationError(pathname)
if (compilationErr) {
// Wrap build errors so that they don't get logged again
throw new WrappedBuildError(compilationErr)
}
try {
await this.hotReloader!.ensurePage({
page: pathname,
appPaths,
clientOnly: false,
})
const serverComponents = this.nextConfig.experimental.serverComponents
// When the new page is compiled, we need to reload the server component
// manifest.
if (serverComponents) {
this.serverComponentManifest = super.getServerComponentManifest()
this.serverCSSManifest = super.getServerCSSManifest()
}
return super.findPageComponents({ pathname, query, params, isAppPath })
} catch (err) {
if ((err as any).code !== 'ENOENT') {
throw err
}
return null
}
}
protected async getFallbackErrorComponents(): Promise<LoadComponentsReturnType | null> {
await this.hotReloader!.buildFallbackError()
// Build the error page to ensure the fallback is built too.
// TODO: See if this can be moved into hotReloader or removed.
await this.hotReloader!.ensurePage({ page: '/_error', clientOnly: false })
return await loadDefaultErrorComponents(this.distDir)
}
protected setImmutableAssetCacheControl(res: BaseNextResponse): void {
res.setHeader('Cache-Control', 'no-store, must-revalidate')
}
private servePublic(
req: BaseNextRequest,
res: BaseNextResponse,
pathParts: string[]
): Promise<void> {
const p = pathJoin(this.publicDir, ...pathParts)
2019-05-03 18:57:47 +02:00
return this.serveStatic(req, res, p)
}
async hasPublicFile(path: string): Promise<boolean> {
try {
const info = await fs.promises.stat(pathJoin(this.publicDir, path))
return info.isFile()
} catch (_) {
return false
}
}
async getCompilationError(page: string): Promise<any> {
const errors = await this.hotReloader!.getCompilationErrors(page)
if (errors.length === 0) return
// Return the very first error we found.
return errors[0]
}
protected isServeableUrl(untrustedFileUrl: string): boolean {
// This method mimics what the version of `send` we use does:
// 1. decodeURIComponent:
// https://github.com/pillarjs/send/blob/0.17.1/index.js#L989
// https://github.com/pillarjs/send/blob/0.17.1/index.js#L518-L522
// 2. resolve:
// https://github.com/pillarjs/send/blob/de073ed3237ade9ff71c61673a34474b30e5d45b/index.js#L561
let decodedUntrustedFilePath: string
try {
// (1) Decode the URL so we have the proper file name
decodedUntrustedFilePath = decodeURIComponent(untrustedFileUrl)
} catch {
return false
}
// (2) Resolve "up paths" to determine real request
const untrustedFilePath = pathResolve(decodedUntrustedFilePath)
// don't allow null bytes anywhere in the file path
if (untrustedFilePath.indexOf('\0') !== -1) {
return false
}
// During development mode, files can be added while the server is running.
// Checks for .next/static, .next/server, static and public.
// Note that in development .next/server is available for error reporting purposes.
// see `packages/next/server/next-server.ts` for more details.
if (
untrustedFilePath.startsWith(pathJoin(this.distDir, 'static') + sep) ||
untrustedFilePath.startsWith(pathJoin(this.distDir, 'server') + sep) ||
untrustedFilePath.startsWith(pathJoin(this.dir, 'static') + sep) ||
untrustedFilePath.startsWith(pathJoin(this.dir, 'public') + sep)
) {
return true
}
return false
}
}