Next-plugins: Cant change page with 'next/link' & 'next-css'

Created on 24 Sep 2018  Β·  221Comments  Β·  Source: vercel/next-plugins

This is bug report

Link does not work with css-module imported. That happens when page with Link has no css, and linked page has. No errors in console, so im not sure about reasons, but there is minimal repo to reproduce:
https://github.com/standy/next-css-error

Bug appears in [email protected] + [email protected],
Older [email protected] + [email protected] works fine

Most helpful comment

my workaround this bug (on latest canary)

somewhere in _app.js

import Router from 'next/router';

Router.events.on('routeChangeComplete', () => {
  if (process.env.NODE_ENV !== 'production') {
    const els = document.querySelectorAll('link[href*="/_next/static/css/styles.chunk.css"]');
    const timestamp = new Date().valueOf();
    els[0].href = '/_next/static/css/styles.chunk.css?v=' + timestamp;
  }
})

on every page reloads css after router change

All 221 comments

I have the exact same issue, on the exact same versions as well.

Confirmed work around: make every page import some css.

Was trying hard to determine what was causing that. Thanks for reporting @Dynogic and @standy

Same problem except with next-css. Clicking links importing less just don't respond. My workaround was to stop using less/css. Note this ticket https://github.com/zeit/next.js/issues/5264#issuecomment-424000127 suggests you can import blank in _app.js.

https://spectrum.chat/thread/2183fc55-236d-42cb-92b9-3ab10acc6303?m=MTUzODU2NDg2ODA2Mg==

Next team is aware and working on it! It's complex and will take time.

Importing an empty stylesheet into _app.js nor importing a stylesheet on every page resolved the issue for me locally.

@kylemh I tried Importing an empty stylesheet into _app.js nor importing a stylesheet on every page resolved the issue for me locally. but still not working

It's a strategy some have professed, but it doesn't resolve anything for me - just like you.

Same problem

@kylemh / others could you try @zeit/next-css@canary? It holds #315

I would fuckin' love to ❀️

@timneutkens The error is gone, great job! However when changing routes I'm not getting that new route's style... is anyone else having that issue?

Unfortunately I have to go and won't be able to troubleshoot it further or provide additional details today.

^ this precisely.

It doesn't look like I'm getting more CSS files per route - just on initial load.

SSR gets all styles properly.

Same issue with @zeit/next-css@canary not get css load on route change

That being said, I'd say this issue can be closed and another can be made on route-based code splitting withCSS with CSS Modules + PostCSS (at least for me) not working as desired?

Yes, on route change issue still present. Long time i used next6 with old next-css and regulary gets not loaded styles on route change. After refresh page it works as expected even on route change.
On 7 version it reproduced on every page change (not sometimes as next6).
But if you 1) load first page 2) transition to next page (gets not loaded styles) 3) refresh page - then you take working styles on both pages.

Looks like styles compilation is long process and delayed and page do not have time for take it and apply. After refresh page styles already precompiled and applied immediatelly.

my workaround this bug (on latest canary)

somewhere in _app.js

import Router from 'next/router';

Router.events.on('routeChangeComplete', () => {
  if (process.env.NODE_ENV !== 'production') {
    const els = document.querySelectorAll('link[href*="/_next/static/css/styles.chunk.css"]');
    const timestamp = new Date().valueOf();
    els[0].href = '/_next/static/css/styles.chunk.css?v=' + timestamp;
  }
})

on every page reloads css after router change

my workaround this bug (on latest canary)

somewhere in _app.js

...
import Router from 'next/router';
...
Router.onRouteChangeComplete = () => {
  if (process.env.NODE_ENV !== 'production') {
    const els = document.querySelectorAll('link[href*="/_next/static/css/styles.chunk.css"]');
    const timestamp = new Date().valueOf();
    els[0].href = '/_next/static/css/styles.chunk.css?v=' + timestamp;
  }
}

on every page reloads css after router change

look like bicyclecode

@plag thanks so much for sharing that! πŸ˜„

@plag I've updated your comment to use Router.events instead: https://github.com/zeit/next.js#router-events

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

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

How ur layout will work in _app.js
For example

<Container>
  <Layout>
    <Component>
  </Layout>
</Container>

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

How ur layout will work in _app.js
For example

<Container>
  <Layout>
    <Component>
  </Layout>
</Container>

I am not using Layout in _app.js. Every single page has a container with Layout.
_e.g._ :

import React, { Component } from 'react';
import { connect } from 'react-redux';
import Layout from '../components/layout/Layout';

class FeedbackSuccess extends Component {
  render() {
    return <Layout title="ζ“δ½œζˆεŠŸ">ζ“δ½œζˆεŠŸ</Layout>;
  }
}

export default connect()(FeedbackSuccess);

Same issue, anyone can resolve it?

@tuanhuu
While waiting for fix, the simplest workaround is to create empty css file in static catalog and import it in _app.jsx

@tuanhuu
While waiting for fix, the simplest workaround is to create empty css file in static catalog and import it in _app.jsx

this doesnt work

@popugang well, it works for me ;)

@cherniavskii did you try following https://github.com/zeit/next-plugins/issues/282#issuecomment-432127816 ?

@stian-midlertidig no, I've resolved it by importing empty css file and it works

Sorry, I meant to cc @popugang πŸ˜„

@tuanhuu
While waiting for fix, the simplest workaround is to create empty css file in static catalog and import it in _app.jsx

it doesn't work for me but i try to add router event in _app.js as plag mentioned and it works

@tuanhuu
While waiting for fix, the simplest workaround is to create empty css file in static catalog and import it in _app.jsx

this doesnt work

Try https://github.com/zeit/next-plugins/issues/282#issuecomment-432127816, it works

@tuanhuu
While waiting for fix, the simplest workaround is to create empty css file in static catalog and import it in _app.jsx

This doesn't work me.

48554964-8950bc00-e8be-11e8-9d0a-a77eaaa4f3da

None of them is working for me too.

None of them is working for me too.

Hope solution will come out soon....

My current workaround is to import _all_ of the .css files used throughout my app in the _app.js file.

The drawback is that I have stylesheets loaded that are mostly unused on the current page, and I cannot co-locate CSS imports in the module that uses those styles. But it avoids this bug πŸ˜„

@cheong12001 @cemsusal @Jero786 @popugang

I'm curious how many of you are using @font-face in your stylesheets.

@kylemh I'm using it!

@kylemh I have @font-face in my style sheets with the following code:

@font-face { font-family: 'GothamBlack_TR'; src: url('/static/fonts/gotham/GothamBlack_TR.eot'); src: url('/static/fonts/gotham/GothamBlack_TR.eot') format('embedded-opentype'), url('/static/fonts/gotham/GothamBlack_TR.woff2') format('woff2'), url('/static/fonts/gotham/GothamBlack_TR.woff') format('woff'), url('/static/fonts/gotham/GothamBlack_TR.ttf') format('truetype'), url('/static/fonts/gotham/GothamBlack_TR.svg#GothamBlack_TR') format('svg'); }

