React Helmet Not Updating Meta Tags
Solution 1:
For an SPA without SSR (server side rendering), from a bot's point of view, your head tags are in your static index.html file in your dist/public folder. To add the ability to serve dynamic elements from head tag to bots you can:
- Use a pre-render service
- Alternatively use next.js to render your pages (or parts of the page) on the server so bots can crawl this
- Look into other solutions for SSR
You may read - https://github.com/nfl/react-helmet/issues/489
An approach that worked for me:
Direct your traffic to a node server
From this node server return your index.html file and also pass head tags.
return res.render('index', { headTags: ReactDOMServer.renderToStaticMarkup(tags), })
Here, tags is an array of HTML elements like <meta/>, <title/>
etc.
Bonus: You can import the same tags module on frontend to get the head tags for Helmet.
In your index.html you can use handlebars to read the head tags that are passed from node server and print the head tags in head section.
<head> {{{ headTags }}} ... </head>
and to use handlebar as an engine, add this to your node sever
app.engine('html', handlebars.engine);
Solution 2:
I faced the same issue. And solved it as below.
In your server file (say server/index.js), add const helmet = Helmet.renderStatic() after ReactDOMServer.renderToString. My code looks like:
const app = ReactDOMServer.renderToString(<App />);
const helmet = Helmet.renderStatic()
const indexFile = path.resolve('./build/index.html');
fs.readFile(indexFile, 'utf8', (err, data) => {
let updated = data.replace('<div id="root"></div>', `<div id="root">${app}</div>`);
return res.send(updateHtmlContent(updated, helmet));
}
and add the following function. This is to update html content with helmet tags.
function updateHtmlContent(app, helmet) {
return `
<!DOCTYPE html><htmllang="en"><head>
${helmet.title.toString()}
${helmet.meta.toString()}
</head><body><divid="root">
${app}
</div></body></html>
`
}
This may help you :)
Post a Comment for "React Helmet Not Updating Meta Tags"