How to manage title, meta tags, etc, inside React with server rendering + streaming?
Asked Answered
A

1

14

There are some libraries that manage <head> tags, like:

react-helmet

react-document-title

react-doc-meta

But all these libraries share the same API on the server rendering: Rewind.

You first generate the component tree using renderToString() and then you call library.rewind() to get the <head> data.

The problem comes when you use react-dom-stream to stream the component tree instead of rendering them as a string. You can't rewind because the stream is not consumed yet, and when it is, it's too late.

What approach should be implemented here?

Autotoxin answered 8/4, 2016 at 9:2 Comment(1)
I would highly, highly recommend checking out Nextjs. It takes care of routing, server side rendering, as well as manipulating the <head> tags.Vestryman
A
1

Unfortunately, the general requirements for having meta tags correctly rendered means that you will first have to have your primary content handy in order to correctly identify what the contents of each meta tag will be. This issue you are seeing is not strictly related to React, but more so in the fact that you have to trade-off between performance and content tagging accuracy.

A primitive solution would involve things like string replacements upon the blob of HTML as a post-processor before being sent to the client (browser in this case), but that will essentially remove the performance gain given to you from a streamed page.

Otherwise, you would need to implement a way to retrieve the basic primary content up front and generate the metatags outside of the streamed response, or before it - so you would make some compromises there.

Another solution is to render to a string, realize the full power of metatag modifications, and then utilize some caching layer like Varnish or simply a key-value store of each page in Redis or Memcached.

Aptitude answered 23/1, 2017 at 20:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.