Unverified Commit 7c0a504a authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Handle assetPrefix in app (#39236)

This ensures we properly leverage the `assetPrefix` for `app`. Note for reviewing the test changes are mostly spacing so hiding that may help. 

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

Fixes: [slack thread](https://vercel.slack.com/archives/C035J346QQL/p1659387244559979)
parent d56aadae
...@@ -33,7 +33,8 @@ self.__next_require__ = __webpack_require__ ...@@ -33,7 +33,8 @@ self.__next_require__ = __webpack_require__
;(self as any).__next_chunk_load__ = (chunk: string) => { ;(self as any).__next_chunk_load__ = (chunk: string) => {
if (!chunk) return Promise.resolve() if (!chunk) return Promise.resolve()
if (chunk.endsWith('.css')) { if (chunk.endsWith('.css')) {
const chunkPath = `/_next/${chunk}` // @ts-expect-error __webpack_public_path__ is inlined by webpack
const chunkPath = `${__webpack_public_path__ || ''}${chunk}`
const existingTag = document.querySelector(`link[href="${chunkPath}"]`) const existingTag = document.querySelector(`link[href="${chunkPath}"]`)
if (!existingTag) { if (!existingTag) {
const link = document.createElement('link') const link = document.createElement('link')
......
...@@ -37,6 +37,7 @@ export type RenderOptsPartial = { ...@@ -37,6 +37,7 @@ export type RenderOptsPartial = {
supportsDynamicHTML?: boolean supportsDynamicHTML?: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
serverComponents?: boolean serverComponents?: boolean
assetPrefix?: string
} }
export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
...@@ -962,7 +963,11 @@ export async function renderToHTMLOrFlight( ...@@ -962,7 +963,11 @@ export async function renderToHTMLOrFlight(
return ( return (
<AppRouter <AppRouter
hotReloader={HotReloader && <HotReloader assetPrefix="" />} hotReloader={
HotReloader && (
<HotReloader assetPrefix={renderOpts.assetPrefix || ''} />
)
}
initialCanonicalUrl={initialCanonicalUrl} initialCanonicalUrl={initialCanonicalUrl}
initialTree={initialTree} initialTree={initialTree}
initialStylesheets={initialStylesheets} initialStylesheets={initialStylesheets}
...@@ -1021,7 +1026,7 @@ export async function renderToHTMLOrFlight( ...@@ -1021,7 +1026,7 @@ export async function renderToHTMLOrFlight(
streamOptions: { streamOptions: {
// Include hydration scripts in the HTML // Include hydration scripts in the HTML
bootstrapScripts: buildManifest.rootMainFiles.map( bootstrapScripts: buildManifest.rootMainFiles.map(
(src) => '/_next/' + src (src) => `${renderOpts.assetPrefix || ''}/_next/` + src
), ),
}, },
}) })
......
...@@ -6,12 +6,16 @@ module.exports = { ...@@ -6,12 +6,16 @@ module.exports = {
legacyBrowsers: false, legacyBrowsers: false,
browsersListForSwc: true, browsersListForSwc: true,
}, },
// assetPrefix: '/assets',
rewrites: async () => { rewrites: async () => {
return [ return {
// beforeFiles: [ { source: '/assets/:path*', destination: '/:path*' } ],
afterFiles: [
{ {
source: '/rewritten-to-dashboard', source: '/rewritten-to-dashboard',
destination: '/dashboard', destination: '/dashboard',
}, },
] ],
}
}, },
} }
...@@ -19,6 +19,7 @@ describe('app dir', () => { ...@@ -19,6 +19,7 @@ describe('app dir', () => {
} }
let next: NextInstance let next: NextInstance
function runTests({ assetPrefix }: { assetPrefix?: boolean }) {
beforeAll(async () => { beforeAll(async () => {
next = await createNext({ next = await createNext({
files: { files: {
...@@ -34,7 +35,19 @@ describe('app dir', () => { ...@@ -34,7 +35,19 @@ describe('app dir', () => {
react: 'experimental', react: 'experimental',
'react-dom': 'experimental', 'react-dom': 'experimental',
}, },
skipStart: true,
}) })
if (assetPrefix) {
const content = await next.readFile('next.config.js')
await next.patchFile(
'next.config.js',
content
.replace('// assetPrefix', 'assetPrefix')
.replace('// beforeFiles', 'beforeFiles')
)
}
await next.start()
}) })
afterAll(() => next.destroy()) afterAll(() => next.destroy())
...@@ -526,11 +539,16 @@ describe('app dir', () => { ...@@ -526,11 +539,16 @@ describe('app dir', () => {
describe('dynamic routes', () => { describe('dynamic routes', () => {
it('should only pass params that apply to the layout', async () => { it('should only pass params that apply to the layout', async () => {
const html = await renderViaHTTP(next.url, '/dynamic/books/hello-world') const html = await renderViaHTTP(
next.url,
'/dynamic/books/hello-world'
)
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#dynamic-layout-params').text()).toBe('{}') expect($('#dynamic-layout-params').text()).toBe('{}')
expect($('#category-layout-params').text()).toBe('{"category":"books"}') expect($('#category-layout-params').text()).toBe(
'{"category":"books"}'
)
expect($('#id-layout-params').text()).toBe( expect($('#id-layout-params').text()).toBe(
'{"category":"books","id":"hello-world"}' '{"category":"books","id":"hello-world"}'
) )
...@@ -660,9 +678,9 @@ describe('app dir', () => { ...@@ -660,9 +678,9 @@ describe('app dir', () => {
// TODO: `await webdriver()` causes waiting for the full page to complete streaming. At that point "Loading..." is replaced by the actual content // TODO: `await webdriver()` causes waiting for the full page to complete streaming. At that point "Loading..." is replaced by the actual content
// expect(await browser.elementByCss('#loading').text()).toBe('Loading...') // expect(await browser.elementByCss('#loading').text()).toBe('Loading...')
expect(await browser.elementByCss('#slow-layout-message').text()).toBe( expect(
'hello from slow layout' await browser.elementByCss('#slow-layout-message').text()
) ).toBe('hello from slow layout')
expect(await browser.elementByCss('#page-message').text()).toBe( expect(await browser.elementByCss('#page-message').text()).toBe(
'Hello World' 'Hello World'
...@@ -692,9 +710,9 @@ describe('app dir', () => { ...@@ -692,9 +710,9 @@ describe('app dir', () => {
// expect(await browser.elementByCss('#loading-layout').text()).toBe('Loading...') // expect(await browser.elementByCss('#loading-layout').text()).toBe('Loading...')
// expect(await browser.elementByCss('#loading-page').text()).toBe('Loading...') // expect(await browser.elementByCss('#loading-page').text()).toBe('Loading...')
expect(await browser.elementByCss('#slow-layout-message').text()).toBe( expect(
'hello from slow layout' await browser.elementByCss('#slow-layout-message').text()
) ).toBe('hello from slow layout')
expect(await browser.elementByCss('#slow-page-message').text()).toBe( expect(await browser.elementByCss('#slow-page-message').text()).toBe(
'hello from slow page' 'hello from slow page'
...@@ -852,7 +870,10 @@ describe('app dir', () => { ...@@ -852,7 +870,10 @@ describe('app dir', () => {
describe('usePathname', () => { describe('usePathname', () => {
// TODO-APP: should enable when implemented // TODO-APP: should enable when implemented
it.skip('should throw an error when imported', async () => { it.skip('should throw an error when imported', async () => {
const res = await fetchViaHTTP(next.url, '/hooks/use-pathname/server') const res = await fetchViaHTTP(
next.url,
'/hooks/use-pathname/server'
)
expect(res.status).toBe(500) expect(res.status).toBe(500)
expect(await res.text()).toContain('Internal Server Error') expect(await res.text()).toContain('Internal Server Error')
}) })
...@@ -889,7 +910,10 @@ describe('app dir', () => { ...@@ -889,7 +910,10 @@ describe('app dir', () => {
describe('useCookies', () => { describe('useCookies', () => {
// TODO-APP: should enable when implemented // TODO-APP: should enable when implemented
it.skip('should throw an error when imported', async () => { it.skip('should throw an error when imported', async () => {
const res = await fetchViaHTTP(next.url, '/hooks/use-cookies/client') const res = await fetchViaHTTP(
next.url,
'/hooks/use-cookies/client'
)
expect(res.status).toBe(500) expect(res.status).toBe(500)
expect(await res.text()).toContain('Internal Server Error') expect(await res.text()).toContain('Internal Server Error')
}) })
...@@ -910,7 +934,10 @@ describe('app dir', () => { ...@@ -910,7 +934,10 @@ describe('app dir', () => {
describe('useHeaders', () => { describe('useHeaders', () => {
// TODO-APP: should enable when implemented // TODO-APP: should enable when implemented
it.skip('should throw an error when imported', async () => { it.skip('should throw an error when imported', async () => {
const res = await fetchViaHTTP(next.url, '/hooks/use-headers/client') const res = await fetchViaHTTP(
next.url,
'/hooks/use-headers/client'
)
expect(res.status).toBe(500) expect(res.status).toBe(500)
expect(await res.text()).toContain('Internal Server Error') expect(await res.text()).toContain('Internal Server Error')
}) })
...@@ -1084,4 +1111,13 @@ describe('app dir', () => { ...@@ -1084,4 +1111,13 @@ describe('app dir', () => {
}) })
}) })
}) })
}
describe('without assetPrefix', () => {
runTests({})
})
describe('with assetPrefix', () => {
runTests({ assetPrefix: 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