How to add dynamic meta tags to a React app

Anjula Shanaka
Nerd For Tech
Published in
3 min readAug 11, 2020

Adding meta tags is easy right? Yeah, but not for React apps. Making your site SEO friendly is one of the major things that everyone cares about. One of the challenges of deploying an app built with create-react-app is that it is rendered entirely client-side. Although Google can render JavaScript content when crawling a site, it doesn’t always, and there is always the risk that your JavaScript bundle will fail anyway. So how to get over this? You’ll know the answer by the end of this.

As always let me start with why had to do this. My task was to build a React website to showcase this some awesome AI at work. So to make this React app SEO-friendly I needed to add meta tags for each page.

I started my research and found these two libraries which will help me to achieve this.

1. React Snapshot

This gives static pre-renderer for React apps. React Snapshot takes a static site snapshot of all your publicly-accessible pages & leaving anything requiring authentication as a normal. These snapshots still have the normal JS bundle included, so once that downloads the site it will function exactly as before (i.e. instantaneous page transitions), but serve you real, functional HTML & CSS as soon as possible. All you have to do is add this to your index.js and update your package.json file with build”: “react-scripts build && react-snapshot” .

If you run npm run build you’ll see it will detect your react-routes and create a static HTML page for each route inside your build directory.

2. React Helmet

This reusable React component will manage all of your changes to the document head. Helmet takes plain HTML tags and outputs plain HTML tags. With React helmet we can embed meta tags, title, link, script to components.

Using React Helmet is super easy. Here’s an example code snippet,

Once you used these two libraries it will do the rest of things for you. Snapshot will do the static Pretty cool right? No need to worry about anything else. If you use this Facebook sharing debugger tool you can easily test how your meta tags are doing.

I hope this gives you a small idea on how to achieve this. Thanks for reading!

--

--

Anjula Shanaka
Nerd For Tech

GSoC ’22 @openMRS | CTO @SEF | Developer @promiseQ | Undergraduate @USJ