Unverified Commit df71f956 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

fix: return plain text 404 for invalid static asset paths (#75111)

parent 36458f90
...@@ -587,6 +587,36 @@ export async function initialize(opts: { ...@@ -587,6 +587,36 @@ export async function initialize(opts: {
'private, no-cache, no-store, max-age=0, must-revalidate' 'private, no-cache, no-store, max-age=0, must-revalidate'
) )
let realRequestPathname = parsedUrl.pathname ?? ''
if (realRequestPathname) {
if (config.basePath) {
realRequestPathname = removePathPrefix(
realRequestPathname,
config.basePath
)
}
if (config.assetPrefix) {
realRequestPathname = removePathPrefix(
realRequestPathname,
config.assetPrefix
)
}
if (config.i18n) {
realRequestPathname = removePathPrefix(
realRequestPathname,
'/' + (getRequestMeta(req, 'locale') ?? '')
)
}
}
// For not found static assets, return plain text 404 instead of
// full HTML 404 pages to save bandwidth.
if (realRequestPathname.startsWith('/_next/static/')) {
res.statusCode = 404
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('Not Found')
return null
}
// Short-circuit favicon.ico serving so that the 404 page doesn't get built as favicon is requested by the browser when loading any route. // Short-circuit favicon.ico serving so that the 404 page doesn't get built as favicon is requested by the browser when loading any route.
if (opts.dev && !matchedOutput && parsedUrl.pathname === '/favicon.ico') { if (opts.dev && !matchedOutput && parsedUrl.pathname === '/favicon.ico') {
res.statusCode = 404 res.statusCode = 404
......
...@@ -45,13 +45,19 @@ describe.each([['', '/docs']])( ...@@ -45,13 +45,19 @@ describe.each([['', '/docs']])(
}, },
}) })
// render 404 page to generate
// "/_next/static/chunks/pages/_app.js"
// we need this because not found static assets
// served as plain text 404 instead of HTML.
await next.render('/404')
await retry(async () => { await retry(async () => {
// make sure host server is running // make sure host server is running
const asset = await fetchViaHTTP( const res = await fetchViaHTTP(
next.appPort, next.appPort,
'/_next/static/chunks/pages/_app.js' '/_next/static/chunks/pages/_app.js'
) )
expect(asset.status).toBe(200) expect(res.status).toBe(200)
}) })
}) })
afterAll(() => next.destroy()) afterAll(() => next.destroy())
...@@ -199,13 +205,19 @@ describe.each([['', '/docs']])( ...@@ -199,13 +205,19 @@ describe.each([['', '/docs']])(
}, },
}) })
// render 404 page to generate
// "/_next/static/chunks/pages/_app.js"
// since we haven't built any paths by this point
// causing this chunk to not be written to disk yet
await next.render('/404')
await retry(async () => { await retry(async () => {
// make sure host server is running // make sure host server is running
const asset = await fetchViaHTTP( const res = await fetchViaHTTP(
next.appPort, next.appPort,
'/_next/static/chunks/pages/_app.js' '/_next/static/chunks/pages/_app.js'
) )
expect(asset.status).toBe(200) expect(res.status).toBe(200)
}) })
}) })
afterAll(() => next.destroy()) afterAll(() => next.destroy())
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function NotFound() {
return <p>Custom Not Found</p>
}
export default function Page() {
return <p>hello world</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('invalid-static-asset-404-app-asset-prefix', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
nextConfig: {
assetPrefix: '/assets',
},
})
it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/assets/_next/static/${
isNextDev ? 'development' : next.buildId
}/_buildManifest.js`
const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200)
const text = await res.text()
expect(text).toContain('__BUILD_MANIFEST')
})
it('should return custom 404 page when fetching invalid non-asset path', async () => {
const res = await next.fetch('/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toContain('Custom Not Found')
})
it('should return 404 with plain text when fetching invalid asset path', async () => {
const res = await next.fetch('/assets/_next/static/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toBe('Not Found')
})
})
import { nextTestSetup } from 'e2e-utils'
describe('invalid-static-asset-404-app-base-path', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
nextConfig: {
basePath: '/base',
},
})
it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/base/_next/static/${
isNextDev ? 'development' : next.buildId
}/_buildManifest.js`
const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200)
const text = await res.text()
expect(text).toContain('__BUILD_MANIFEST')
})
it('should return custom 404 page when fetching invalid non-asset path', async () => {
const res = await next.fetch('/base/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toContain('Custom Not Found')
})
it('should return 404 with plain text when fetching invalid asset path', async () => {
const res = await next.fetch('/base/_next/static/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toBe('Not Found')
})
})
import { nextTestSetup } from 'e2e-utils'
describe('invalid-static-asset-404-app', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/_next/static/${
isNextDev ? 'development' : next.buildId
}/_buildManifest.js`
const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200)
const text = await res.text()
expect(text).toContain('__BUILD_MANIFEST')
})
it('should return custom 404 page when fetching invalid non-asset path', async () => {
const res = await next.fetch('/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toContain('Custom Not Found')
})
it('should return 404 with plain text when fetching invalid asset path', async () => {
const res = await next.fetch('/_next/static/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toBe('Not Found')
})
})
import { nextTestSetup } from 'e2e-utils'
describe('invalid-static-asset-404-pages-asset-prefix', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
nextConfig: {
assetPrefix: '/assets',
},
})
it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/assets/_next/static/${
isNextDev ? 'development' : next.buildId
}/_buildManifest.js`
const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200)
const text = await res.text()
expect(text).toContain('__BUILD_MANIFEST')
})
it('should return custom 404 page when fetching invalid non-asset path', async () => {
const res = await next.fetch('/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toContain('Custom Not Found')
})
it('should return 404 with plain text when fetching invalid asset path', async () => {
const res = await next.fetch('/assets/_next/static/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toBe('Not Found')
})
})
import { nextTestSetup } from 'e2e-utils'
describe('invalid-static-asset-404-pages-base-path', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
nextConfig: {
basePath: '/base',
},
})
it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/base/_next/static/${
isNextDev ? 'development' : next.buildId
}/_buildManifest.js`
const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200)
const text = await res.text()
expect(text).toContain('__BUILD_MANIFEST')
})
it('should return custom 404 page when fetching invalid non-asset path', async () => {
const res = await next.fetch('/base/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toContain('Custom Not Found')
})
it('should return 404 with plain text when fetching invalid asset path', async () => {
const res = await next.fetch('/base/_next/static/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toBe('Not Found')
})
})
import { nextTestSetup } from 'e2e-utils'
describe('invalid-static-asset-404-pages', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/_next/static/${
isNextDev ? 'development' : next.buildId
}/_buildManifest.js`
const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200)
const text = await res.text()
expect(text).toContain('__BUILD_MANIFEST')
})
it('should return custom 404 page when fetching invalid non-asset path', async () => {
const res = await next.fetch('/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toContain('Custom Not Found')
})
it('should return 404 with plain text when fetching invalid asset path', async () => {
const res = await next.fetch('/_next/static/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect(text).toBe('Not Found')
})
})
export default function NotFound() {
return <p>Custom Not Found</p>
}
export default function Page() {
return <p>hello world</p>
}
...@@ -78,7 +78,10 @@ export function runTests(ctx) { ...@@ -78,7 +78,10 @@ export function runTests(ctx) {
if (!defaultLocales.includes(locale)) { if (!defaultLocales.includes(locale)) {
expect(res.status).toBe(404) expect(res.status).toBe(404)
expect(await res.text()).toContain('could not be found') expect(res.headers.get('content-type')).toBe(
'text/plain; charset=utf-8'
)
expect(await res.text()).toBe('Not Found')
} else { } else {
// We only 404 for non-default locale // We only 404 for non-default locale
expect(res.status).toBe(200) expect(res.status).toBe(200)
......
...@@ -642,8 +642,6 @@ describe('Required Server Files', () => { ...@@ -642,8 +642,6 @@ describe('Required Server Files', () => {
it('should handle 404s properly', async () => { it('should handle 404s properly', async () => {
for (const pathname of [ for (const pathname of [
'/_next/static/chunks/pages/index-abc123.js',
'/_next/static/some-file.js',
'/static/some-file.js', '/static/some-file.js',
'/non-existent', '/non-existent',
'/404', '/404',
...@@ -657,6 +655,23 @@ describe('Required Server Files', () => { ...@@ -657,6 +655,23 @@ describe('Required Server Files', () => {
expect(res.status).toBe(404) expect(res.status).toBe(404)
expect(await res.text()).toContain('custom 404') expect(await res.text()).toContain('custom 404')
} }
for (const pathname of [
'/_next/static/chunks/pages/index-abc123.js',
'/_next/static/some-file.js',
]) {
const res = await fetchViaHTTP(appPort, pathname, undefined, {
headers: {
'x-matched-path': '/404',
redirect: 'manual',
},
})
expect(res.status).toBe(404)
expect(res.headers.get('content-type')).toBe(
'text/plain; charset=utf-8'
)
expect(await res.text()).toBe('Not Found')
}
}) })
} }
) )
......
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