npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-relay-network-modern-ssr

v1.4.0

Published

Server side rendering middleware for react-relay-network-modern

Downloads

10,961

Readme

SSR middleware for react-relay-network-modern (for Relay Modern)

npm Travis Commitizen friendly semantic-release FlowType compatible

For a full examples, see:

  • https://github.com/damassi/react-relay-network-modern-ssr-example
  • https://github.com/damassi/react-relay-network-modern-ssr-todomvc

Server

import express from 'express';
import ReactDOMServer from 'react-dom/server';
import { RelayNetworkLayer } from 'react-relay-network-modern';
import RelayServerSSR from 'react-relay-network-modern-ssr/lib/server';
import serialize from 'serialize-javascript';
import { Environment, Network, RecordSource, Store } from 'relay-runtime';
import schema from './schema';

const app = express();

app.get('/*', async (req, res, next) => {
  const relayServerSSR = new RelayServerSSR();

  const network = new RelayNetworkLayer([
    // There are three possible ways relayServerSSR.getMiddleware() can be used;
    // choose the one that best matches your context:

    // By default, if called without arguments it will use `fetch` under the hood
    // to request data. (See https://github.com/relay-tools/react-relay-network-modern
    // for more info)
    relayServerSSR.getMiddleware(),

    // OR, you can directly pass in a GraphQL schema, which will use `graphql`
    // from `graphql-js` to request data
    relayServerSSR.getMiddleware({
      schema,
      contextValue: {},
    }),

    // OR, if you need to prepare context in async mode, `getMiddleware` will also
    // accept a function:
    relayServerSSR.getMiddleware(async () => ({
      schema,
      contextValue: await prepareGraphQLContext(req),
    })),
  ]);
  const source = new RecordSource();
  const store = new Store(source);
  const relayEnvironment = new Environment({ network, store });

  // Once the RelayEnvironment is instantiated, two App renders need to be made in
  // order to prepare data for hydration:

  // First, kick off Relay requests with an initial render
  ReactDOMServer.renderToString(<App relayEnvironment={relayEnvironment} />);

  // Second, await while all data were recieved from graphql server
  const relayData = await relayServerSSR.getCache();

  // Third, render the app a second time now that the Relay store has been primed
  // and send HTML and bootstrap data to the client for rehydration.
  const appHtml = ReactDOMServer.renderToString(
    <App
      relayEnvironment={new Environment({
        network: Network.create(() => relayData[0][1]),
        store,
      })}
    />
  );

  try {
      res.status(200).send(`
      <html>
        <body>
          <div id="react-root">${appHtml}</div>
          <script>
            window.__RELAY_BOOTSTRAP_DATA__ = ${serialize(relayData)};
          </script>
          <script src="/assets/bundle.js"></script>
        </body>
      </html>
    `);
  } catch (error) {
    console.log('(server.js) Error: ', error);
    next(error);
  }
}

app.listen(3000);

// simple example, how to asynchronously prepare data for GraphQL context
async function prepareGraphQLContext(req) {
  const { userToken } = req.cookies;
  const user = userToken ? (await somehowLoadUser(userToken)) : undefined;
  return {
    user,
    req,
  }
}

Client

import { RelayNetworkLayer } from 'react-relay-network-modern';
import RelayClientSSR from 'react-relay-network-modern-ssr/lib/client';

const relayClientSSR = new RelayClientSSR(window.__RELAY_BOOTSTRAP_DATA__);

const network = new RelayNetworkLayer([
  relayClientSSR.getMiddleware({
    lookup: true // Will preserve cache rather than purge after mount.
  }),
]);

...

ReactDOM.render(
  <QueryRenderer
    dataFrom="STORE_THEN_NETWORK" // Required for Relay 1.5
    environment={environment}
    ...
  />,
  document.getElementById('react-root')
);

Contribute

I actively welcome pull requests with code and doc fixes.

CHANGELOG

License

MIT