When using Next.js with next-css plugin (canary version). Routing to another page doesn't load CSS styles, you will need to refresh the page to get the styles.
npm i and then npm run devhttp://localhost:3000, you will see index page with big red "HelloIndexPage" textnpm run build -> npm run start).This is fixed in next@canary + @zeit/next-css@canary as far as I know.
@timneutkens I tried in next@canary + @zeit/next-css@canary (by using npm i next@canary @zeit/next-css@canary today, or sorry if I do something wrong). Could you please follow my 'To Reproduce' section. It's very simple repos that used the canary version.
Any updates? I'm also having the same issue under similar circumstances.
Looking forward for a fix :)
This is a dupe of https://github.com/zeit/next-plugins/issues/282 and #282 contains a workaround with extra discussion. Should this issue be closed, and the other left open?
same problem.
The file _styles.chunk.css_ in _.next/static/css/_ has changed when i use _Link_ or _Router.push()_ to another page, but in the browser it stays the same from the first time loaded.
I had found a way to solve it. Not really perfect.
I have used a component Layout in every page.
import React, { Component } from 'react';
import Head from 'next/head';
export default class Layout extends Component {
render() {
const { children, title, style, className } = this.props;
return (
<div className={'main-layout col ' + className} style={style}>
<Head>
<title>{title}</title>
{process.env.NODE_ENV !== 'production' && (
<link rel="stylesheet" type="text/css" href={'/_next/static/css/styles.chunk.css?v=' + Date.now()} />
)}
</Head>
<div className="main-content">{children}</div>
</div>
);
}
}
Duplicate of #282
I just found that I wasn't doing using <Link /> correctly so on any sub pages my CSS wasn't loading.
I had to change:
<Link
href={`/event/${eventSlug}/${EventID}`}
as={`/event/${eventSlug}/${EventID}`}
>
to this:
<Link
href={`/event/[name]/[id]`}
as={`/event/${eventSlug}/${EventID}`}
>
Noting that the href prop is now the path of the page in the pages folder and as is the URL to show in URL bar of the browser.
I just made some modification from this issue https://github.com/zeit/next-plugins/issues/282
and I got this working for me
fix memory leak (update jun 17 20)
//_app.js
// import App from 'next/app'
import React from 'react'
import Router from 'next/router';
import * as PropTypes from 'prop-types'
class MyApp extends React.Component {
cacheURL = []
handleLoadStyle = (url) => {
if (this.cacheURL.includes(url)) return
const els = document.querySelectorAll(
'link[href*="/_next/static/css/styles.chunk.css"]')
const timestamp = new Date().valueOf()
for (let i = 0; i < els.length; i++) {
if (els[i].rel === 'stylesheet') {
els[i].href = '/_next/static/css/styles.chunk.css?v=' + timestamp
console.log('Style loaded')
this.cacheURL.push(url)
break
}
}
}
componentDidMount () {
if (process.env.NODE_ENV !== 'production') {
// prevent duplication listener
Router.events.on('routeChangeComplete', this.handleLoadStyle)
}
}
componentWillUnmount () {
if (process.env.NODE_ENV !== 'production') {
Router.events.off('routeChangeComplete', this.handleLoadStyle)
}
}
render () {
let { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
MyApp.propTypes = {
Component: PropTypes.any,
pageProps: PropTypes.any
}
export default MyApp
or you can convert it to hooks for simplification
@chornos13 Thanks for the workaround! Although there seems to be a problem with rendering styles for dynamic routes.
use cdn
I have same problem but in mine I can see css styles in page I access into by Link from other pages but when I want to access page with url I do not see any css style. has anyone any idea?
I am having a similar issue. Does the CSS load for you after a refresh? That is my issue.
any update ?
@MartinYounghoonKim As far as I know I haven't found a fix. Styling works perfectly in production mode though.
Having this issue as well. Replacing the href as shown above does not work as it just replaces it with the one of the previous page :/ This is also happening in production
What I did to solve this problem is to make a direct on root index. Simple as that I think. Then, you could redirect to whatever the page you wanna that breaks, and the css will load just correctly (just if you did a refresh)
// import { AmplifyAuthenticator } from '@aws-amplify/ui-react'
import { Amplify, API, Auth, withSSRContext } from 'aws-amplify'
import { useRouter } from 'next/router'
import awsExports from '../src/aws-exports'
import { useEffect } from 'react'
// import { createPost } from '../src/graphql/mutations'
// import { listPosts } from '../src/graphql/queries'
import styles from '../styles/Home.module.css'
Amplify.configure({ ...awsExports, ssr: true })
const RootPage = ({ props }) => {
console.log('props', props)
const router = useRouter()
useEffect(() => {
router.push('/ask')
})
return null
}
export async function getStaticProps(ctx) {
if (ctx.req) {
ctx.res.writeHead(302, { Location: '/ask' })
ctx.res.end()
}
return { props: { } }
}
export default RootPage
Modified from @chornos13 using hooks.
In _app.js:
import React, { useEffect } from 'react';
import { useRouter } from 'next/router';
const cacheURL = [];
const handleLoadStyle = url => {
if (cacheURL.includes(url)) {
return;
}
const styleLinks = document.querySelectorAll(
'link[href*="/_next/static/css/styles.chunk.css"]'
);
const timestamp = new Date().valueOf();
[...styleLinks].map(link => {
if (link.rel === 'stylesheet') {
link.href = `/_next/static/css/styles.chunk.css?v=${timestamp}`;
cacheURL.push(url);
}
});
};
function App({ Component, pageProps }) {
const { asPath, events } = useRouter();
useEffect(() => {
if (process.env.NODE_ENV === 'production') {
return;
}
events.on('routeChangeComplete', handleLoadStyle);
return () => {
events.off('routeChangeComplete', handleLoadStyle);
};
}, [asPath]);
return <Component {...pageProps} />;
}
export default App;
Most helpful comment
same problem.
The file _styles.chunk.css_ in _.next/static/css/_ has changed when i use _Link_ or _Router.push()_ to another page, but in the browser it stays the same from the first time loaded.
I had found a way to solve it. Not really perfect.
I have used a component
Layoutin every page.