Need more sample size to confirm that it’s somehow related, but this makes me πŸ€”

I'm curious how many of you are using @font-face in your stylesheets.

@kylemh Not in my case. Have no @font-face and experiencing the same problems.

You can try to reproduce with this repo. Sorry no sample data, you have to create a project and a subproject and try to navigate to a subproject from a project page to reproduce the issue. No @font-face used in this repo.

I also removed @font-face from my css and tested it and the issue persists.

So much for that idea πŸ˜‚

I read out there a workaround that seems like fix this problem, could you try guys if that works for you as well?

just add in their .eslintrc

...
"rules": {
...
        "no-console": 1,
...
}
...

@Jero786 that isn't a fix, but it's just preventing the react error renderer showing up. You likely still have hash collisions and your website should appear sightly off (missing some - if not all - styles)

I'm facing the same issues and tried all the workarounds suggested above. It has fixed the error messages however it is not loading the components CSS. Here's my next.config.js:

const withSass = require('@zeit/next-sass');

module.exports = withSass({
  cssModules: true,
  cssLoaderOptions: {
    importLoaders: 1,
    localIdentName: "[local]",
  },
  webpack: (config, { dev }) => {
    config.module.rules.push(
      {
        test: /\.js$/,
        loader: 'eslint-loader',
        exclude: /node-modules/,
        enforce: 'pre',
        options: {
          emitWarning: true
        }
      },
      {
        test: /\.(config)$/,
        loader: 'file-loader',
        options: {
          name: '[path][name].[ext]',
        }
      },
      {
        test: /\.(png|ttf|eot|wtf|jpg|svg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {}
          }
        ]
      },
    );

    const StyleLintPlugin = require('stylelint-webpack-plugin');

    config.plugins.push(
      new StyleLintPlugin({
        emitErrors: false,
        quiet: false,
      }),
    );

    return config;
  }
});

My _app.js:

import App, { Container } from 'next/app';
import Head from 'next/head';
import React, { Fragment } from 'react';
import '../style/global.scss';
import INITIAL_STATE from '../utils/initialState';

export default class MyApp extends App {
  state = { appState: INITIAL_STATE }

  static async getInitialProps({ Component, ctx }) {
    let pageProps = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps };
  }

  handleUpdateAppState = (event, step) => {
    const appState = { ...this.state.appState };
    appState[step][event.target.name] = event.target.value;

    this.setState({ appState });
  }

  handleUpdateCheckboxState = (checkboxObj, step) => {
    const appState = { ...this.state.appState };
    appState[step] = checkboxObj;

    this.setState({ appState });
  }

  render() {
    const { Component, pageProps } = this.props;
    return (
      <Fragment>
        <Head>
          {process.env.NODE_ENV !== 'production' && (
            <link rel="stylesheet" type="text/css" href={`/_next/static/css/styles.chunk.css?v=${Date.now()}`} />
          )}
        </Head>
        <Container>
          <Component
            onUpdateAppState={this.handleUpdateAppState}
            onUpdateCheckboxState={this.handleUpdateCheckboxState}
            appState={this.state.appState}
            {...pageProps}
          />
        </Container>
      </Fragment>
    );
  }
}
  • global.scss is not empty, it loads the vendors SCSS and some variables.
  • When I open /_next/static/css/styles.chunk.css the components CSS is there but the first time the components are rendered their CSS is not loaded.

I was able to prevent the error message by using these options in the withSass import:

  cssModules: true,
  cssLoaderOptions: {
    importLoaders: 1,
    localIdentName: "[local]",
  },

The reason why the localIdentName is just [local] is because I'm not using hashes in the css class names and if I disable cssModules I get the 'Unhandled rejection' error

For me a slightly different version of the above worked as temporary fix.

I am using Less so I installed "@zeit/next-less": "^1.0.2-canary.2" and then in _app.js:

import Router from 'next/router'
Router.events.on('routeChangeComplete', () => {
  const els = document.querySelectorAll('link[href*="/_next/static/chunks/styles.chunk.css"]')
  const timestamp = new Date().valueOf()
  els[0].href = '/_next/static/chunks/styles.chunk.css?v=' + timestamp
})

The difference with the above is that I used /_next/static/chunks/styles.chunk.css instead of /_next/static/css/styles.chunk.css

I am using sass in my project and initially had the "Unexpected Rejection", however upgrading to "@zeit/next-sass": "^1.0.2-canary.2" worked in removing the error. However, now I have the problem that my css wont load when switching pages, only after I refresh does it load. I have tried the solutions mentioned by @afuggini and @plag however I keep getting this error.

schermafbeelding 2018-12-13 om 10 32 36

@farisT Make sure the path on your _app.js and the path on your page source code matches.

@samhenri this solution worked for me. Thank you very much! Also I did not need to install any canary builds to make it work. I just needed the 3 lines in the withSass config

