Solve flash of unstyled content (FOUC) on NexJS and GatsbyJS

July 30, 2020

This guide will help you solve the issue known as “flash of unstyled content” (FOUC) on your Nextjs or Gatbsyjs site that was likely caused by Styled Components.

As mentioned in the title, the flash of unstyled content may be caused by the use of the styled-component plugin. That makes it super easy to solve. The issue is usually visible when the site is in production, or when you build and serve the site. Rather than waiting to merge the changes in production I suggest to build the site and serve it on local.

Let’s start with the solution on Nextjs.

Solve FOUC on NextJS

First of all open the server.js file and add these lines of code:

// server.js const next = require('next') const routes = require('./routes') const app = next({dev: process.env.NODE_ENV !== 'production'}) const handler = routes.getRequestHandler(app) // With express const express = require('express') app.prepare().then(() => { express().use(handler).listen(3000) })

While the second step is to modify the _document.js file:

import Document from 'next/document' import { ServerStyleSheet } from 'styled-components' export default class MyDocument extends Document { static async getInitialProps (ctx) { 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() } } }

Save, build and serve the site, and the issue should be solved.

Solve FOUC on GatsbyJS

The solution for the flash of unstyled content on Gatbsy is much simpler than on Nextjs.

First install the gatsby plugin for Styled Components:

npm install gatsby-plugin-styled-components styled-components babel-plugin-styled-components

Then open the gatsby-config.js and add the newly added plugin within the plugins list:

module.exports = { plugins: [{ resolve: `gatsby-plugin-styled-components`, options: { // Add any options here }, },], }

At this point you just need to build and serve the site. FOUC should no longer happen.

Personal blog of Joseph, co-founder of With a focus on node and javascript development, blockchain and photography.