Dynamic Meta Tags with next.js, React and Contentful
By Alex R.

Dynamic Meta Tags that actually work with Facebook, Twitter and Linkedin

When looking for a new stack for our corporate website, we had a few priorities.

  • A Headless CMS for easy addition of Blog Posts, Press Releases, etc.

  • Easy to develop and add new features

  • Server-side rendering for SEO

  • Dynamic Meta Tags that actually work (and not just for the google crawler).

After a few experiments with Angular Universal (though we're fans of Angular 2 it was quite frankly overkill for a mostly static website), we settled on React with next.js for server side rendering, and Contentful for our Headless CMS.

The dynamic meta tags are implemented like this. Each page in next.js is a React component which wraps the Head component from next:

import Head from 'next/head';

Then we have some bindings for the meta tags like so:

// In your gatsby-config.js
plugins: [
    resolve: `gatsby-transformer-remark`,
    options: {
      plugins: [

And so on. The Contentful magic happens using the getInitialProps lifecycle hook, which grabs the item id from the URL (i.e. /blog/id):

static async getInitialProps({query}){
  // Set up contentful SDK
  // Fetch contentful stuff for that specific blog post
  const response = await contentfulClient.getEntries({'sys.id':query.id});

  return {
    post: response.items[0]

When the webserver renders a blog post, the async/await grabs the post from Contentful and attaches it to __this.props__. The render function then uses the initial value to set the meta tags in the Head block.

The beauty of this system is that the sky is the limit when it comes to extensibility. For instance, we incorporated the Marked library to parse markdown from Contentful into what you see on this blog post.

Contentful even allows you to link pieces of content to other pieces - in this case we can link a post with an author, and the Contentful SDK automatically grabs the associated items and media urls.

We're very happy with the stack so far and I would definitely suggest trying it out for any similar use cases. It hits the sweet spot between something like the lightweight Gatsby library and a fully monolithic framework.

One thing's for sure - I will never use wordpress again.