Unverified Commit cfe66e74 authored by Aurélien MANCA's avatar Aurélien MANCA Committed by GitHub

fix(next@15): use the asset prefix when loading a CSS in App Router (#72095)

# What

This PR fixes a bug when using next@15, next/dynamic and assetPrefix
config in App Router.

# Why

The current behavior loads the CSS with only the pathname and so, it
results with a 404.


# How

The new behavior uses the full url of the asset.

Fixes #72470

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

---------
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 2de97220
...@@ -619,7 +619,11 @@ export const css = curry(async function css( ...@@ -619,7 +619,11 @@ export const css = curry(async function css(
insert: function (linkTag: HTMLLinkElement) { insert: function (linkTag: HTMLLinkElement) {
if (typeof _N_E_STYLE_LOAD === 'function') { if (typeof _N_E_STYLE_LOAD === 'function') {
const { href, onload, onerror } = linkTag const { href, onload, onerror } = linkTag
_N_E_STYLE_LOAD(new URL(href).pathname).then( _N_E_STYLE_LOAD(
href.indexOf(window.location.origin) === 0
? new URL(href).pathname
: href
).then(
() => onload?.call(linkTag, { type: 'load' } as Event), () => onload?.call(linkTag, { type: 'load' } as Event),
() => onerror?.call(linkTag, {} as Event) () => onerror?.call(linkTag, {} as Event)
) )
......
module.exports = {
assetPrefix: 'http://localhost:__CDN_PORT__/path-prefix',
}
import styles from './Component2.module.scss'
export default function Content2() {
return (
<div className={styles.container}>
<h1 className={styles.header}>Where does it come from?</h1>
<div className={styles.textContent}>
Contrary to popular belief, Lorem Ipsum is not simply random text. It
has roots in a piece of classical Latin literature from 45 BC, making it
over 2000 years old. Richard McClintock, a Latin professor at
Hampden-Sydney College in Virginia, looked up one of the more obscure
Latin words, consectetur, from a Lorem Ipsum passage, and going through
the cites of the word in classical literature, discovered the
undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33
of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by
Cicero, written in 45 BC. This book is a treatise on the theory of
ethics, very popular during the Renaissance. The first line of Lorem
Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section
1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is
reproduced below for those interested. Sections 1.10.32 and 1.10.33 from
"de Finibus Bonorum et Malorum" by Cicero are also reproduced in their
exact original form, accompanied by English versions from the 1914
translation by H. Rackham.
</div>
</div>
)
}
.header {
font-style: italic;
}
.container {
background-color: #dddddd;
padding: 1rem;
}
.textContent {
color: #666;
letter-spacing: -1px;
}
import styles from './Content.module.css'
import Content2 from './Component2'
export default function Content() {
return (
<div className={styles.container}>
<h1 className={styles.header}>Where does it come from?</h1>
<div className={styles.textContent}>
Contrary to popular belief, Lorem Ipsum is not simply random text. It
has roots in a piece of classical Latin literature from 45 BC, making it
over 2000 years old. Richard McClintock, a Latin professor at
Hampden-Sydney College in Virginia, looked up one of the more obscure
Latin words, consectetur, from a Lorem Ipsum passage, and going through
the cites of the word in classical literature, discovered the
undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33
of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by
Cicero, written in 45 BC. This book is a treatise on the theory of
ethics, very popular during the Renaissance. The first line of Lorem
Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section
1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is
reproduced below for those interested. Sections 1.10.32 and 1.10.33 from
"de Finibus Bonorum et Malorum" by Cicero are also reproduced in their
exact original form, accompanied by English versions from the 1914
translation by H. Rackham.
</div>
<Content2 />
</div>
)
}
.header {
font-style: italic;
}
.container {
background-color: #dddddd;
padding: 1rem;
}
.textContent {
color: #666;
letter-spacing: -1px;
}
export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
'use client'
import React, { useState } from 'react'
import style from '../../Content4.module.css'
import { Comp } from '../../inner/k'
export default function Index() {
const [s] = useState(true)
if (s) {
return (
<>
<div className={style.header}></div>
<Comp />
</>
)
}
return null
}
import dynamic from 'next/dynamic'
export const Comp = dynamic(() => import('../Content'), { ssr: false })
import React, { useState } from 'react'
import style from '../Content4.module.css'
import { Comp } from '../inner/k'
export default function Index() {
const [s] = useState(true)
if (s) {
return (
<>
<div className={style.header}></div>
<Comp />
</>
)
}
return null
}
export const getServerSideProps = () => {
return {
props: {},
}
}
/* eslint-env jest */
import webdriver from 'next-webdriver'
import { createServer, request } from 'http'
import { join, resolve } from 'path'
import {
findPort,
launchApp,
killApp,
nextBuild,
nextStart,
File,
} from 'next-test-utils'
const appDir = join(__dirname, '..')
const nextConfig = new File(resolve(__dirname, '../next.config.js'))
let appPort
let cdnPort
let app
let cdn
function runTests() {
it('should load a Pages Router page correctly', async () => {
const browser = await webdriver(appPort, '/')
expect(
await browser
.elementByCss('#__next div:nth-child(2)')
.getComputedCss('background-color')
).toContain('221, 221, 221')
expect(await browser.eval('document.documentElement.innerHTML')).toContain(
'Where does it come from?'
)
})
it('should load a App Router page correctly', async () => {
const browser = await webdriver(appPort, '/test-app')
expect(
await browser
.elementByCss('body div:nth-child(3)')
.getComputedCss('background-color')
).toContain('221, 221, 221')
expect(await browser.eval('document.documentElement.innerHTML')).toContain(
'Where does it come from?'
)
})
}
describe('next/dynamic with assetPrefix', () => {
;(process.env.TURBOPACK_BUILD ? describe.skip : describe)(
'development mode',
() => {
beforeAll(async () => {
cdnPort = await findPort()
// lightweight http proxy
cdn = createServer((clientReq, clientRes) => {
const proxyPath = clientReq.url.slice('/path-prefix'.length)
const proxyReq = request(
{
hostname: 'localhost',
port: appPort,
path: proxyPath,
method: clientReq.method,
headers: clientReq.headers,
},
(proxyRes) => {
// cdn must be configured to allow requests from this origin
proxyRes.headers['Access-Control-Allow-Origin'] =
`http://localhost:${appPort}`
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers)
// [NOTE] if socket doesn't have a handler to error event and if error
// event leaks, node.js ends its process with errored exit code.
// However, there can be failing socket event while running test
// as long as assertion is correct, do not care indiviual socket errors.
proxyRes.on('error', (e) => {
require('console').error(e)
})
clientRes.on('error', (e) => {
require('console').error(e)
})
proxyRes.pipe(clientRes, { end: true })
}
)
proxyReq.on('error', (e) => {
require('console').error(e)
})
clientReq.on('error', (e) => {
require('console').error(e)
})
clientReq.pipe(proxyReq, { end: true })
})
await new Promise((resolve) => cdn.listen(cdnPort, resolve))
nextConfig.replace('__CDN_PORT__', cdnPort)
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
afterAll(() => cdn.close())
afterAll(() => nextConfig.restore())
runTests(true)
}
)
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode',
() => {
beforeAll(async () => {
cdnPort = await findPort()
// lightweight http proxy
cdn = createServer((clientReq, clientRes) => {
const proxyPath = clientReq.url.slice('/path-prefix'.length)
const proxyReq = request(
{
hostname: 'localhost',
port: appPort,
path: proxyPath,
method: clientReq.method,
headers: clientReq.headers,
},
(proxyRes) => {
// cdn must be configured to allow requests from this origin
proxyRes.headers['Access-Control-Allow-Origin'] =
`http://localhost:${appPort}`
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers)
// [NOTE] if socket doesn't have a handler to error event and if error
// event leaks, node.js ends its process with errored exit code.
// However, there can be failing socket event while running test
// as long as assertion is correct, do not care indiviual socket errors.
proxyRes.on('error', (e) => {
require('console').error(e)
})
clientRes.on('error', (e) => {
require('console').error(e)
})
proxyRes.pipe(clientRes, { end: true })
}
)
proxyReq.on('error', (e) => {
require('console').error(e)
})
clientReq.on('error', (e) => {
require('console').error(e)
})
clientReq.pipe(proxyReq, { end: true })
})
await new Promise((resolve) => cdn.listen(cdnPort, resolve))
nextConfig.replace('__CDN_PORT__', cdnPort)
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
afterAll(() => cdn.close())
afterAll(() => nextConfig.restore())
runTests()
}
)
})
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"noEmit": true,
"incremental": true,
"module": "esnext",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
'use client'
import React, { useState } from 'react'
import style from '../../Content4.module.css'
import { Comp } from '../../inner/k'
export default function Index() {
const [s] = useState(true)
if (s) {
return (
<>
<div className={style.header}></div>
<Comp />
</>
)
}
return null
}
...@@ -15,7 +15,7 @@ let appPort ...@@ -15,7 +15,7 @@ let appPort
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
function runTests() { function runTests() {
it('should load page correctly', async () => { it('should load a Pages Router page correctly', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
expect( expect(
...@@ -28,6 +28,20 @@ function runTests() { ...@@ -28,6 +28,20 @@ function runTests() {
'Where does it come from?' 'Where does it come from?'
) )
}) })
it('should load a App Router page correctly', async () => {
const browser = await webdriver(appPort, '/test-app')
expect(
await browser
.elementByCss('body div:nth-child(3)')
.getComputedCss('background-color')
).toContain('221, 221, 221')
expect(await browser.eval('document.documentElement.innerHTML')).toContain(
'Where does it come from?'
)
})
} }
describe('next/dynamic', () => { describe('next/dynamic', () => {
......
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"noEmit": true,
"incremental": true,
"module": "esnext",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
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