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

Fix middleware not executed when pages directory is empty (#43205)

Fixes #41995

Closes #43144

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`
Co-authored-by: 's avatarBruno Nascimento <bruno.hn@icloud.com>
parent 5d39daaf
...@@ -457,7 +457,11 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -457,7 +457,11 @@ 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) { if (nestedMiddleware.length > 0) {
throw new NestedMiddlewareError(nestedMiddleware, rootDir, pagesDir!) throw new NestedMiddlewareError(
nestedMiddleware,
rootDir,
(appDir || pagesDir)!
)
} }
return { return {
......
...@@ -11,7 +11,7 @@ import { escapeStringRegexp } from '../shared/lib/escape-regexp' ...@@ -11,7 +11,7 @@ import { escapeStringRegexp } from '../shared/lib/escape-regexp'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import { nanoid } from 'next/dist/compiled/nanoid/index.cjs' import { nanoid } from 'next/dist/compiled/nanoid/index.cjs'
import { pathToRegexp } from 'next/dist/compiled/path-to-regexp' import { pathToRegexp } from 'next/dist/compiled/path-to-regexp'
import path, { join } from 'path' import path from 'path'
import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-messages' import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-messages'
import { import {
STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR, STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR,
...@@ -331,15 +331,16 @@ export default async function build( ...@@ -331,15 +331,16 @@ export default async function build(
}) })
const { pagesDir, appDir } = findPagesDir(dir, isAppDirEnabled) const { pagesDir, appDir } = findPagesDir(dir, isAppDirEnabled)
const isSrcDir = path
.relative(dir, pagesDir || appDir || '')
.startsWith('src')
const hasPublicDir = await fileExists(publicDir) const hasPublicDir = await fileExists(publicDir)
telemetry.record( telemetry.record(
eventCliSession(dir, config, { eventCliSession(dir, config, {
webpackVersion: 5, webpackVersion: 5,
cliCommand: 'build', cliCommand: 'build',
isSrcDir: isSrcDir,
(!!pagesDir && path.relative(dir, pagesDir).startsWith('src')) ||
(!!appDir && path.relative(dir, appDir).startsWith('src')),
hasNowJson: !!(await findUp('now.json', { cwd: dir })), hasNowJson: !!(await findUp('now.json', { cwd: dir })),
isCustomServer: null, isCustomServer: null,
turboFlag: false, turboFlag: false,
...@@ -502,11 +503,10 @@ export default async function build( ...@@ -502,11 +503,10 @@ export default async function build(
`^${MIDDLEWARE_FILENAME}\\.(?:${config.pageExtensions.join('|')})$` `^${MIDDLEWARE_FILENAME}\\.(?:${config.pageExtensions.join('|')})$`
) )
const rootPaths = pagesDir const rootDir = path.join((pagesDir || appDir)!, '..')
? ( const rootPaths = (
await flatReaddir(join(pagesDir, '..'), middlewareDetectionRegExp) await flatReaddir(rootDir, middlewareDetectionRegExp)
).map((absoluteFile) => absoluteFile.replace(dir, '')) ).map((absoluteFile) => absoluteFile.replace(dir, ''))
: []
// needed for static exporting since we want to replace with HTML // needed for static exporting since we want to replace with HTML
// files // files
...@@ -1306,7 +1306,7 @@ export default async function build( ...@@ -1306,7 +1306,7 @@ export default async function build(
config.experimental.gzipSize config.experimental.gzipSize
) )
const middlewareManifest: MiddlewareManifest = require(join( const middlewareManifest: MiddlewareManifest = require(path.join(
distDir, distDir,
SERVER_DIRECTORY, SERVER_DIRECTORY,
MIDDLEWARE_MANIFEST MIDDLEWARE_MANIFEST
...@@ -1387,7 +1387,7 @@ export default async function build( ...@@ -1387,7 +1387,7 @@ export default async function build(
const staticInfo = pagePath const staticInfo = pagePath
? await getPageStaticInfo({ ? await getPageStaticInfo({
pageFilePath: join( pageFilePath: path.join(
(pageType === 'pages' ? pagesDir : appDir) || '', (pageType === 'pages' ? pagesDir : appDir) || '',
pagePath pagePath
), ),
...@@ -1982,7 +1982,7 @@ export default async function build( ...@@ -1982,7 +1982,7 @@ export default async function build(
const cssFilePaths = await new Promise<string[]>((resolve, reject) => { const cssFilePaths = await new Promise<string[]>((resolve, reject) => {
globOrig( globOrig(
'**/*.css', '**/*.css',
{ cwd: join(distDir, 'static') }, { cwd: path.join(distDir, 'static') },
(err, files) => { (err, files) => {
if (err) { if (err) {
return reject(err) return reject(err)
...@@ -2803,7 +2803,7 @@ export default async function build( ...@@ -2803,7 +2803,7 @@ export default async function build(
.traceAsyncFn(async () => { .traceAsyncFn(async () => {
await verifyPartytownSetup( await verifyPartytownSetup(
dir, dir,
join(distDir, CLIENT_STATIC_FILES_PATH) path.join(distDir, CLIENT_STATIC_FILES_PATH)
) )
}) })
} }
......
...@@ -1774,13 +1774,17 @@ export function getPossibleMiddlewareFilenames( ...@@ -1774,13 +1774,17 @@ export function getPossibleMiddlewareFilenames(
} }
export class NestedMiddlewareError extends Error { export class NestedMiddlewareError extends Error {
constructor(nestedFileNames: string[], mainDir: string, pagesDir: string) { constructor(
nestedFileNames: string[],
mainDir: string,
pagesOrAppDir: string
) {
super( super(
`Nested Middleware is not allowed, found:\n` + `Nested Middleware is not allowed, found:\n` +
`${nestedFileNames.map((file) => `pages${file}`).join('\n')}\n` + `${nestedFileNames.map((file) => `pages${file}`).join('\n')}\n` +
`Please move your code to a single file at ${path.join( `Please move your code to a single file at ${path.join(
path.posix.sep, path.posix.sep,
path.relative(mainDir, path.resolve(pagesDir, '..')), path.relative(mainDir, path.resolve(pagesOrAppDir, '..')),
'middleware' 'middleware'
)} instead.\n` + )} instead.\n` +
`Read More - https://nextjs.org/docs/messages/nested-middleware` `Read More - https://nextjs.org/docs/messages/nested-middleware`
......
...@@ -380,9 +380,9 @@ If you cannot make the changes above, but still want to try out\nNext.js v13 wit ...@@ -380,9 +380,9 @@ If you cannot make the changes above, but still want to try out\nNext.js v13 wit
eventCliSession(distDir, rawNextConfig as NextConfigComplete, { eventCliSession(distDir, rawNextConfig as NextConfigComplete, {
webpackVersion: 5, webpackVersion: 5,
cliCommand: 'dev', cliCommand: 'dev',
isSrcDir: isSrcDir: path
(!!pagesDir && path.relative(dir, pagesDir).startsWith('src')) || .relative(dir, pagesDir || appDir || '')
(!!appDir && path.relative(dir, appDir).startsWith('src')), .startsWith('src'),
hasNowJson: !!(await findUp('now.json', { cwd: dir })), hasNowJson: !!(await findUp('now.json', { cwd: dir })),
isCustomServer: false, isCustomServer: false,
turboFlag: true, turboFlag: true,
......
...@@ -277,12 +277,11 @@ export default class DevServer extends Server { ...@@ -277,12 +277,11 @@ export default class DevServer extends Server {
const app = this.appDir ? [this.appDir] : [] const app = this.appDir ? [this.appDir] : []
const directories = [...pages, ...app] const directories = [...pages, ...app]
const files = this.pagesDir const rootDir = this.pagesDir || this.appDir
? getPossibleMiddlewareFilenames( const files = getPossibleMiddlewareFilenames(
pathJoin(this.pagesDir, '..'), pathJoin(rootDir!, '..'),
this.nextConfig.pageExtensions this.nextConfig.pageExtensions
) )
: []
let nestedMiddleware: string[] = [] let nestedMiddleware: string[] = []
const envFiles = [ const envFiles = [
...@@ -294,7 +293,7 @@ export default class DevServer extends Server { ...@@ -294,7 +293,7 @@ export default class DevServer extends Server {
files.push(...envFiles) files.push(...envFiles)
// tsconfig/jsonfig paths hot-reloading // tsconfig/jsconfig paths hot-reloading
const tsconfigPaths = [ const tsconfigPaths = [
pathJoin(this.dir, 'tsconfig.json'), pathJoin(this.dir, 'tsconfig.json'),
pathJoin(this.dir, 'jsconfig.json'), pathJoin(this.dir, 'jsconfig.json'),
...@@ -577,7 +576,7 @@ export default class DevServer extends Server { ...@@ -577,7 +576,7 @@ export default class DevServer extends Server {
new NestedMiddlewareError( new NestedMiddlewareError(
nestedMiddleware, nestedMiddleware,
this.dir, this.dir,
this.pagesDir! (this.pagesDir || this.appDir)!
).message ).message
) )
nestedMiddleware = [] nestedMiddleware = []
...@@ -726,14 +725,15 @@ export default class DevServer extends Server { ...@@ -726,14 +725,15 @@ export default class DevServer extends Server {
} }
const telemetry = new Telemetry({ distDir: this.distDir }) const telemetry = new Telemetry({ distDir: this.distDir })
const isSrcDir = relative(
this.dir,
this.pagesDir || this.appDir || ''
).startsWith('src')
telemetry.record( telemetry.record(
eventCliSession(this.distDir, this.nextConfig, { eventCliSession(this.distDir, this.nextConfig, {
webpackVersion: 5, webpackVersion: 5,
cliCommand: 'dev', cliCommand: 'dev',
isSrcDir: 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 })), hasNowJson: !!(await findUp('now.json', { cwd: this.dir })),
isCustomServer: this.isCustomServer, isCustomServer: this.isCustomServer,
turboFlag: false, turboFlag: false,
......
/* eslint-env jest */ /* eslint-env jest */
import { NextInstance } from 'test/lib/next-modes/base' import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP } from 'next-test-utils' import { fetchViaHTTP, renderViaHTTP } from 'next-test-utils'
import { createNext, FileRef } from 'e2e-utils' import { createNext, FileRef } from 'e2e-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import path from 'path' import path from 'path'
...@@ -18,10 +18,6 @@ describe('app-dir with middleware', () => { ...@@ -18,10 +18,6 @@ describe('app-dir with middleware', () => {
beforeAll(async () => { beforeAll(async () => {
next = await createNext({ next = await createNext({
files: new FileRef(path.join(__dirname, 'app-middleware')), files: new FileRef(path.join(__dirname, 'app-middleware')),
dependencies: {
react: 'experimental',
'react-dom': 'experimental',
},
}) })
}) })
...@@ -122,3 +118,41 @@ describe('app-dir with middleware', () => { ...@@ -122,3 +118,41 @@ describe('app-dir with middleware', () => {
}) })
}) })
}) })
describe('app dir middleware without pages dir', () => {
if ((global as any).isNextDeploy) {
it('should skip next deploy for now', () => {})
return
}
let next: NextInstance
afterAll(() => next.destroy())
beforeAll(async () => {
next = await createNext({
files: {
app: new FileRef(path.join(__dirname, 'app-middleware/app')),
'next.config.js': new FileRef(
path.join(__dirname, 'app-middleware/next.config.js')
),
'middleware.js': `
import { NextResponse } from 'next/server'
export async function middleware(request) {
return new NextResponse('redirected')
}
export const config = {
matcher: '/headers'
}
`,
},
})
})
it(`Updates headers`, async () => {
const html = await renderViaHTTP(next.url, '/headers')
expect(html).toContain('redirected')
})
})
module.exports = { module.exports = {
experimental: { experimental: {
appDir: true, appDir: true,
legacyBrowsers: false, allowMiddlewareResponseBody: true,
browsersListForSwc: true,
}, },
} }
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