# A/B test variations styling doesn’t often look right using \`emotion\` css styling with Next.js

**URL:** <https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197>\
**Category:** CMS\
**Tags:** styling, nextjs\
**Created:** [October 19, 2021, 9:36pm UTC](https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197 "2021-10-19T21:36:50Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![TimG](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.builder.io/timg/32/714_2.png) [@TimG](https://forum.builder.io/u/TimG)\
**Post date:** [October 19, 2021, 9:36pm UTC](https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197/1 "2021-10-19T21:36:51Z")

</div>

In `@builder.io/react@1.1.46` and above we introduced SSR support for a/b tests variations by default, those variations are rendered under `template` html tags so they don’t have any effect on rendering performance, the [issue](https://github.com/emotion-js/emotion/issues/2040) with using `emotion` css lib is that it doesn’t hoist the resulting styles all the way to the body tag, which could cause a flashing of unstyled content if you’re assigned to one of the tests groups of the content. To fix this issue we need to post process the rendered html to pluck all those styles tags that are tucked under the template tag up to the body tag.

In Next.js you can do that by extracting the styles into a [custom document](https://nextjs.org/docs/advanced-features/custom-document)

To do this, you will first create a file at `./pages/_document.js`, this will replace the default Document normally provided by Next.js

then we’re going to need a library to make it possible to extract the necessary styles, we recommend `cheerio`

```auto
npm install cheerio

```

Import cheerio into your \_document file and then we can create a function to extract all the necessary styles

```auto
const extractABTestingStyles = (body) => {
  let globalStyles = ''

  if (body.includes('<template')) {
    const $ = cheerio.load(body)
    const templates = $('template')
    templates.toArray().forEach((element) => {
      const str = $(element).html()
      const styles = cheerio.load(String(str))('style')
      globalStyles += styles
        .toArray()
        .map((el) => $(el).html())
        .join(' ')
    })
  }
  return globalStyles
}

```

From here, you will run `extractABTestStyles` within the MyDocument component to pull all styles, and then set them inside the `body` using

`<style dangerouslySetInnerHTML={{ __html: this.props.globalStyles }}></style>`

```auto
class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const originalRenderPage = ctx.renderPage

    let globalStyles = ''
    ctx.renderPage = async (options) => {
      const render = await originalRenderPage(options)
      globalStyles = extractABTestingStyles(render.html)
      return render
    }
    const initialProps = await Document.getInitialProps(ctx)
    return {
      ...initialProps,
      globalStyles,
    }
  }
  render() {
    return (
      <Html>
        <Head />
        <body>
          <style
            dangerouslySetInnerHTML={{
              __html: this.props.globalStyles,
            }}
          ></style>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

```

And that should do it. You can see an example of how we have achieved the same in our [Next.js/Shopify starter](https://github.com/BuilderIO/nextjs-shopify/blob/master/pages/_document.tsx) using the technique outlined above.

---

<div class="post-metadata">

**Author:** ![mike.lambert](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.builder.io/mike.lambert/32/2282_2.png) [@mike.lambert](https://forum.builder.io/u/mike.lambert)\
**Post date:** [January 15, 2023, 12:42am UTC](https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197/2 "2023-01-15T00:42:11Z")

</div>

Thanks so much for this suggestion. It has been working great for us.

Unfortunately though, while upgrading to NextJS v13, this solution stopped working. I suspect that it has something to do with [comment that the NextJS documentation has](https://nextjs.org/docs/advanced-features/custom-document#customizing-renderpage) about customization of getInitialProps and renderPage not being supported by React 18.

Any ideas for a new solution that will work with Next 13 / React 18?

---

<div class="post-metadata">

**Author:** ![manish-sharma](https://avatars.discourse-cdn.com/v4/letter/m/8797f3/32.png) [@manish-sharma](https://forum.builder.io/u/manish-sharma)\
**Post date:** [January 16, 2023, 3:19pm UTC](https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197/3 "2023-01-16T15:19:21Z")

</div>

Hi @mike.lambert,

Could you please tell us the error you are getting in the browser console when using Next 13 / React 18?

---

<div class="post-metadata">

**Author:** ![mike.lambert](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.builder.io/mike.lambert/32/2282_2.png) [@mike.lambert](https://forum.builder.io/u/mike.lambert)\
**Post date:** [January 16, 2023, 4:53pm UTC](https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197/4 "2023-01-16T16:53:12Z")

</div>

Hi Manish,  
I’m not getting a particular error in the console and the issue only rears its head in our production builds in which most console errors are suppressed.

`getPersonalizedURL` was not working initially due to the issue described [here](https://github.com/BuilderIO/builder/issues/1679).

Once past this, we have found that pages with AB tests have a flashing of unstyled content. This was the same behavior that we had prior to implementing the suggestion to hoist the styles using a custom document. We were getting hydration errors in when running in dev mode initially, but those have been fixed and this styling issue still persists.

I’m not sure if it’s related, but when there is a flashing of content without any styling, all of these script tags get appended to the body.

![Screenshot of elements tab from dev tools](https://us1.discourse-cdn.com/flex020/uploads/builder/original/2X/0/0c75343063220edfe5b9b4e616d29d53fc67c920.png)

We are using the following dependencies:  
`next` - 13.1.1  
`react`- 18.2.0  
`@emotion/react` - 11.10.5  
`@builder.io/react` - 2.0.12  
`cheerio` - 1.0.0-rc.12

---

<div class="post-metadata">

**Author:** ![manish-sharma](https://avatars.discourse-cdn.com/v4/letter/m/8797f3/32.png) [@manish-sharma](https://forum.builder.io/u/manish-sharma)\
**Post date:** [January 24, 2023, 3:18pm UTC](https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197/5 "2023-01-24T15:18:43Z")

</div>

Hi @mike.lambert,

Possibly this could be an issue related to [Monitor Next.js 13 Layout integration with Emotion + MUI · Issue #21 · accelist/nextjs-starter · GitHub](https://github.com/accelist/nextjs-starter/issues/21) and may not be resolved until this is fixed.

Could you still confirm how you are using next13 with emotion?

---

<div class="post-metadata">

**Author:** ![mike.lambert](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.builder.io/mike.lambert/32/2282_2.png) [@mike.lambert](https://forum.builder.io/u/mike.lambert)\
**Post date:** [February 14, 2023, 11:19pm UTC](https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197/6 "2023-02-14T23:19:05Z")

</div>

My apologies for the delay in getting back to you @manish-sharma ! Darn those vacations… 😉

When attempting to upgrade, we were continuing to use the `pages` directory and had not yet moved to the `app` directory because it’s still experimental. We’re not yet attempting to use `layout.tsx` files like described in this issue.

---

<div class="post-metadata">

**Author:** ![manish-sharma](https://avatars.discourse-cdn.com/v4/letter/m/8797f3/32.png) [@manish-sharma](https://forum.builder.io/u/manish-sharma)\
**Post date:** [February 15, 2023, 2:14pm UTC](https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197/7 "2023-02-15T14:14:54Z")

</div>

Hi @mike.lambert,

Could you tell if this flashing of unstyled content is only with text or if the entire content is flashing?

This could be due to nextJS recent changes [Flash Of Unstyled Text (FOUT) on reload using next.js and styled components](https://stackoverflow.com/questions/60841540/flash-of-unstyled-text-fout-on-reload-using-next-js-and-styled-components)

---

<div class="post-metadata">

**Author:** ![mike.lambert](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.builder.io/mike.lambert/32/2282_2.png) [@mike.lambert](https://forum.builder.io/u/mike.lambert)\
**Post date:** [February 15, 2023, 3:26pm UTC](https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197/8 "2023-02-15T15:26:14Z")

</div>

Hi @manish-sharma,  
All of the content flashes without any CSS applied for a moment. It’s the same as flash that we observed in NextJS v12 prior to implementing the solution that @TimG originally suggested in this post.

---

<div class="post-metadata">

**Author:** ![manish-sharma](https://avatars.discourse-cdn.com/v4/letter/m/8797f3/32.png) [@manish-sharma](https://forum.builder.io/u/manish-sharma)\
**Post date:** [February 21, 2023, 4:32pm UTC](https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197/9 "2023-02-21T16:32:03Z")

</div>

Hi @mike.lambert,

Would you be able to share the code reproduction, which would help us speed up the process to find a new solution?

---

<div class="post-metadata">

**Author:** ![mike.lambert](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.builder.io/mike.lambert/32/2282_2.png) [@mike.lambert](https://forum.builder.io/u/mike.lambert)\
**Post date:** [April 11, 2023, 4:40pm UTC](https://forum.builder.io/t/a-b-test-variations-styling-doesn-t-often-look-right-using-emotion-css-styling-with-next-js/1197/10 "2023-04-11T16:40:49Z")

</div>

Sorry for the delay on this again. I see that y’all have been working on v2 of the the `@builder.io/react` package, which is for React v18 and am guessing that that will fix the issue. I’ll let you know if the problem persists after the upgrade.
