Dynamic Metadata in NextJS

Understand how to include dynamic metadata in NextJS

Introduction

If you have ever wondered how you can introduce dynamic metadata into your projects using NextJS, then this article is exactly what you’ve been looking for!

The same principle will work with any NextJS project that consumes data from a CMS.

Getting Started

The first thing I did approached trying to do this was to ensure that I had the correct setup in my Layout component.

This is the component that wraps all of the content within the pages of this site and uses the Head component of NextJS to allow for the passing of different values for the metadata e.g. title, description and keywords which are the main three used.

![Layout!](res.cloudinary.com/xenos-design/image/uploa.. 'Layout')

Although it is not essential, it is a good idea to add default props layout values for the metadata that you want to cover. This is shown at the bottom of the screen.

Following that, I updated the [slug] page, which is the page that displays an individual article when you click on the card, specifically where you can see that I find it in the title, description and keywords and pointed the value to 3 unique fields within the post content that is being extracted from the Strapi CMS.

![Layout!](res.cloudinary.com/xenos-design/image/uploa.. 'stuff')

This allows me to pass in the values that I want, which are stored within each individual article record in the database.

By doing this you can create unique titles for each of your articles, which allows your audience to save them with meaningful titles without having to type something in.

You can also add in whatever page description and keywords they want, therefore making each individual article more usable to search engines.

Once this was done all I needed to was to create the three fields within the article record structure in Strapi CMS (metaTitle, metaDesc and metaKey). The name of the fields does not really matter, as long as it is meaningful to you and to whoever you may be getting to support implementation going forwards.

Results

At this stage, you are in a position to test your code works as expected. I recommend using the Chrome dev tools. If you implement this correctly you should see the following:

![Results!](res.cloudinary.com/xenos-design/image/uploa.. 'Results')

and

![Results!](res.cloudinary.com/xenos-design/image/uploa.. 'Results')

as you will see each of my articles on this site have their own unique titles and metadata.

I hope you found this useful and gives you some inspiration to implement into your own projects. If you get stuck and need some advice for free contact me via email or Twitter.