pshrmn / curi

A JavaScript router for single-page applications
https://curi.js.org
MIT License
268 stars 10 forks source link

Pass server side response to client side router on creation #225

Closed faergeek closed 4 years ago

faergeek commented 5 years ago

First of all, great router, I really like how it works 👍

But It seems like there's no way to pass response data from server to client, which is a bit sad :-( May be we could improve this. I'm more than happy to send a PR after some discussion.

So what I'm doing right now:

Everything is good.

But what happens when I render my app on server?

So it would be cool to have some way of passing that response from server to client. Aka "initial response". Not sure how that should work with regard to things which actually need to be resolved on client separately like route components or other things which can't be serialized. May be I am missing something? Do you have any ideas on how that could be implemented?

pshrmn commented 5 years ago

What about setting the data in the HTML markup, like Redux?

https://redux.js.org/recipes/server-rendering#inject-initial-component-html-and-state

You could then have your resolve function check if the initial data exists and only fire off a request if it doesn't. The code below is pretty generic, but hopefully paints a clear picture.

I think that there are strategies for including components in the server rendered markup, but I think that including that isn't really worth the hassle.

function renderHandler(req, res) {
  const router = createRouter(reusable, routes, {
    history: { location: req.url }
  });
  router.once(({ response }) => {
    const Router = createRouterComponent(router);
    const markup = renderToString(
      <Router>
        <App />
      </Router>
    );
    const html = insertMarkup(markup, response);
    res.send(html);
  });
}

function insertMarkup(markup, response) {
  return `<!doctype html>
<html>
  <body>
    <div id="root">${markup}</div>
    <script src="/static/js/bundle.js"></script>
    <script>
      window.__INITIAL_DATA__ = ${JSON.stringify(response.data)};
    </script>
  </body>
</html>`;
}
faergeek commented 5 years ago

Yes, I thought of something like that. For example, I could inject initialData into external, then make some wrapper for resolvers which would check if data is already there, return it and then reset for subsequent transitions on client, so that other routes do not return other routes' data. I just hoped that it's possible to solve this problem at library level somehow. Not sure how though. Anyway, this probably needs to be added to server side rendering guide as a recipe. What do you think? I would try to write it once I figure out what to do myself))

pshrmn commented 5 years ago

It would definitely be helpful to have this laid out for others.

I think that I would personally set up a local API that initializes itself with the data set by the server and caches new data after API results. I believe that data stores like Apollo will actually do this for you (if you've jumped on the GraphQL train), but you can also roll your own.

// api.js
const data = window.__INITIAL_DATA__
  ? window.__INITIAL_DATA__
  : {
      products: []
    };

const api = {
  product(id) {
    const cached = data.products.find(p => p.id === id);
    if (cached) {
      return Promise.resolve(cached);
    } else {
      return fetch(`/api/product/${id}`)
        .then(response => response.json())
        .then(result => {
          // cache result
          data.products.push(result);
          return result;
        });
    }
  }
}

export default api;
// routes.js
import api from "./api";

export default prepareRoutes([
  // ...
  {
    name: "Product",
    path: "product/:id",
    resolve({ params }) {
      return api.product(params.id);
    }
]);