question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

pass data from server.js to client side component

See original GitHub issue

Hello, I am trying to pass some data to client side components from the server. My current approach is, when registering server side middleware I try to pass additional data to the context.

const context = {
  insertCss: styles => css.push(styles._getCss()),
  onSetTitle: value => (data.title = value),
  onSetMeta: (key, value) => (data[key] = value),
  onPageNotFound: () => (statusCode = 404),
  serverData: resp,
};

when I log during render on the server side the data is there. but when the client kicks in, my guess is that it is being overwritten.

Same happens inside the routes.js:

on('*', async (state, next) => {
  const component = await next();
    return component && <App path={state.path} context={state.context}>{component}</App>;
});

Server side state.context.serverData is there, but on the client side it is undefined. I kinda need to use res.redirect before the header is set, so fetch will not really work for me in this situation.

Here is a full example of what I am trying to achieve:

//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
  const respond = (authorized, resp) => {
    try {
      let statusCode = 200;
      const template = require('./views/index.jade');
      const data = { title: '', description: '', css: '', body: '', entry: assets.main.js };

      if (process.env.NODE_ENV === 'production') {
        data.trackingId = analytics.google.trackingId;
      }

      const css = [];
      const context = {
        insertCss: styles => css.push(styles._getCss()),
        onSetTitle: value => (data.title = value),
        onSetMeta: (key, value) => (data[key] = value),
        onPageNotFound: () => (statusCode = 404),
        serverData: resp,
      };

      /* await */ Router.dispatch({path: req.path, query: req.query, context }, (state, component) => {
        data.body = ReactDOM.renderToString(component);
        data.css = css.join('');
      });

      res.status(statusCode);
      (authorized == true ? res.send(template(data)) : res.redirect('/login'));
    } catch (err) {
      next(err);
    }
  }
  if(req.path !== '/login'){
    validateSession(req.session, (resp) => {
      respond(true, resp);
    }, () => {
      respond(false);
    });
  } else {
    respond(true);
  }

});

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:8 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
koistyacommented, Mar 30, 2016

One solution is to update the “shell” HTML template to include something like this:

<script>window.appData = {{appData}};</script>

Then update server.js to pass the initial application’s state to that template:

data.appData = JSON.stringify({ foo: 123 });

Then update client.js to pass data from that window.appData variable, to React app via context.

1reaction
frenzzycommented, Oct 5, 2017

@joenot443 yes, it is ok. But do not forget about XSS protection, for example: https://github.com/kriasoft/react-starter-kit/pull/883 uses serialize-javascript for that.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Pass data to client-side JavaScript (preferably without view ...
Part I: Problem introduction. The short story: I need to pass data from the server to the client, but this data will not...
Read more >
Fetching data from the server - Learn web development | MDN
This article shows how to start working with Fetch to fetch data from the server.
Read more >
How to Pass New Server Data to react.js Components
This guide will show how to pass new server data to your components and make a web app more interactive using realtime data....
Read more >
Client-side data fetching
Learn about client-side data fetching, and how to use SWR, a data fetching React hook library that handles caching, revalidation, focus tracking, ...
Read more >
Server-Side Rendering (SSR)
Vue.js is a framework for building client-side applications. By default, Vue components produce and manipulate DOM in the browser as output.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found