Skip to content

Update middleware public/static matching #78875

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion packages/next/src/server/lib/router-utils/resolve-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -461,9 +461,23 @@ export function getResolveRoutes(

if (!opts.minimalMode && route.name === 'middleware') {
const match = fsChecker.getMiddlewareMatchers()
let maybeDecodedPathname = parsedUrl.pathname || '/'

try {
maybeDecodedPathname = decodeURIComponent(maybeDecodedPathname)
} catch {
/* non-fatal we can't decode so can't match it */
}

if (
// @ts-expect-error BaseNextRequest stuff
match?.(parsedUrl.pathname, req, parsedUrl.query)
match?.(parsedUrl.pathname, req, parsedUrl.query) ||
match?.(
maybeDecodedPathname,
// @ts-expect-error BaseNextRequest stuff
req,
parsedUrl.query
)
) {
if (ensureMiddleware) {
await ensureMiddleware(req.url)
Expand Down
15 changes: 14 additions & 1 deletion packages/next/src/server/next-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1688,7 +1688,20 @@ export default class NextNodeServer extends BaseServer<

parsedUrl.pathname = pathnameInfo.pathname
const normalizedPathname = removeTrailingSlash(parsed.pathname || '')
if (!middleware.match(normalizedPathname, req, parsedUrl.query)) {
let maybeDecodedPathname = normalizedPathname

try {
maybeDecodedPathname = decodeURIComponent(normalizedPathname)
} catch {
/* non-fatal we can't decode so can't match it */
}

if (
!(
middleware.match(normalizedPathname, req, parsedUrl.query) ||
middleware.match(maybeDecodedPathname, req, parsedUrl.query)
)
) {
return handleFinished()
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Page() {
return <p>hello world</p>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Page() {
return <p>hello world</p>
}
Binary file not shown.
3 changes: 3 additions & 0 deletions test/e2e/middleware-static-files/app/app/glob/hello/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Page() {
return <p>hello world</p>
}
18 changes: 18 additions & 0 deletions test/e2e/middleware-static-files/app/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { Metadata } from 'next'

export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
103 changes: 103 additions & 0 deletions test/e2e/middleware-static-files/app/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import Image from 'next/image'

export default function Home() {
return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="list-inside list-decimal text-sm/6 text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2 tracking-[-.01em]">
Get started by editing{' '}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-[family-name:var(--font-geist-mono)] font-semibold">
app/page.tsx
</code>
.
</li>
<li className="tracking-[-.01em]">
Save and see your changes instantly.
</li>
</ol>

<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 w-full sm:w-auto md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-[24px] flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org →
</a>
</footer>
</div>
)
}
20 changes: 20 additions & 0 deletions test/e2e/middleware-static-files/app/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { NextResponse } from 'next/server'

export const config = {
matcher: [
'/file.svg',
'/vercel copy.svg',
'/another/file.svg',
'/another/hello',
'/dynamic/:path*',
'/glob/:path*',
'/pages-another/hello',
'/pages-dynamic/:path*',
'/pages-glob/:path*',
'/_next/static/css/:path*',
],
}

export default function middleware() {
return NextResponse.json({ middleware: true })
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React from 'react'

export default function Page() {
return (
<>
<p>pages-another/hello</p>
</>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React from 'react'

export default function Page() {
return (
<>
<p>pages-another/hello</p>
</>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.text {
color: orange;
}
10 changes: 10 additions & 0 deletions test/e2e/middleware-static-files/app/pages/pages-glob/hello.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import React from 'react'
import * as styles from './hello.module.css'

export default function Page() {
return (
<>
<p className={styles['text']}>pages-another/hello</p>
</>
)
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions test/e2e/middleware-static-files/app/public/file.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions test/e2e/middleware-static-files/app/public/glob/file.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions test/e2e/middleware-static-files/app/public/globe.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions test/e2e/middleware-static-files/app/public/next.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions test/e2e/middleware-static-files/app/public/vercel.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions test/e2e/middleware-static-files/app/public/window.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
82 changes: 82 additions & 0 deletions test/e2e/middleware-static-files/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/* eslint-env jest */

import glob from 'glob'
import { join } from 'path'
import { createNext, FileRef } from 'e2e-utils'
import { isNextStart, NextInstance } from 'e2e-utils'

describe('Middleware Runtime', () => {
let next: NextInstance
let testPaths: Array<{ testPath: string }> = [
{ testPath: '/file.svg' },
{ testPath: '/vercel copy.svg' },
{ testPath: '/vercel%20copy.svg' },
{ testPath: '/another%2ffile.svg' },
{ testPath: '/another/file.svg' },
{ testPath: '/another/hello' },
{ testPath: '/another%2fhello' },
{ testPath: '/glob%2ffile.svg' },
{ testPath: '/glob/file.svg' },
{ testPath: '/dynamic%2f/first' },
{ testPath: '/dynamic/first' },
{ testPath: '/glob%2fhello' },
{ testPath: '/glob/hello' },
{ testPath: '/pages-another/hello' },
{ testPath: '/pages-another%2fhello' },
{ testPath: '/pages-dynamic%2f/first' },
{ testPath: '/pages-dynamic/first' },
{ testPath: '/pages-glob%2fhello' },
{ testPath: '/pages-glob/hello' },
]

beforeAll(async () => {
next = await createNext({
files: new FileRef(join(__dirname, 'app')),
})
})
afterAll(async () => {
await next.destroy()
})

it.each(testPaths)(
'should match middleware correctly for $testPath',
async ({ testPath }) => {
const res = await next.fetch(testPath, {
redirect: 'manual',
})

if (res.status === 404) {
expect(await res.text()).toContain('page could not be found')
} else {
expect(await res.json()).toEqual({ middleware: true })
}
}
)

if (isNextStart && !process.env.IS_TURBOPACK_TEST) {
it('should match middleware of _next/static', async () => {
const cssChunks = glob.sync('*.css', {
cwd: join(next.testDir, '.next', 'static', 'css'),
})

if (cssChunks.length < 1) {
throw new Error(`Failed to find CSS chunk`)
}

for (const testPath of [
`/_next/static/css%2f${cssChunks[0]}`,
`/_next/static/css/${cssChunks[0]}`,
]) {
const res = await next.fetch(testPath, {
redirect: 'manual',
})

if (res.status === 404) {
expect(await res.text()).toContain('page could not be found')
} else {
expect(await res.json()).toEqual({ middleware: true })
}
}
})
}
})
Loading