Next js static export unstyled html flash. [FOUC]

2.4k Views Asked by At

I am working with next.js and everything seems to be fine when I am using app with npm run dev.

But when I am exporting my next.js app to a static files with command npm run build and trying to open my project for part of the second the screen is unstyled, this cause verry bad user experience.

I know this is called FOUC but how to avoid it on next.js static export?

P.S I am using styled-components library, not sure if that affecting the final result.

3

There are 3 best solutions below

0
On

For anyone facing this annoying problem using styled-component, I solved it by referring to this and this to render your styling on the server side before your page loads. Hope this helps someone end their frustration

import Document, { Html, Head, Main, NextScript, DocumentContext } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
    static async getInitialProps(ctx: DocumentContext) {
        const sheet = new ServerStyleSheet();
        const originalRenderPage = ctx.renderPage;

        try {
            ctx.renderPage = () =>
                originalRenderPage({
                    enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
                });

            const initialProps = await Document.getInitialProps(ctx);
            return {
                ...initialProps,
                styles: [initialProps.styles, sheet.getStyleElement()],
            };
        } finally {
            sheet.seal();
        }
    }
    render() {
        return (
            <Html lang="en">
                <Head />
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        );
    }
}
0
On

Long shot that this is a fix for anyone else, but I saw this behavior when I mistakenly wrapped the entire page contents inside the head tag. Heh, oops.

So don't override Document with something like this like I did, make sure to close that head tag sooner:

<Html lang="en">
    <Head>
        <body>
            <Main />
            <NextScript />
        </body>
    </Head>
</Html>
0
On

If you are using styled-components, I would look into modifying your _document.js file per these instructions: https://styled-components.com/docs/advanced#server-side-rendering

That's how I managed to get out FOUC after trying a bunch of random stuff like:

  • putting a loader
  • putting a <script>0</script> tag
  • etc..