Blog>
Snippets

Enhanced SEO with Route-specific Meta Tags

Demonstrate how to manipulate meta tags dynamically for each route change to improve SEO with a route interceptor.
// Function to update meta tags
document.head = document.head || document.getElementsByTagName('head')[0];

function setMetaTags(title, description, keywords) {
  const titleTag = document.querySelector('title') || document.createElement('title');
  const metaDescription = document.querySelector('meta[name="description"]') || document.createElement('meta');
  const metaKeywords = document.querySelector('meta[name="keywords"]') || document.createElement('meta');

  titleTag.textContent = title;
  metaDescription.setAttribute('name', 'description');
  metaDescription.setAttribute('content', description);
  metaKeywords.setAttribute('name', 'keywords');
  metaKeywords.setAttribute('content', keywords);

  document.head.appendChild(titleTag);
  document.head.appendChild(metaDescription);
  document.head.appendChild(metaKeywords);
}
This function 'setMetaTags' allows setting or updating the `<title>`, `<meta name="description">`, and `<meta name="keywords">` tags within the document head. It appends the elements if they do not exist or updates them if they do.
// Example usage of `setMetaTags` for a specific route
function updateMetaForRoute(route) {
  switch (route) {
    case '/home':
      setMetaTags('Home Page', 'Welcome to our homepage.', 'home, welcome');
      break;
    case '/about':
      setMetaTags('About Us', 'Learn more about us.', 'about, info, company');
      break;
    // Add more cases for other routes
    default:
      setMetaTags('Default Title', 'Default description.', 'default, placeholder');
  }
}
This function 'updateMetaForRoute' decides what meta information to set based on the current route. The 'case' statements should be expanded to include all routes for which specific meta tags are needed.
// Route change interceptor
// This should be adapted to the routing library being used, e.g., React Router, Vue Router, react-router-dom, etc.

window.addEventListener('popstate', function (event) {
  // Assume `getCurrentRoute()` is a function that provides the current route
  const currentRoute = getCurrentRoute();
  updateMetaForRoute(currentRoute);
});
This event listener is an example of a route change interceptor using the browser's 'popstate' event. It should be adapted to your specific routing library to react on route changes. It calls 'updateMetaForRoute' with the current route whenever the history state changes.