We know react is single page application. ReactJs pushes the rendered data to the root element after data is prepared.
When we share a post on Facebook, Facebook searches for the og:image and og:url meta tag in the header section. When Facebook fetches the data from the shared URL it does not find the necessary meta tags because of ReactJs pushes the data to the root element after it prepares.We can solve this problem by NGINX or other any web server by appending og:image and og:url and other meta tags which we need to make available when a request comes to a server.
location ~ ^/product/(.*)/(.*) {
try_files $uri $uri/ /index.html;
}
In above (.)/(.) are the dynamic parameters of the product page. First dynamic parameter (.) will be accessed by $1 and the second dynamic parameter (.) will be accessed by $2.
location / {
sub_filter </head>
'<meta property="og:url" content="https://image-url/$2" />
<meta property="og:image" content="https://image-url/$2" />
<meta property="twitter:image" content="https://image-url/$2" />
<meta property="twitter:image:src" content="https://image-url/$2" />
</head>';
sub_filter_once on;
try_files $uri $uri/ /index.html;
}
You need to put the above two code blocks in your NGINX configuration file.
In the above, sub_filter will search for the </head> text and will replace with the following text ‘<meta property=”og:url” ….
Here we are assuming the dynamic name of the image in the second (.*) so we used $2 to get the image name of the shared post.
With the above two segments of the code block, you can get a nice image preview of your shared post on Facebook or other social media platform.
Note: For Facebook share you need to ensure image URL and shared post URL should be in the same domain otherwise Facebook may not be able to show image preview properly.