Edit: It seems I was too quick with my testing. It only works on some pages :(

I just wanted to add that I'm also experiencing this issue beyond simply route changes: any time I render a component in the client that is different than what is rendered on the server, the component's CSS fails to load.

class Comp extends Component {
  state = {
    isMobile: false
  };
  componentDidMount() {
    if (window && window.matchMedia("(max-width: 400px)").matches) {
      this.setState({ isMobile: true });
    }
  }
  render() {
    // MobileComponent.scss is not working
    return this.state.isMobile ? <MobileComponent /> : <DesktopComponent />
  }
}

I assumed this was worth mentioning here as it feels related, but if I'm alone here or this is actually unrelated I am happy to open a new issue with all of the necessary details.

@chancestrickland Exactly the same here. I have at least one component that is not stateless and any state change unloads the CSS and then loads it again with the config that I've posted above. Since I have some transitions in the CSS it shows the default properties such as colors and borders transitioning to the properties I have set in my styles.

I had to move all SCSS imports to my global.scss and downgraded next and next-sass to the stable versions.

I created a Head component and included CDN urls to relevant stylesheets there as follows.

`import Head from 'next/head'

function Heading(props){
return (



{props.title}





)
}

export default Heading `

Then I used this heading whenever stylesheets are needs.This began working perfectly for me.

I basically spent the entire afternoon fighting this annoying bug and none of the solutions I found so far worked for me.

So I've managed to come up with another possible quick-and-dirty workaround, if you don't mind performing an automatic hard-reload whenever the error occurs.

Put this in your _app.js:

if (process.env.NODE_ENV !== 'production') {
  require('next/router').default.events.on('routeChangeError', (err, url) => {
    if (err.stack.startsWith("TypeError: Cannot read property 'call' of undefined\n    at __webpack_require__")) {
      location.href = url;
    }
  });
}

I don't need the Router anywhere else in my _app.js, hence the require statement; but you could also do:

import Router from 'next/router';

if (process.env.NODE_ENV !== 'production') {
  Router.events.on('routeChangeError', (err, url) => {
    if (err.stack.startsWith("TypeError: Cannot read property 'call' of undefined\n    at __webpack_require__")) {
      location.href = url;
    }
  });
}

I know it's stupid, but it works. Careful if you're not simply copy-pasting – there are 4 spaces between \n and "at __webpack_require__".

I didn't have much luck with the solutions posted above. The best results I got was from the solution @plag showed, but it didn't work reliably (it just didn't work on few of the pages).

What ended up fixing it for me was importing antd like this import 'antd/dist/antd.css'; and not the modularised solution that's shown in the example (https://github.com/zeit/next.js/tree/canary/examples/with-ant-design)

Additionally, the styles we wrote are inside of 1 big .scss file with bunch of imports. When this issue get's fixed we'll split up our styles per component.

Currently using html <a href="/"></a> instead of Link or next-routes/Link πŸ˜”

That would make everything SSR, fwiw

Import some xx.css file in every page can reslove this problem

For me the only solution so far was to move all of the css imports to the _app file, the other solutions either didn't work or brought up new issues for me, it's similar to what @DyslexicDcuk is doing but I'm not using scss, didn't try the one proposed by @Sylvenas yet.

Also be sure to test the builds as well since sometimes I've seen that the issue was fixed by a solution on my local machine but when building the app the issue would still persist.

This has been killing me for a while now. I wrote the following hack to use until this gets fixed properly:

// HACK: Reload CSS in development
//       Remove when this issue is resolved:
//       https://github.com/zeit/next-plugins/issues/282
function initializeCssHack() {
  if (process.env.NODE_ENV == 'production') return;
  const href = '/_next/static/css/styles.chunk.css';
  Router.events.on('routeChangeComplete', () => {
    const css = document.querySelector(`link[href^="${href}"]`);
    const newCss = css.cloneNode();
    newCss.href = `${href}?c=${Date.now()}`;
    newCss.onload = () => css.remove();
    css.parentNode.appendChild(newCss);
  });
}

I call this at the top level within _app.js and am now able to successfully import CSS files within modules when running in development.

I'm brand new to Next and have been tearing my hair out for 3 days on this. I finally found this thread which was quite hard to find not knowing the exact search terms. I even put a post on StackOverflow and a post on Spectrum about this.

FWIW, I'm trying to migrate my nodejs/bootstrap/express app to Next and I came upon this by trying to load 3rd party React modules with their own CSS files. Therefore, I encountered this bug pretty early on in my exploration with Next. At least I see from all the comments that I'm not alone. 😒

Update: for those of you who say the temporary fixes don't work, I had to combine a couple of the approaches above to achieve success. Each one alone didn't quite do it.

  1. Add an empty style.css in my Layout.js which is included in every single page of my app.
  2. Add the following to my _app.js
import Router from 'next/router';
Router.onRouteChangeComplete = () => {
  if (process.env.NODE_ENV !== 'production') {
    const els = document.querySelectorAll('link[href*="/_next/static/css/styles.chunk.css"]');
    const timestamp = new Date().valueOf();
    els[0].href = '/_next/static/css/styles.chunk.css?v=' + timestamp;
  }
}

Importing an empty stylesheet into _app.js worked for me, both with canary and with this version

i have the same problem.adding css files to a wrapper component solves the problem waiting for a proper fix

Updated all libraries and the problem is still happening. I've left the project I was working but I'll try to reproduce the problem in a personal project and post the link here. The only viable solutions were:
1) Use global styles for vendor libraries and load them in the _app.js or in some sort of wrapper
2) Use a CDN for global styles and resets
3) Styled components for components

There's also a weird issue that on the first time you change routes, if there's any component using css animations, you can see the default browser styles changing to the styles that you created. Some times it happens whenever the component state has changed, if it is not a stateless component.

I can't resolve this problem even with any solutions posted above. Is it really necessary to deal with this during development? πŸ˜’

Solved with a mixture of above empty stylesheets, and building project once. Yay! ¬¬

I got it to work by adding an empty stylesheet to _app.js, using the onRouteChangeComplete watcher and also adding an empty stylesheet to whichever page is crashing. I have to say that this is kind of hacky and I know in the future I may delete the empty stylesheet if I forget what it's for. Please update if a proper fix is found, thank you.

How about updating Next to the new version 8.0.0 ?

How about updating Next to the new version 8.0.0 ?

Same

How about updating Next to the new version 8.0.0 ?

Just the developers do not want to do anything about it. Broke in version 7 and forgot

Just the developers do not want to do anything about it. Broke in version 7 and forgot

I'm very aware of this issue, the thing is that it doesn't happen consistently and it's very hard to debug, the 70 comments and 50 πŸ‘ and no real solution being figured out are evidence of that.

I'll be focusing on fixing this soon, but it's not trivial and will probably take a significant amount of my time, hence why I haven't been able to look into it yet.

How about updating Next to the new version 8.0.0 ?

I don't have access to the same project that I had reported the issue because I left the company I was working but I've copied the configuration file and package.json, updated with next 8.0.0 and the problem still persists with SCSS. I wasn't able to reproduce the animation bug when the state changes but I believe this has more to do with the transition property being loaded before the component styles than with next, unless something is making the component unmount/mount again instead of updating. In case someone ends up with the same problem, just make sure that you're not using transition: all time animation-type in any kind of "global" class

It seems to me that the loading fails because the server does not have the page prebuilt (builds it on request), at least in my case, only the initial page load is the issue... Once you refresh the browser, you can go to previous page and back to the problematic page with no issues via next/link.

If that is the case, is there any way I can try to run next in dev mode that would behave more like the production build and hopefully resolve this? As far as I remember, there were some major dev performance optimizations in the version that introduced this bug, and I have a feeling its because this building happens on demand?

Does that make any sense?

If that is the case, is there any way I can try to run next in dev mode that would behave more like the production build and hopefully resolve this?

This wouldn't be the correct solution to the issue.

As far as I remember, there were some major dev performance optimizations in the version that introduced this bug, and I have a feeling its because this building happens on demand?

On-demand entries has been a part of Next.js since 3.x

It seems to me that the loading fails because the server does not have the page prebuilt (builds it on request), at least in my case, only the initial page load is the issue... Once you refresh the browser, you can go to previous page and back to the problematic page with no issues via next/link.

The main issue here is that webpack doesn't handle dynamically loaded styles correctly / the HMR part of the extraction plugin seems to work incorrectly. Another issue is that it expects a file to load that is never loaded.

