FOUC: Initial page loaded without any styles

Viewed 2843

I'm trying to apply global styles by importing .scss files in _app.js for a Nextjs app.

But the issue is, styles are not getting pre-applied on page load. Because of which FOUC happens for all the initial page render.

Example 1

Given below is a basic version of the issue mentioned above:

Project structure:

pages/
    _app.js
    index.js
app.scss
package.json

index.js file:

export default function Home() {
  return (
    <div className="hello">
      <p>Hello World</p>
    </div>
  );
}

_app.js file:

import "../app.scss";

export default function App({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

app.scss file:

 $color: red;

 .hello {
     background-color: lavender;
     padding: 100px;
     text-align: center;
     transition: 100ms ease-in background;

     &:hover {
         color: $color;
     }
 }

package.json file:

{
  "name": "basic-css",
  "version": "1.0.0",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "next": "^9.4.5-canary.31", // using canary build as per https://github.com/vercel/next.js/issues/11195
    "node-sass": "4.14.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1"
  },
  "license": "ISC"
}

Example 2 (repo using next-sass)

As per the 3rd point of @Ramakay's answer Which creates a static hashed css file and appends it to <head/> tag but still the issue persists.


What I am expecting:

enter image description here

What I'm getting now:

enter image description here

I'm not using any external library like "styled-components" etc. And I'm not looking for it.

What can I do to fix the issue at hand?

1 Answers

Because this is a CSS in JS approach, the files are not rendered on the server side for the document pre-parser to apply so it has to wait for Javascript to download

  1. You can use the Nextjs offering - https://github.com/vercel/styled-jsx - which will output styles server as well as client side.
  2. You can look at exporting the SCSS separately and linking to the document head.
  3. Next-sass with Node-sass outputting a file - https://github.com/vercel/next-plugins/tree/master/packages/next-sass + https://github.com/sass/node-sass#outfile
Related