@asphalt-react/ssr

1.17.0 • Public • Published

⚠️ Styles for Asphalt React components are absent on the client on initial request and are loaded when script executes which may cause FOUC or Flash Of Unstyled Content for some users. This package is designed to add styles for components and solve FOUC.

Asphalt React SSR

Provides a wrapper React component called SSR and a function called extractCSS to add styles when server rendering asphalt-react components.

  • <SSR> (default): Wrap your App with SSR component for server side rendering to work.

Only wrapped subtree is considered for styling

Following is a pseudocode of a hypothetical client implementation

app.js

import Button from "@asphalt-react/button"
import SSR from "@asphalt-react/ssr"

const App = () => (
  <SSR>
    <Button>Click Me</Button>
  </SSR>
)

export default App
  • extractCSS(): Wrap SSR with extractCSS function on server side implementation. Function extractCSS returns the following:
const { html,css,id } = extractCSS(...)
  • html: html of all wrapped components
  • css: combined css as string of asphalt-react components
  • id: string to uniquely identify style node.

Inject the css to the html on the server and apply the id to the style node.

When the script runs on the browser, <style> tag with above id is removed from the document.

Following is a pseudocode of a hypothetical server implementation

server.js

const ReactDOMServer = require("react-dom/server")
const React = require("react")

const App = require("./app.js").default
const { extractCSS } = require("@asphalt-react/asphalt-ssr")

const { html,css,id } = extractCSS(ReactDOMServer.renderToString(React.createElement(App)))

const serverHtml = `<!DOCTYPE html>
  <html lang="en">
    <head>
      <title>My page</title>
      <style id=`${id}`>${css}</style>
      <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
    </head>
    <body>
      <div id="root">${html}</div>
    </body>
  </html>
`

Certain changes may be required to the above code according to implementation.

Installation

# yarn
$ yarn add @asphalt-react/ssr

# npm
$ npm install @asphalt-react/ssr

Local Development

How it works ?

Uses StyleContext from @asphalt-react/context for communication between server side and client side. Components receive a function as context's value and pass the respective stylesheet to the function in server environment. A dock then collects, de-duplicates and ships the styles. extractCSS returns final styles which are injected to server html.

How to build?

This package is built using @asphalt-react/build using a custom rollup.config.js.

# yarn
$ yarn rollup -c

# npx
$ npx rollup -c

Readme

Keywords

Package Sidebar

Install

npm i @asphalt-react/ssr

Weekly Downloads

2

Version

1.17.0

License

UNLICENSED

Unpacked Size

7.69 kB

Total Files

4

Last publish

Collaborators

  • shripriya.bhat
  • dawn29
  • itsjay26
  • sayantan1211
  • abhinav.preetu