Unverified Commit 08ed362b authored by Damien Simonin Feugas's avatar Damien Simonin Feugas Committed by GitHub

chore: reworks nested middleware error message (#37513)

* chore: reworks nested middleware error message

* chore: fix invalid path in nested middleware error message

* Update to show nested middleware error together

* update
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 09f48a75
...@@ -30,6 +30,7 @@ import { ...@@ -30,6 +30,7 @@ import {
isMiddlewareFile, isMiddlewareFile,
isMiddlewareFilename, isMiddlewareFilename,
isServerComponentPage, isServerComponentPage,
NestedMiddlewareError,
} from './utils' } from './utils'
import { getPageStaticInfo } from './analysis/get-page-static-info' import { getPageStaticInfo } from './analysis/get-page-static-info'
import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
...@@ -281,6 +282,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -281,6 +282,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
const edgeServer: webpack5.EntryObject = {} const edgeServer: webpack5.EntryObject = {}
const server: webpack5.EntryObject = {} const server: webpack5.EntryObject = {}
const client: webpack5.EntryObject = {} const client: webpack5.EntryObject = {}
const nestedMiddleware: string[] = []
const getEntryHandler = const getEntryHandler =
(mappings: Record<string, string>, pagesType: 'app' | 'pages' | 'root') => (mappings: Record<string, string>, pagesType: 'app' | 'pages' | 'root') =>
...@@ -321,9 +323,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -321,9 +323,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
!absolutePagePath.startsWith(ROOT_DIR_ALIAS) && !absolutePagePath.startsWith(ROOT_DIR_ALIAS) &&
/[\\\\/]_middleware$/.test(page) /[\\\\/]_middleware$/.test(page)
) { ) {
throw new Error( nestedMiddleware.push(page)
`nested Middleware is not allowed (found pages${page}) - https://nextjs.org/docs/messages/nested-middleware`
)
} }
const isServerComponent = serverComponentRegex.test(absolutePagePath) const isServerComponent = serverComponentRegex.test(absolutePagePath)
...@@ -399,6 +399,10 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -399,6 +399,10 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
} }
await Promise.all(Object.keys(pages).map(getEntryHandler(pages, 'pages'))) await Promise.all(Object.keys(pages).map(getEntryHandler(pages, 'pages')))
if (nestedMiddleware.length > 0) {
throw new NestedMiddlewareError(nestedMiddleware, rootDir, pagesDir)
}
return { return {
client, client,
server, server,
......
...@@ -1331,3 +1331,17 @@ export function getPossibleMiddlewareFilenames( ...@@ -1331,3 +1331,17 @@ export function getPossibleMiddlewareFilenames(
path.join(folder, `${MIDDLEWARE_FILENAME}.${extension}`) path.join(folder, `${MIDDLEWARE_FILENAME}.${extension}`)
) )
} }
export class NestedMiddlewareError extends Error {
constructor(nestedFileNames: string[], mainDir: string, pagesDir: string) {
super(
`Nested Middleware is not allowed, found:\n` +
`${nestedFileNames.map((file) => `pages${file}`).join('\n')}\n` +
`Please move your code to a single file at ${path.join(
path.posix.sep,
path.relative(mainDir, path.resolve(pagesDir, '..')),
'middleware'
)} instead.\n` +
`Read More - https://nextjs.org/docs/messages/nested-middleware`
)
}
}
...@@ -70,6 +70,7 @@ import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' ...@@ -70,6 +70,7 @@ import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { import {
getPossibleMiddlewareFilenames, getPossibleMiddlewareFilenames,
isMiddlewareFile, isMiddlewareFile,
NestedMiddlewareError,
} from '../../build/utils' } from '../../build/utils'
// Load ReactDevOverlay only when needed // Load ReactDevOverlay only when needed
...@@ -282,6 +283,7 @@ export default class DevServer extends Server { ...@@ -282,6 +283,7 @@ export default class DevServer extends Server {
pathJoin(this.pagesDir, '..'), pathJoin(this.pagesDir, '..'),
this.nextConfig.pageExtensions this.nextConfig.pageExtensions
) )
let nestedMiddleware: string[] = []
wp.watch(files, directories, 0) wp.watch(files, directories, 0)
...@@ -351,9 +353,7 @@ export default class DevServer extends Server { ...@@ -351,9 +353,7 @@ export default class DevServer extends Server {
* warn without adding it so it doesn't make its way into the system. * warn without adding it so it doesn't make its way into the system.
*/ */
if (/[\\\\/]_middleware$/.test(pageName)) { if (/[\\\\/]_middleware$/.test(pageName)) {
Log.error( nestedMiddleware.push(pageName)
`nested Middleware is not allowed (found pages${pageName}) - https://nextjs.org/docs/messages/nested-middleware`
)
continue continue
} }
...@@ -370,6 +370,14 @@ export default class DevServer extends Server { ...@@ -370,6 +370,14 @@ export default class DevServer extends Server {
routedPages.push(pageName) routedPages.push(pageName)
} }
if (nestedMiddleware.length > 0) {
Log.error(
new NestedMiddlewareError(nestedMiddleware, this.dir, this.pagesDir)
.message
)
nestedMiddleware = []
}
this.appPathRoutes = appPaths this.appPathRoutes = appPaths
this.middleware = getSortedRoutes(routedMiddleware).map((page) => { this.middleware = getSortedRoutes(routedMiddleware).map((page) => {
return { return {
......
...@@ -2,8 +2,10 @@ ...@@ -2,8 +2,10 @@
import stripAnsi from 'next/dist/compiled/strip-ansi' import stripAnsi from 'next/dist/compiled/strip-ansi'
import { getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage } from 'next/dist/build/utils' import { getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage } from 'next/dist/build/utils'
import { join } from 'path' import fs from 'fs-extra'
import { dirname, join } from 'path'
import { import {
check,
fetchViaHTTP, fetchViaHTTP,
File, File,
findPort, findPort,
...@@ -157,16 +159,30 @@ describe('Middleware importing Node.js modules', () => { ...@@ -157,16 +159,30 @@ describe('Middleware importing Node.js modules', () => {
}) })
it('warns about nested middleware being not allowed', async () => { it('warns about nested middleware being not allowed', async () => {
const file = new File(join(__dirname, '../pages/about/_middleware.js')) const aboutMiddleware = join(__dirname, '../pages/about/_middleware.js')
file.write(`export function middleware() {}`) const apiMiddleware = join(__dirname, '../pages/api/_middleware.js')
await fs.ensureDir(dirname(aboutMiddleware))
await fs.ensureDir(dirname(apiMiddleware))
await fs.writeFile(aboutMiddleware, `export function middleware() {}`)
await fs.writeFile(apiMiddleware, `export function middleware() {}`)
try { try {
const res = await fetchViaHTTP(context.appPort, '/about') const res = await fetchViaHTTP(context.appPort, '/about')
expect(context.logs.stderr).toContain(
'nested Middleware is not allowed (found pages/about/_middleware) - https://nextjs.org/docs/messages/nested-middleware'
)
expect(res.status).toBe(200) expect(res.status).toBe(200)
await check(() => {
return context.logs.stderr.includes(
'Nested Middleware is not allowed, found:'
) &&
context.logs.stderr.includes('pages/about/_middleware') &&
context.logs.stderr.includes('pages/api/_middleware')
? 'success'
: context.logs.output
}, 'success')
} finally { } finally {
file.delete() await fs.remove(aboutMiddleware)
await fs.remove(apiMiddleware)
} }
}) })
}) })
...@@ -215,16 +231,26 @@ describe('Middleware importing Node.js modules', () => { ...@@ -215,16 +231,26 @@ describe('Middleware importing Node.js modules', () => {
}) })
it('fails when there is a not allowed middleware', async () => { it('fails when there is a not allowed middleware', async () => {
const file = new File(join(__dirname, '../pages/about/_middleware.js')) const aboutMiddleware = join(__dirname, '../pages/about/_middleware.js')
file.write(`export function middleware() {}`) const apiMiddleware = join(__dirname, '../pages/api/_middleware.js')
await fs.ensureDir(dirname(aboutMiddleware))
await fs.ensureDir(dirname(apiMiddleware))
await fs.writeFile(aboutMiddleware, `export function middleware() {}`)
await fs.writeFile(apiMiddleware, `export function middleware() {}`)
const buildResult = await nextBuild(context.appDir, undefined, { const buildResult = await nextBuild(context.appDir, undefined, {
stderr: true, stderr: true,
stdout: true, stdout: true,
}) })
await fs.remove(aboutMiddleware)
await fs.remove(apiMiddleware)
expect(buildResult.stderr).toContain( expect(buildResult.stderr).toContain(
'Error: nested Middleware is not allowed (found pages/about/_middleware) - https://nextjs.org/docs/messages/nested-middleware' 'Nested Middleware is not allowed, found:'
) )
expect(buildResult.stderr).toContain('pages/about/_middleware')
expect(buildResult.stderr).toContain('pages/api/_middleware')
}) })
}) })
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment