Adding Meta Tags to Next.js With Headless WordPress.

Working with the WordPress REST API can be both fun and annoying. Having data and code separated just feels right. However, there are some catches. Adding basic things like meta-tags for example is not as straight forward as I thought. But let`s do it anyway, it`s fun they said!

The “Problem”

Working with the NEXT.JS WordPress example you get the following response from post.tags.edges:

So, we have an array with objects, Wohoo! The problem is that we can`t loop straight trough them. since “return” tells React to return your component.

The Sollution

The solution is simple. Create an empty array like this:

const tagItems = []

Then loop trough post.tags.edges and push them to your empty array.

tagArray = post.tags.edges;

let i;
for(i = 0; i < tagArray.length; i++ ) {
   tagItems.push(tagArray[i].node.name)
}

The Meta tag

Next, you have to import Head from next/head like this:

import Head from 'next/head'

Then add your meta inside of <Head> like this:

<Head>
   <title>
      {post.title}
   </title>
   <meta name="keywords"
         content={tagItems}
   />
</Head>

And we`re done! There are other and maybe better ways of doing this.
See more here: https://flaviocopes.com/react-how-to-loop/

Other posts:

Hide Folders and Files With Robots.txt

3 simple CSS hacks