It seems to me that the loading fails because the server does not have the page prebuilt (builds it on request), at least in my case, only the initial page load is the issue... Once you refresh the browser, you can go to previous page and back to the problematic page with no issues via next/link.

If that is the case, is there any way I can try to run next in dev mode that would behave more like the production build and hopefully resolve this? As far as I remember, there were some major dev performance optimizations in the version that introduced this bug, and I have a feeling its because this building happens on demand?

Does that make any sense?

I have experienced this but also have experienced constant failures - it's very strange.

This is just slightly frustrating because something I have used previously that works fine, that you assume is core to the framework is now broken and not working properly and is the same across multiple versions of the package. I lost hours thinking I was doing something wrong myself.

But as the developer says I believe this would be a complex issue to fix - we can solve this together with further debugging. I will try my best to help.

@Brandoning

We cannot help because we do not know how the kernel works. Researching his work will take too long. I think because of the change in version 7 https://nextjs.org/blog/next-7/#css-imports

Does updating next to 8.0.3 fix it, or it has nothing to do with this?

I'm not sure about other peoples' situations, but client-side routing works w/o error after upgrading to v8. I haven't dived into whether or not route-based style-splitting is working correctly.

Does updating next to 8.0.3 fix it, or it has nothing to do with this?

dont fixed

I experience a similar behavior:

I have a page that loads react-table stylesheet with

import 'react-table/react-table.css';

I have another page "no-style" that doesn't load any CSS.

And finally, I have a link that targets a 404.

So that's 3 links in my menu:

- react-table
- no-style
- 404

At initial load, I can navigate from "react-table" to "no-style" and back to "react-table".
As soon as I hit the "404" page, I cannot go back to "react-table" but I can go to "no-style".
From there, opening a private browser session, restarting the dev server, closing and reopening the browser tab... None of them will make the link to "react-table" work again.

The only solution from there is to manually write the URL to the "react-table" page and it will be working again until I hit the "404" and everything is back to broken.

I will give the above workarounds a try.
I'm on 8.0.3.
The problem is present in prod and dev mode.

Edit:

Loading an empty CSS file in my _app.js fixed it.

import '../static/dummy.css';

Try new plugins versions with canary4

@zeit/[email protected] has the same problem.
I don't even seem to be able to reach my "react-table" page anymore without manually typing the URL first.

Just the developers do not want to do anything about it. Broke in version 7 and forgot

I'm very aware of this issue, the thing is that it doesn't happen consistently and it's very hard to debug, the 70 comments and 50 πŸ‘ and no real solution being figured out are evidence of that.

I'll be focusing on fixing this soon, but it's not trivial and will probably take a significant amount of my time, hence why I haven't been able to look into it yet.

@timneutkens
That's good to know, and by the way, I use "antd" through next-css, and it failed to switch to any page containing antd component through client navigation each and every time, 100% reproduceable! I am using "next": "^7.0.2" & "@zeit/next-css": "^1.0.1"
So if you need, I can create a demo for you.

@yxwu i made this basic example with the same problem

https://github.com/ivanhuay/next-css-conflict-example

They're aware of the issue, and are working on it.

@yxwu i made this basic example with the same problem

https://github.com/ivanhuay/next-css-conflict-example

@ivanhuay In fact, I don't know if it's the same as this issue, but I've studied the issues you're talking about.
I had the same problem, and I found the answer over the course of a few days.
The first problem is with "with-css".
"With-css" has "css-loader-config", where optimize config is used.

  if (!isServer) {
    config.optimization.splitChunks.cacheGroups.styles = {
      name: 'styles',
      test: new RegExp(`\\.+(${[...fileExtensions].join('|')})$`),
      chunks: 'all',
      enforce: true
    }
  }

This config ends up making all css a single chunk file.
I removed this config from "next.config.js" to fix the problem.

if (!isServer) {
    delete optimization.splitChunks.cacheGroups.styles;
}

And also changed the MiniCssExtractPlugin setting.

plugins.forEach((plugin, index) => {
    if (plugin.constructor.name === 'MiniCssExtractPlugin') {
        plugins[index] = new MiniCssExtractPlugin({
            filename: 'static/css/[contenthash].css',
            chunkFilename: 'static/css/[contenthash].css',
        });
    }
});

Let me know if you have any other ideas.

@kimorkim this solution doesn't work with Link from 'next/link'

i uploaded a new version in other branch

https://github.com/ivanhuay/next-css-conflict-example/tree/custom_config

@ivanhuay
oh, i see.
But it's not what it used to be.
To explain in detail, with-css makes all the styles used into a single chunk file.
So you cannot use a classname of the same name.

This can be resolved simply by using the cssmodule.

This file is automatically added to the "_document" and provided to the user.
However, it does not seem to update the already created "_document" when using "next/link".
This seems to be because "nextjs" operates as "spa" after page loading.
Perhaps the perfect solution should be devised to update the "_document".

@ivanhuay
I've made a solution with your repository.
I didn't use cssmodule and with-sass.
https://github.com/kimorkim/next-css-conflict-example
By default, we used the configuration of scss directly and put the results into jsx.

next.config.js

module.exports = {
  webpack(config, options) {
    const { module } = config;
    const { rules } = module;
    rules.push({
      test: /\.(sc|sa|c)ss$/,
      use: ["css-loader", "sass-loader"]
    });
    return config;
  }
};

index.jsx

import css from "./index.scss";
import Link from "next/link";
const Index = () => (
  <div className="container">
    <style>{css.toString()}</style>
    <h1>index</h1>
    <Link href="/b">
      <a>a pagina b</a>
    </Link>
  </div>
);
export default Index;

I don't think it's a good way, but you can get the results you want.

@kimorkim that work for me thanks!

but the way that next-css works is correct?

i don't know if this is a bug or the expected behavior.

in any way it should be documented

@ivanhuay It is not the way to use "with-css".
It is a combination of ordinary webpack and css.
would be better to use the cssmodule when using nextjs.
This is the official way.

But I don't think there will be a problem with that.
Of course, it may differ from the optimization direction that nextjs is pursuing.

I need a better idea.

@kimorkim Thanks so much for your code in this comment

I've been battling the call undefined moduleid issue for a few days now, switching the versions of nearly everything and up until the point of dropping the nextjs dependency entirely and rolling our own SSR.

Thanks for figuring out a bandaid to get our build system working for another few weeks until something else introduces a breaking change!

so in "next": "^8.0.3", it's still the same, router.push is broken

I am having the same issue I think. Unable to navigate using Link tags unless I import styles used in subsequent linked pages. Is this related?

@kimorkim , I did in next.config.js how you wrote. In _document.js did import styles from bootstrap, tryed scss file import bootstrapStyles from "bootstrap/scss/bootstrap.scss"; and css file import bootstrapStyles from "bootstrap/dist/css/bootstrap.min.css";, pasted <style dangerouslySetInnerHTML={{ __html: bootstrapStyles,}} /> in Head component, but in browser I recived <style>[object Object]</style>. If I doing <style dangerouslySetInnerHTML={{ __html: JSON.stringify(bootstrapStyles) }} /> in browser I see <style>{}</style> , just empty object ( Help me, please.

I have this problem, too. Importing an empty css file in _app.js half-resolved the problem for me. It allowed navigating to the next page to work, but the css imported in the next page wasn't actually applied.

Moving all css imports to _app.js fully resolved the problem. So, that seems to be the workaround that actually works.

@mrrotberry Even the same style import has different results depending on the webpack setting.

import css from "./index.scss";
//...
    <style>{css.toString()}</style>
//...

My setting must be use css.toString().
The bootstrapStyles you used will be able to check the contents with the console.
Check your console.log

@popuguytheparrot Thanks for the help! I was able to fix it by adding the following to my _document.js:

import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';

export default class CustomDocument extends Document {
  static async getInitialProps(ctx) {
    return {};
  }

  render() {
    return (
      <html lang="en">
        <Head>

          {process.env.NODE_ENV == 'production' && (
            <link
              rel="stylesheet"
              type="text/css"
              href={'/_next/static/css/styles.chunk.css?v=' + Date.now()}
            />
          )}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

My export command has to specify NODE_ENV to work:

NODE_ENV=production && rm -rf out && next build && next export

Guys, the method that @kimorkim described works only if you don’t use @zeit/next-css and @zeit/next-sass. Thank you again very much, @kimorkim.

More notes on this...

You have to manually hit the dev server to create /_next/static/css/styles.chunk.css. This really threw me, because it broke in my CI pipeline. The CI pipeline isn't hitting the dev server... so it never creates the styles.chunk.css file.

I've temporarily turned off my CI pipeline so that I can manually create styles.chunk.css using the dev server and deploy manually.

I was able to solve the problem πŸ’«. Check solution here: https://github.com/shashkovdanil/next-styles-fixed. Works in dev and prod. I extracted the next-css packages for work with .sss files (SugarSS), you can not do it.

Most likely fix in the update next and @zeit/next-css packages.

Thank you @shashkovdanil, your fix worked for me!

Most likely fix in the update next and @zeit/next-css packages.

canary 4 has fix

Same problem!

I use [email protected] and @zeit/[email protected].

@nuintun , try @zeit/[email protected] (yarn add @zeit/next-less@next), check my example https://github.com/shashkovdanil/next-styles-fixed

@shashkovdanil Thanks, I try this, but still not working for me.

An update of https://github.com/zeit/next-plugins/issues/282#issuecomment-432127816

if (process.env.NODE_ENV !== 'production') {
  Router.events.on('routeChangeComplete', () => {
    const chunksSelector = 'link[href*="/_next/static/chunks/styles.chunk.css"]';
    const chunksNodes = document.querySelectorAll(chunksSelector);
    const timestamp = new Date().valueOf();
    chunksNodes[0].href = `/_next/static/chunks/styles.chunk.css?${timestamp}`;
  });
}

So is there a definitive fix to this? I've tried all of the above mentions (really appreciated, too) but no luck.

@dougwithseismic, this bug may not be fixed, use css-in-js with runtime js code (emotion, styled-components).

Or try my package https://www.npmjs.com/package/next-with-css, https://www.npmjs.com/package/next-sugarss

I've started linking my third-party CSS in with tags. Old-school HTML still works :)

Is this issue fixed????

@movingStars Nothing new but it was solved with a hacky fix. Try adding import '../static/css/empty.css' to _app.js template (where empty.css is literally an empty css file) and all was sorted. Shitty workaround but works. Have you tried?

https://spectrum.chat/thread/2183fc55-236d-42cb-92b9-3ab10acc6303?m=MTUzODU2NDg2ODA2Mg==

Next team is aware and working on it! It's complex and will take time.

Importing an empty stylesheet into _app.js nor importing a stylesheet on every page resolved the issue for me locally.

Thanks! It's work for me :)

I fixed this problem in version 8.1 using this way:

_app.js:

{process.env.NODE_ENV !== 'production' && (
  <link
      rel="stylesheet"
      type="text/css"
       href={`/_next/static/css/styles.chunk.css?v=${Date.now()}`}
    />
)}

and load css in my BaseTemplate component:

import '_styles/base.css'

@helderburato
its look like a fix, but is not

Coming up with the same error here - using the empty CSS files nor the router hack worked.

  "dependencies": {
    "@zeit/next-sass": "^1.0.1",
    "firebase-admin": "^6.3.0",
    "firebase-functions": "^2.1.0",
    "next": "^7.0.0",
    "node-sass": "^4.12.0",
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
    "react-image-gallery": "^0.8.16"
  }

Since September.. phew.

This comes over as a pretty aggressive comment. Just wanted to point that out.

This comes over as a pretty aggressive comment. Just wanted to point that out.

Just edited it out - didn't mean it aggressively. I meant it as doubt in my project as I've tried many other SSR React methods and this got me the closest, aside from this :)

No worries ❀️ I assumed you didn't mean it like that πŸ™

I'm trying to replicate this error, Is there a difference in the output when you import any of next-css | next-less | next-sass as --save-dev or --save

Same problem!

I use [email protected] and @zeit/[email protected]. and @zeit/[email protected]

Is there a fix for this on latest version of next and next-css? This is a road blocker for my and am going to have to switch off of next if this doesn't work.

Edit: I've tried every recent fix in this thread and none work for me.

Edit: I've tried every recent fix in this thread and none work for me.

 // _app.js
 Router.events.on("routeChangeComplete", () => {
   if (process.env.NODE_ENV !== "production") {
     let elems = document.querySelectorAll("link[href*=\"/_next/static/css/styles.chunk.css\"]")
     let timestamp = new Date().valueOf()
     elems[0].href = "/_next/static/css/styles.chunk.css?v=" + timestamp
   }
 })

hack works. The downside is that it causes an extra rerendering in browser (page screen blinks, everything reevaluates) – not good for dev either. Personally, I'm going to solve the case by switching to CSS-in-JS. But I understand your frustration, bro ;) The bug is too annoying.

What's the state here?

This is still broken :/

Very easy to replicate this one, but bamboozled me for the past couple of months! Would be great to at the very least add a note to the top of the next-css (or better, next.js) readme highlighting this bug. It had me thinking next.js was just very slow in development and was timing out or something πŸ€¦β€β™‚οΈ.

Yet another simple demo of the issue:
https://github.com/kirkness/nextjs-with-css

my workaround this bug (on latest canary)

somewhere in _app.js

import Router from 'next/router';

Router.events.on('routeChangeComplete', () => {
  if (process.env.NODE_ENV !== 'production') {
    const els = document.querySelectorAll('link[href*="/_next/static/css/styles.chunk.css"]');
    const timestamp = new Date().valueOf();
    els[0].href = '/_next/static/css/styles.chunk.css?v=' + timestamp;
  }
})

on every page reloads css after router change

Many thanks! The solution works well!

What is needed here to push it forward? Some guys have time to mark comments as spam but not to work on a solution. I'm here to help.

@developit is figuring out a solution to the issue.

Please stop spamming this thread with "any update", thanks πŸ™

i meet the same problem ..is the problem happened only in the dev ?

As said before:

Please stop spamming this thread, thanks πŸ™

Yes it's only related to development (as said before in this thread).

Hi everyone,

I've found a work around if the previous work arounds did not work for you as they didn't for me. This strategy is only useful for those using CSS-in-JS. What I did is I used raw-loader to import my necessary css files as a TXTlike this:
import DatePickerCSS from "raw-loader!react-datepicker/dist/react-datepicker.css";
Then I simply used that file in my GlobalStyle: ${DatePickerCSS} You can also inject it into the global. This strategy seems useless if you're already using a CSS-in-JS module however if you have dependencies that have their own CSS files, then this can be a helpful work around.

+1

@dmwin72015 I'm really not sure what more to say. There's 68 participants in this thread. You're pinging every single one of these people for a +1. You can use GitHub's πŸ‘ feature at the start of the thread.

As said, now for the third time:

Please stop spamming this thread, thanks πŸ™

I'd rather not lock this thread as it discourages people to investigate.

Thanks @ijjk for sending me here. My issue seemed to be specific to AOS css - Animate On Scroll Library, I was using AOS.init() on some pages but not others, moved the AOS.init() into _app.js and voila πŸŽ‰
Hope this helps someone

...

import AOS from 'aos'
import 'aos/dist/aos.css'

class MyApp extends App {
    static async getInitialProps({ Component, ctx }) {
        let pageProps = {}
        if (Component.getInitialProps) {
            pageProps = await Component.getInitialProps(ctx)
        }
        // this exposes the query to the user
        pageProps.query = ctx.query
        return { pageProps }
    }

    componentDidMount() {
        AOS.init({
            duration: 600,
        })
    }

...

I'm observing the same issue but:

  • Using next-sass instead of next-css.
  • It only happens on production (after next build). Under development there's no issue.

What seems to be causing it is the fact that source page has no styles import while the target page has. So avoiding that situation is useful as a workaround:

  • Option 1: Importing an empty style file (sass or css) in the source page
  • Option 2: Importing an empty style file inside _app.js so we ensure all pages have styles even if they don't need them.

Option 2 seems to be more elegant and will scale across your app, so it is what I suggest to do.

This seems to be making it impossible to split CSS per-page. I'm running into it in both dev & prod environments.

I'm using next-sass. I'm outputting one common CSS file served on every page - this one's fine.

However, I'm also splitting page-specific CSS so that each page gets its own file. When using Link, these files are not requested.

Is the Next team planning to address this any time soon?

@geochanto css splitting is unrelated to this issue, as next-css doesn't include css splitting support as of right now. We're planning to introduce css imports into Next.js core eventually that will have css splitting.

@timneutkens I'm splitting with webpack splitchunksplugin. In and of itself, splitting works fine - CSS files are generated in the static folder, and tags exist in the DOM both on server and client side.

Problem only occurs when using next/link, which prefetches pages but does not request CSS files in the process. So it seems somewhat related to me.

That's custom config unrelated to this plugin, this bug is something else, it's related to webpack output JavaScript files that shouldn't be there and it automatically waiting for those.

@timneutkens Can u point to the code that is waiting for those js files in Next?

Not really as it really has nothing to do with Next.js, it's webpack's loading mechanism.

As I once said, next-css is basically based on SPA. It's not MPA.
For now, it seems best to use 'css-module' or 'styled-component'.
Until next.js supports MPA.
but this is my opinion. It can be wrong

@kimorkim when I only use css-module or styled-component ,it is fine.If both are used, it will go wrong.

As I once said, next-css is basically based on SPA. It's not MPA.
For now, it seems best to use 'css-module' or 'styled-component'.
Until next.js supports MPA.
but this is my opinion. It can be wrong

What do you mean by css-module?

@ThoughtZer I completely agree with you.

@felixmosh Literally css-modules
I think my explanation was lacking before.
First of all, I am not good at expressing English because it is not my first language. I hope you understand.
There seem to be a mix of some problems on this issue.
What I am saying is this.
Next.js sends all styles to clients when the first page is rendered.
This is a problem when you think of MPA.
Because of this, different page styles are applied to the current page.
So I recommended a way to apply style independently.
Among them, I mentioned "css-modules" and "styled-component".
I think there are many other ways besides this.

I had the same issue. I was using two layout components which loaded the main css file.
After creating a custom pages/_app.js where I import the main css file, the issue was gone.

Also this issue is a little bit tricky, since everything worked on development mode but not in production.

https://spectrum.chat/thread/2183fc55-236d-42cb-92b9-3ab10acc6303?m=MTUzODU2NDg2ODA2Mg==

Next team is aware and working on it! It's complex and will take time.

Importing an empty stylesheet into _app.js nor importing a stylesheet on every page resolved the issue for me locally.

I use [email protected] with [email protected]. The problem I got was that router can't be redirected to the page containing DatePicker. (router.push or router.replace)

But router works well in development env. The problem appears after next build && next export.

After adding Importing a stylesheet into _app.js, the problem has gone.

I guess is not related with the <Link /> or next/router itself. The same issue is happening to me loading a modal content with the next/dynamic. Looks that the first time that is getting the content also is not downloading the styles correctly, similar than navigating to another page using the <Link /> component.

The workaround doesn't work for me in the latest version 9.1.3. Here is the updated version:

if (process.env.NODE_ENV !== 'production') {
  Router.events.on('routeChangeComplete', () => {
    const path = '/_next/static/chunks/styles.chunk.css';
    const chunksSelector = `link[href*="${path}"]:not([rel=preload])`;
    const chunksNodes = document.querySelectorAll(chunksSelector);
    if (chunksNodes.length) {
      const timestamp = new Date().valueOf();
      chunksNodes[0].href = `${path}?ts=${timestamp}`;
    }
  });
}

Still an issue over a year later with Next 9.1.3 and next-css 0.2.1-canary.4

Are there any plans to fix this?

I also want to add that the proposed solutions didn't work for me. My situation is the following:

@myscope/button

...
import style from './style.css'
...

MyPage.tsx

import Button from '@myscope/button'
...

This will results in a broken client side navigation, since the styles of my button won't be loaded, both on development and production build.

I found that importing the Button within the _app.tsx, without reference, will fix the problem. So I'm currently importing my external components as workaround like so:

_app.tsx

...
import '@myscope/button'

I really hope this will be addressed soon...

@amclin yes - CSS integration is their number one priority right now. Keep an eye on releases. They're making it 1st-class and moving away from the plugin though.

@amclin this still stands: https://github.com/zeit/next-plugins/issues/282#issuecomment-462743580

We're working on bringing in CSS imports support into Next.js: https://github.com/zeit/next.js/issues/8626

Still an issue over a year later

As said earlier there's been 152 replies and most are looking into workarounds instead of fixing the actual issue. I've invested a lot of my free time into investigating this and we've started building CSS imports into Next.js by default partially because of this issue with next-css.
Overall that particular statement comes over to me as "fix it" instead of "what can we do to help solve the issue".

Overall that particular statement comes over to me as "fix it" instead of "what can we do to help solve the issue".

@timneutkens that's a fair criticism, and certainly was not my intent.

In most projects, long running bugs that are waiting on major refactoring efforts never get fixed, and it can become a significant detriment to adoption for that project as it causes frustration for its users. I'm not saying that's the case here, but user's perceptions will lean this way based on their experience with other projects. When there's 152 comments, most people will gloss over the ones in the middle that say "we're working on it".

Back to the issue in question:

As an interim solution to get you breathing room, would it be reasonable to adopt whatever the "most correct" workaround for the current state into the NextJS base _app.js, _document.js, or router since that's the level where the solution would need to be applied?

There really is no interim solution to this issue, it's a bug in webpack / the way it loads code. The workarounds mentioned try to fix symptoms of the issue and don't cover all cases.

In most projects, long running bugs that are waiting on major refactoring efforts never get fixed, and it can become a significant detriment to adoption for that project as it causes frustration for its users. I'm not saying that's the case here, but user's perceptions will lean this way based on their experience with other projects. When there's 152 comments, most people will gloss over the ones in the middle that say "we're working on it".

Well the alternative was locking the thread as mentioned multiple times as people keep adding +1 type comments that don't work towards solving the issue. We're definitely addressing larger issues people run into. As said before this is a complicated one and we're planning to solve it by imposing more constraints on what people can do with CSS imports to prevent common pitfalls.

Hi @timneutkens, Thank you for helping on this issue. I am wondering if this stylesheet importing issue is going to be fixed in the next release? It seems two issues under the hood:

  1. next/route: if a page under ./pages/* import a component which import any stylesheet within it. The routing will fail to route to that page
  1. @zeit/next-css: the temporary fix like import an empty stylesheet in _app.js actually make the routing work, but the page shows no style at the initial loading, styles.chunk.css will not be loaded until I refresh the page or explicitly direct visit the route.

We're working on https://github.com/zeit/next.js/issues/8626 in particular.

If anyone stumbles upon this and is looking for a workaround:

  1. Create an empty CSS file in /static/ directory.
  2. Import it in _app.tsx:
// import stuff
import '../static/jank-empty.css';

// ...more _app.tsx stuff

My project structure:

.
β”œβ”€β”€ components
β”œβ”€β”€ contexts
β”œβ”€β”€ jest.config.js
β”œβ”€β”€ lib
β”‚Β Β  β”œβ”€β”€ hocs
β”‚Β Β  └── hooks
β”œβ”€β”€ next-env.d.ts
β”œβ”€β”€ pages
β”‚Β Β  β”œβ”€β”€ _app.tsx
β”‚Β Β  β”œβ”€β”€ _document.tsx
β”‚Β Β  β”œβ”€β”€ index.tsx
β”‚Β Β  └── new-post.tsx
β”œβ”€β”€ specs
β”‚Β Β  └── index.spec.tsx
β”œβ”€β”€ static
β”‚Β Β  └── jank.css
β”œβ”€β”€ tsconfig.json
└── tsconfig.spec.json

next version: 9.0.5
@zeit/next-css version: 1.0.1

Good luck.

If anyone stumbles upon this and is looking for a workaround:

  1. Create an empty CSS file in /static/ directory.
  2. Import it in _app.tsx:
// import stuff
import '../static/jank-empty.css';

// ...more _app.tsx stuff

Good luck.

Would you mind sharing your code structure? I don't know whether I should use /static/ directory in .next/static or in my src

If anyone stumbles upon this and is looking for a workaround:

  1. Create an empty CSS file in /static/ directory.
  2. Import it in _app.tsx:
// import stuff
import '../static/jank-empty.css';

// ...more _app.tsx stuff

Good luck.

could you also share your next.js and next-css version?

@seta-namle @vbilici I updated my comment. I hope it helps.

@AryanJ-NYC so can I still import second css with my styles? So I should import empty one in app.js and the proper one where?

@Shaquu I imported the "proper one" whereever it belonged. For instance, I needed Editor styles so I imported my Editor-specific CSS in /pages/new-post.

In my case, importing an empty css file in _app.js file didn't work. So I've imported all the css file that I need in _app.js file. And it seems to work just fine now.

Would this be too inefficient way to import css? anybody has opinion about this?

All right. Solved for me by doing what you suggested.
Now my first line in _app.tsx is:
import '../assets/empty.less'
If it helps for someone, I am using ant.design and Table component caused problems for me.

All right. Solved for me by doing what you suggested.
Now my first line in _app.tsx is:
import '../assets/empty.less'
If it helps for someone, I am using ant.design and Table component caused problems for me.

Hi @Shaquu, I also use ant design with sass. @AryanJ-NYC method only fix it partially. I still lost some style.
@lmhkkang Do you import all the css file of your project or just this one _next/static/css/styles.chunk.css like some answers above?

Do you import all the css file of your project or just this one _next/static/css/styles.chunk.css like some answers above?

@seta-namle I import all the css file of my project
I just tried it to see if it works and it worked. That why I'm curious if it's inefficient way or not.

I found that replacing styles.chunk.css with a timestamp refresh caused page flicker issues.

So my solution is to append the css first, and then wait for the rendering (about 1s) to finish before deleting all the previous css.

https://github.com/SolidZORO/leaa/blob/a101b9b4fc6c6e06490085f210d6606fbbc926c2/packages/leaa-www/src/pages/_app.tsx

// _app.tsx

// force refresh style.chunk.css (ONLY for dev mode)
// related discussions @see https://github.com/zeit/next-plugins/issues/282
if (process.env.NODE_ENV !== 'production') {
  const refreshChunkStyle = (chunkFileName: string) => {
    const head = document.getElementsByTagName('head')[0];
    const style = document.createElement('link');

    style.rel = 'stylesheet';
    style.href = `${chunkFileName}?ts=${new Date().getTime()}`;
    head.append(style);

    const chunks = document.querySelectorAll(`link[href*="${chunkFileName}"]`);

    // delete all chunks css, except the last one. (delay 1s to keep the page from flickering)
    setTimeout(
      () => chunks.forEach((c, i) => i !== chunks.length - 1 && c && c.parentNode && c.parentNode.removeChild(c)),
      1000,
    );
  };

  Router.events.on('routeChangeComplete', () => {
    refreshChunkStyle('/_next/static/css/styles.chunk.css');
  });
}

I was experiencing same issue.

To simplify, I have 3 pages (/, /search, /login).

In my login page I use the next snippet:

componentDidMount {
    if (condition) {
        Router.push('/search')
    }
}

Redirect only worked in dev mode, not on static export. Importing empty.css in _app.js file didn't fix the problem.

But importing empty.css both in /search and /login pages fixed the issue.

Here is updated version of this for v9.1.4:

import Router from 'next/router'

if (process.env.NODE_ENV !== 'production') {
  Router.events.on('routeChangeComplete', () => {
    const path = '/_next/static/css/styles.chunk.css'
    const chunksNodes = document.querySelectorAll(`link[href*="${path}"]:not([rel=preload])`)
    if (chunksNodes.length) {
      const timestamp = new Date().valueOf()
      chunksNodes[0].href = `${path}?ts=${timestamp}`
    }
  })
}

There was changed location of styles.chunk.css.

I'm using next 9.1.6 and @zeit/next-sass 1.0.1 module and my problem was that the Links were not working in production, when I was visiting the website from a page other than ./pages/index.js.

The only solution that works for me is importing empty.scss in every page.

However, what I discovered is that if I import empty.scss in more than 5 pages, again all the Links break down entirely in production. So, I created and imported a second empty2.scss in the rest of my pages (I have 9 pages in total, at this moment) and now works.

This is becoming unbelievable and I am seriously considering switching to a more "bare bones" solution like pure reactjs, over which I have more control over.

These workarounds worked good in dev env πŸ‘ however, I noticed same behaviour in production when using experimental granularChunks. Styles were not applied correctly until page was refreshed. And I am not sure how to apply these fixes in production since style chunk filename has unique hash.

Is this solved with NextJS 9.2?

I've been using an import in _app.js as a workaround, which now is included without the need of @zeit/next-css, but it's not clear if per-page imports are solved as well.

Should be! Sass is a'comin' too

We switched to the Experimental CSS Modules system in NextJS 9.1 (as of 9.2 it's enabled out of the box, does not need configuration settings) and this issue is completely solved.

any info about sass? I'm having the same issue with next-sass

I had 9.2 with @zeit/next-css installed and configured and thus turned off the 9.2 default css support. Removed @zeit/next-css, restarted and am good to go.

per 9.2 docs

If you are currently using @zeit/next-css we recommend removing the plugin from your next.config.js and package.json, thereby moving to the built-in CSS support upon upgrading.

any info about less? I'm having the same issue with next-less

@kylemh thanks! your workaround with an empty file works great. My project is based on next-css & next-sass, so I've added your workaround to the readme here https://github.com/webdeb/next-styles#known-issues

But the default in-built css support doesnt include css variables. So, I have to use next-css.

@KartheekJavvaji how'd you mean? The implementation is very similar to next-css with more constraints.

I have same issue with next v9.0.2 and typescript v3.4.5.When I redirect to another page with next/link it takes too much time to load page .

I still facing this in next-sass, can't believe a 2018 bug is still there, very bad.

@ivanhoe-dev try https://github.com/webdeb/next-styles

Same issue

@carvinlo you are right.. I've also mentioned that Issue at the bottom of the readme.

Still seeing this on 9.2.1 and next-sass 1.0.1. Am i doing something wrong? is the consensus that this is solved?

is the consensus that this is solved?

don't think so, instead the consensus is that the workaround is not that scary. (you basically have to load a style in your _app.js)

import "../styles/global.scss"

// And export the default app or define your own..
export { default } from 'next/app'

Still seeing this on 9.2.1 and next-sass 1.0.1. Am i doing something wrong? is the consensus that this is solved?

I guess that in 9.2.3 sass is going to be part of next.js without this plugin. In 9.2.1 you can active the behavior under the experimental.scss = true flag in your next.config.js file.

Perhaps instead of doing some workaround to support this plugin is better to change to the experimental flag in development, and in some days, in 9.2.3 you can just remove the experimental flag.

Any official resolution from Next authors yet?

Any official resolution from Next authors yet?

Use built-in CSS support: https://nextjs.org/blog/next-9-2
Sass support is coming soon (already available on next@canary)

can confirm the built-in sass support available in next@canary fixes this, but breaks all sorts of other things such as sass mixins / functions, importing sass from node_modules, any custom sassLoaderOptions you may have set, the :global flag in css modules, importing non .module.scss files into components, as well as any bundle splitting you are doing currently.

https://github.com/zeit/next.js/issues/10755 referring to this issue

1. Go to this link http://ec2-3-134-112-176.us-east-2.compute.amazonaws.com:3000/english-test.
2. Click on header title Fluency Hub on the top left header.
3. You will get navigated to another page you can see the page with broken CSS.
4. Now, refresh the page its CSS works well but after again repeating these steps gave issue only in the production build.
5. If you are cloning the repo then just clone the repo from this link https://github.com/geekyoperand/fluencyhub.git.
6. Now run the npm run start:staging for producing issue which will run a production build of next.js.
7. If you run just npm run start It will work well because it will run a development build.

after client side routing expected :
image

after client-side routing current :
image

@timneutkens I have tried removing the next-css as suggested by you as I read the blog carefully but still not able to fix my issue. I have updated my repo.
Can you try once running at your locally and suggest a better method?

I am having this issue with [email protected].

This fix worked for me: https://github.com/sheerun/extracted-loader/issues/11.
It also works much better than the routeChangeComplete hack and causes no _FOUC_ flashes.

I guess the root cause of this issue is regarding HMR handling of next and the mini-css-extract-plugin

Any update on this issue ?

@shirshendubhowmick https://github.com/zeit/next-plugins/issues/282#issuecomment-590219154

Sass support was introduced too recently: https://nextjs.org/blog/next-9-3

Hi
@timneutkens Thanks for replying.

Actually my use case is bit different.

I need a custom CSS loading configuration, so i have written it in next.config.js

I am using mini-css-extract-plugin to generate CSS files. Everything works fine in production mode.

However in development mode whenever i am doing a client side navigation using <Link> the CSS file of that particular page is not getting loaded.

A direct hit to that page (server side navigation) works fine though.

@shirshendubhowmick are you using styled components lib? I had the same issue with components and had to rollback styled components to v4 as it was clearing the