Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 664
Félix Sanz Avatar asked Apr 08 '16 09:04

Félix Sanz


People also ask

How do you add meta TItle and description in react JS?

You can use react-meta-tags. It allows you to write title and other meta tags in a declarative way and in normal jsx format, which will be moved to head (Check server usage on the doc). You may also like to check react-helmet if you have an advanced use case. Show activity on this post.


1 Answers

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.

like image 164
Cameron Avatar answered Oct 14 '22 10:10

Cameron