Dynamic page title and description with Vue Router
Tags: vue, typescript, javascript, tutorial
Published: 2024-04-29 10:05:24


I recently wanted to improve user experience related to meta of visiting page of one of our projects at Alokai -> Console. I thought that it would have been useful to display dynamic page title and description based on the page that the user currently is.

So, the idea was to modify the existing Vue Router and routes so that they will contain metadata about title and descriptions of each routes in our application and then register a plugin/middleware that would change the existing title and description (default one declared in the `index.html` file) into a custom one that would be more user friendly.

![Page Title](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ngi09spg8yj2jbvsfb4g.png)

I tried to search for information how such feature could be implemented but couldn't find the information easy, I decided to write an article about it so that it would be easier for you in the future :)

Enjoy!

## 🤔 What is a Vue Router?

VueRouter is a expressive, configurable and convenient routing for Vue.js.

![Vue Router](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cx3lxy9gd90c7hw4ntbb.png)

* 🛣 Expressive route syntax - Define static and dynamic routes with an intuitive and powerful syntax.

* 🛑 Fine-grained Navigation control - Intercept any navigation and precisely control its outcome.

* 🧱 Component-based configuration - Map each route to the component that should display.

* 🔌 History modes - Choose between HTML5, Hash or Memory history modes.

* 🎚 Scroll control - Precisely control the scroll position in every page.

* 🌐 Automatic Encoding - Directly use unicode characters (你好) in your code.

If you would like to learn more about the basic usage of Vue Router, check out the official documentation [here](https://router.vuejs.org/).

## 🟢 Dynamic page title and description with Vue Router

To create the custom page title and description with the usage of Vue Router, there are few things that we need to do.

Let's take a look at the following `routes` declaration:

```ts
export const routes = [{
  name: 'MyCustomRoute',
  path: 'my-custom-path',
  meta: {
    title: 'Amazing Title',
    description: 'Awesome Description',
  }
}];
```

It is a very simple route with the `name` and the `path`, but we also pass a `meta` object with both `title` and `description`. We will use these meta properties later on in the router configuration.

Now, let's take a look at the router itself.

```ts
const router: Router = createRouter({
  routes,
  // other router configuration options
});
```

At this point, we only register our routes in the router but magic will come in the `beforeEach` method of the router. This method adds a navigation guard that executes before any navigation and you can read more about it [here](https://router.vuejs.org/api/interfaces/Router.html#beforeEach)

```ts
router.beforeEach((to) => {
  const { title, description } = to.meta;
  const defaultTitle = 'Default Title';
  const defaultDescription = 'Default Description';

  document.title = title || defaultTitle

  const descriptionElement = document.querySelector('head meta[name="description"]')
  
  descriptionElement.setAttribute('content', description || defaultDescription)
})
```

There is quite a lot of things that are going on here, so let's explain each individually:

1. Destructure the `to.meta` object to get both `title` and `description` properties.
2. We set a value of `document.title` to either the custom title or the default title if this custom title wasn't configured.
3. If the description was passed as a meta, we set it to a custom one by using the `setAttribute` method.

And that's it! With this navigation guard, we will be modifying dynamically both the `title` and the `description` of the website based on the router configuration.

Just keep in mind that this title and description won't be seen in the links or raw HTML of your website if you are using a classic SPA application because the Vue (and JS) are executed after the page load. If you would like to achieve that, you would need to convert your application into one of the following:

1. Multi Page Application (MPA)
2. Server Side Rendering Application (SSR)
3. Static Site Generation Application (SSG)

## 📖 Learn more 

If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this [link](https://vueschool.io/courses?friend=baroshem) or by clicking the image below:

[![Vue School Link](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i662jpyni4zs2dlaeud1.png)](https://vueschool.io/courses?friend=baroshem)

It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉

## ✅ Summary

Well done! You have just learned how to use Tailwind plugins to create custom classes. 

Take care and see you next time!

And happy coding as always 🖥️