This article will show you how you can take care of dynamic SEO of your single page application for different routes whether its React, Vue, Angular or any other SPA for that matter.
The issue is quite straight forward. You have a Single Page Application and you want your website to display relevant information like a thumbnail image, some title and some description, when you share some link on any other website like Facebook, LinkedIn, Twitter, Slack. e.g. ‘https://tv-maze.netlify.app/tvshow/1’, where 1 is the tv show id that is dynamic.
But the problem is you serve a single ‘index.html’ file to the client that loads your entire SPA with static meta tags. So how do we fetch the relevant info based on the tv show id and populate them in meta tags so it can display the relevant info when some website crawler tries to gather some important data?
One of the things that you require is a back-end server that can serve your static files. For this article I have used Node hosted on Heroku, using TVmaze API. But you can use any back-end server or API by using the same steps that I’m about to share.
- First you build your SPA which will consist of .js and .css files along with a single ‘index.html’ file and store it in a place where your back-end server has access to.
- Secondly you choose a route from your front-end app that you want the SEO done for. In this article it’s ‘/tvshow/:id’ where :id is dynamic.
- Then you tell your back-end server to intercept that route (‘/tvshow/:id’) and see from the User-Agent of the request headers, if the request came from a browser or a crawler. For this differentiation I decided to use isbot, like so: isbot(‘user_agent_string’).
- If the request seems to have come from a browser, then you simply return the path to the ‘index.html’ file of your SPA.
- If the request seems to have come from a crawler, then you fetch info based on the tv show id, from the API, populate them in your meta tags and return it as string in your back-end response.
Below is an image of what I tried to explain:
That’s it! you can check a live example of this here.
It’s important to note that there are two front-end examples that I have shared in this article.
The first one doesn’t consist of any back-end code. Just some static SPA built files hosted on Netlify. The second one serves those static SPA files through a node.js server, allowing you to program some intermediary code, which in our case is responsible for dealing with SEO before serving those files over to the client. Feel free to share both these links on your social media like Facebook, Twitter or Slack and you will see that the Netlify one doesn’t display any relevant info for the tv show.
GitHub link to the projects: