Skip to content

Server Side Rendering #124

Closed
Closed

Description

@geelen

Thought I'd open an issue to kick off the discussion. It's already possible because of the way we build on top of Glamor, but we haven't exposed it as an API. But basically, if you did this:

import styleSheet from 'styled-components/lib/models/StyleSheet'

/* before each render */
styleSheet.flush()

/* after each render */
styleSheet.rules().map(rule => rule.cssText).join('\n')

Then you should get the chunk of CSS you need for each request. Can someone with a server-rendered setup take a look and confirm this works, and maybe show how they'd be invoking it? I'd be happy enough to export something like:

import { serverStylesheet } from 'styled-components'

/* before each render */
serverStylesheet.reset()

/* after each render */
serverStylesheet.getCSS()

What do people think?

Activity

  1. pheuter commented on Oct 22, 2016

    @pheuter

    I'll gladly help test this out! We currently avoid using styled components for most styles because of the unclear path to support SSR, would be great to move the inline styles into styled components if we can generate the CSS on the server.

    Here is what I have setup so far:

    import styleSheet from 'styled-components/lib/models/StyleSheet';
    
    styleSheet.flush();
    
    let markup = renderToString(
      <Root store={store} Router={ServerRouter} routerProps={{ location, context }} />
    );
    
    console.log(styleSheet.rules());

    Unfortunately, I'm getting back an empty array []. I can confirm that one of the components nested inside Root is wrapped by styled and generates a className when the client loads.

  2. diegohaz commented on Oct 24, 2016

    @diegohaz
    Member

    I'm currently implementing SSR on a project and I managed to make this work without styleSheet.flush() (if I call this, the result is the same as @pheuter), only the styles from injectGlobal weren't included.

    Once I finish it I will post the complete code and a demo here. (I'm trying to make the app work completely without javascript enabled on client).

  3. mxstbr commented on Oct 24, 2016

    @mxstbr
    Member

    only the styles from injectGlobal weren't included.

    Huh, that's interesting. I think I might accidentally use another styleSheet for that? /cc @geelen

  4. diegohaz commented on Oct 24, 2016

    @diegohaz
    Member

    Demo: https://arc.diegohaz.com (disable javascript, even the form works).
    Code: https://github.com/diegohaz/arc/blob/universal-redux/src/server.js#L74

    It doesn't work with injectGlobal (I removed).

    The serverStylesheet.getCSS() API would be nice. 👍

  5. lucasavila00 commented on Oct 29, 2016

    @lucasavila00

    I noticed something.
    I'm using Grid from 'grid-styled' and using styleSheet.rules().map(rule => rule.cssText).join('\n') seems to go just one level deep. It never rendered code of Grid, but rendered my code that used media queries.

    code is like this:

    const Wrapper = styled(Grid)`
      position: fixed;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 40px;
      z-index: 0;
      top: 90px;
      z-index: 1;
      width: 100%;
      left: 0px;
      @media screen and (min-width: 52em){
        left: 16.66%;
      }
      @media screen and (min-width: 64em){
        left: 25%;
      }
    `
    

    Invoked as <Wrapper xs={1} sm={1} md={2/3} lg={1/2}>{children}</Wrapper>

    css gets rendered as

    .iMsaJZ { 
      position: fixed;
      display: -webkit-box;display:flex;display:-webkit-flex;display:-ms-flexbox;
      -webkit-box-pack: center;
      -ms-flex-pack: center;
      -moz-justify-content: center;
      -webkit-justify-content: center;
      justify-content: center;
      -webkit-box-align: center;
      -ms-flex-align: center;
      -webkit-align-items: center;
      align-items: center;
      height: 40px;
      z-index: 0;
      top: 90px;
      z-index: 1;
      width: 100%;
      left: 0px;
     }
    @media screen and (min-width: 52em){
      .iMsaJZ { 
        left: 16.66%;
      }
    }
    @media screen and (min-width: 64em){
      .iMsaJZ { 
        left: 25%;
      }
    }
    
    

    The element receives the correct classname on SSR (class="iMsaJZ hqknNf"), wich are two classes, one for my code(iMsaJZ) and one for Grid's(hqknNf).
    But there is no mention to the classname designed to Grid in the initial server response.
    When I turn JS on then Grid's code appears to the browser.

    .hqknNf { 
      -webkit-box-sizing: border-box; 
      box-sizing: border-box;
      display: inline-block;
      vertical-align: top;
      padding-left: 0px;
      padding-right: 0px;
      width: 100%;
      width: 100%;
     }
    @media screen and (min-width: 40em) {
      .hqknNf { 
        width: 100%;
      }
    }
    @media screen and (min-width: 52em) {
      .hqknNf { 
        width: 66.66666666666666%;
      }
    }
    @media screen and (min-width: 64em) {
      .hqknNf { 
        width: 50%;
      }
    }
    
    

    Inlining code solves the problem and ssr can be used but it breaks composition :(
    I hope I made myself clear :)

    Also to notice that while profiling on my dev pc (windows 10) I got 0 ~ 1ms latency calling styleSheet.rules().map(rule => rule.cssText).join('\n')
    That's nice!

  6. gbozee commented on Nov 2, 2016

    @gbozee

    Based on @pheuter test, I get the same result,(the class is injected in the string markup) but not calling stylesheet.flush() before calling styleSheet.rules() produces TypeError: Cannot read property 'cssRules' of undefined

  7. aesopwolf commented on Nov 3, 2016

    @aesopwolf

    Ah, this is so great. I was able to get it working with gatsby in no time

      render () {
        const styles = styleSheet.rules().map(rule => rule.cssText).join('\n');
    
        return (
          <html lang="en">
            <head>
              <style>
                {styles}
              </style>
            </head>
            <body>
              <div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} />
              <script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} />
            </body>
          </html>
        )
      }

    I'm all for exposing a simpler api via serverStylesheet.getCSS()

  8. kitten commented on Nov 9, 2016

    @kitten
    Member

    @gbozee I ran into that problem. Turns out when (f.e.) webpack 2 is used, it loads the es bundle, due to the package.json js:next/module fields.

    Until there is an API for the stylesheet that we can use, you should work around it using webpack's resolve.alias to load the lib folder instead.

  9. diegohaz commented on Nov 16, 2016

    @diegohaz
    Member

    I think I might accidentally use another styleSheet for that?

    @mxstbr I'm interested in solving this (injectGlobal). Can you give me a way?

  10. MoOx commented on Nov 17, 2016

    @MoOx

    Please get in touch when somebody start to handle this. I would like to get this to work out of the box in Phenomic (I just integrated Glamor and Aphrodite rendering and would like to cover all populars CSS in JS solutions).
    I was thinking glamor integration will be enough but @philpl just told me it won't work :(

  11. chiefjester commented on Nov 17, 2016

    @chiefjester
    Member

    @aesopwolf did you get the same problem as @diegohaz of not having styles included from injectGlobal calls?

    I think its a general consensus that this is working out of the box. The only minor caveat is styles from injectGlobal isn't included. But fixing that is trivial I guess?

  12. added a commit that references this issue on Nov 17, 2016
  13. 27 remaining items

  14. ItsBenCodes commented on Dec 30, 2016

    @ItsBenCodes

    @tomazy You can always remove your SSR style block once the client-side rendering is done. That way, your page will look great while the app is loading and you will not get duplicate styles.

    ReactDOM.render(<App />, document.getElementById('app'));
    document.getElementById('ssr-style').remove();
  15. codepunkt commented on Dec 30, 2016

    @codepunkt
    Member

    @exon yes, but styled-components could also just stop injecting it on the client-side again so you don't have to hack stuff like that together ;-)

    See #214 for more discussion about this.

  16. teonik commented on Dec 31, 2016

    @teonik

    @tomazy I used something similar to remove the server rendered critical-css block when react and styled-components kicked in on the client side.
    The problem with this approach is that it will also remove any styles you injected with injectGlobals,Those styles, if rendered on the server, will end up in the ssr block.
    It is also feels like a dirty hack compared to the rest of the experience offered by styled-components 😛

    Of course there are simpler ways to stick some global css in the pre-rendered page's head section but the point is that it would be nice to have proper support for it.

  17. added a commit that references this issue on Jan 10, 2017
    067f20d
  18. modified the milestone: v2.0 on Jan 17, 2017
  19. kristojorg commented on Jan 19, 2017

    @kristojorg
    Contributor

    PSA: I was seeing TypeError: Cannot read property 'cssRules' of undefined when using this line of code:

    const styles = styleSheet.rules().map(rule => rule.cssText).join('\n');

    The fix: If you are seeing this as well, make sure you are rendering at least one styled component in your app.

    For me, I was just installing styled-components for the first time, and hadn't used one yet, and was therefore seeing this error.

  20. kristojorg commented on Jan 20, 2017

    @kristojorg
    Contributor

    I have submitted a PR to fix this issue here. Hope this helps some!

  21. karthikiyengar commented on Mar 23, 2017

    @karthikiyengar

    I am trying to use hedron, but it seems the styles from it are not present. But my custom styles are rendered fine. Any ideas why this is happening/how to work around?

    @dignifiedquire - Could you please tell me how you worked around this? I'm having the exact same issue with hedron.
    @diegohaz - Using the universal-redux branch for this, is there anything that I should look into particularly?

  22. kristojorg commented on Mar 24, 2017

    @kristojorg
    Contributor

    @karthikiyengar Hedron is using styled-components which I believe means you need to import both your own server markup and theirs.

  23. karthikiyengar commented on Mar 24, 2017

    @karthikiyengar

    @kristojorg - Thanks for your answer.

    Please disregard, my vendor assets weren't being generated properly, leading to the issue.

  24. mxstbr commented on Apr 1, 2017

    @mxstbr
    Member

    This discussion has now been moved to #386.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions