Skip to content
This repository has been archived by the owner on Jul 6, 2021. It is now read-only.

next-css: Routing to another page doesn't load CSS in development mode #263

Closed
Splendith opened this issue Sep 16, 2018 · 18 comments
Closed

Comments

@Splendith
Copy link

Describe the bug

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.

To Reproduce

  1. Clone https://github.com/Splendith/next.js-test (on master branch)
  2. Run npm i and then npm run dev
  3. Visit http://localhost:3000, you will see index page with big red "HelloIndexPage" text
  4. Click 'Test Page' link
  5. You will see the non-styled "HelloTestPage" text
  6. Refresh page and you will see big orange "HelloTestPage" text

System information

  • Version of next: 7.0.0-canary.18
  • Version of @zeit/next-css: 0.2.1-canary.2
  • Version of react: 16.5.0
  • Web browser: Google Chrome / Firefox

Additional context

  • It does not happen in production deployment (npm run build -> npm run start).
  • next 6.0 and @zeit/next-css 0.2.0 also happen, you can reproduce by checkout next_v6 branch and follow the same above steps
@timneutkens
Copy link
Member

This is fixed in next@canary + @zeit/next-css@canary as far as I know.

@Splendith
Copy link
Author

Splendith commented Sep 16, 2018

@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.

@timneutkens timneutkens reopened this Sep 16, 2018
@GerardVee
Copy link

Any updates? I'm also having the same issue under similar circumstances.

@calmburst
Copy link

Looking forward for a fix :)

@kylemh
Copy link
Contributor

kylemh commented Oct 5, 2018

This is a dupe of #282 and #282 contains a workaround with extra discussion. Should this issue be closed, and the other left open?

@zhanglin-doudou
Copy link

zhanglin-doudou commented Oct 23, 2018

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>
    );
  }
}

@timneutkens
Copy link
Member

Duplicate of #282

@timneutkens timneutkens marked this as a duplicate of #282 Oct 23, 2018
@drydenwilliams
Copy link

drydenwilliams commented Nov 21, 2019

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.

@chornos13
Copy link

chornos13 commented May 3, 2020

I just made some modification from this issue #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

@raindecastro
Copy link

raindecastro commented Jun 14, 2020

@chornos13 Thanks for the workaround! Although there seems to be a problem with rendering styles for dynamic routes.

@thotho19
Copy link

use cdn

@faeghe-hajiabadi
Copy link

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?

@dmtx97
Copy link

dmtx97 commented Jul 27, 2020

I am having a similar issue. Does the CSS load for you after a refresh? That is my issue.

@MartinYounghoonKim
Copy link

any update ?

@dmtx97
Copy link

dmtx97 commented Aug 25, 2020

@MartinYounghoonKim As far as I know I haven't found a fix. Styling works perfectly in production mode though.

@insivika
Copy link

insivika commented Aug 29, 2020

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

@snk-js
Copy link

snk-js commented Oct 11, 2020

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

@AlexandraKlein
Copy link

AlexandraKlein commented Dec 27, 2020

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;

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests