Logo

Adding Schema.org Markup to Your Next.js Blog with Prismic: A User-Friendly Guide

Posted By

Hugo Carvalho

Published Date

2024-05-20

Read Time

6 min
random code image

random code image

Introduction

Boost your SEO and improve search engine visibility by adding Schema.org markup to your Next.js blog powered by Prismic. This guide provides a clear and concise walkthrough, making it easy to implement structured data for enhanced user experience and search engine optimization.

Why Use Schema.org Markup?

Schema.org markup provides search engines with a structured understanding of your content, helping them display richer and more informative search results. This can lead to:

  • Increased visibility: Your blog posts are more likely to appear in featured snippets and knowledge panels.
  • Improved click-through rates: Search results with rich snippets are more visually appealing and attract more clicks.
  • Enhanced user experience: Search engines can display relevant information directly in the search results, providing users with a better understanding of your content before clicking.

Prerequisites

  • Next.js application: You need a Next.js project to implement this guide.
  • Prismic CMS setup: Your blog content should be managed using Prismic.
  • Basic TypeScript knowledge: Familiarity with TypeScript is helpful but not mandatory.

Step 1: Define the SchemaData Type

Start by defining a TypeScript type to ensure type safety and consistency when working with your schema data. Create a file named schemaData.ts in your src/types directory:

// src/types/schemaData.ts
export type SchemaData = {
  "@context": string;
  "@type": string;
  headline: string | null;
  description: string | null;
  image: string | null;
  author: {
    "@type": string;
    name: string | null;
  };
  datePublished: string | null;
  dateModified: string | null;
  mainEntityOfPage: {
    "@type": string;
    "@id": string | null;
  };
};

Step 2: Fetch Data from Prismic

Update your blog post page component to fetch data from Prismic and generate the schema data based on the fetched content.

import { Metadata } from "next";
import { notFound } from "next/navigation";
import { SliceZone } from "@prismicio/react";
import { createClient } from "@/prismicio";
import { components } from "@/slices";
import { SchemaData } from "@/types/schemaData";

type Params = { uid: string };

export default async function Page({ params }: { params: Params }) {
  const client = createClient();
  const page = await client
    .getByUID("blog_post", params.uid)
    .catch(() => notFound());

  const schemaData: SchemaData = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: page.data.title || null,
    description: page.data.summary_content || null,
    image: page.data.featured_image.url || null,
    author: {
      "@type": "Person",
      name: page.data.author_name || null,
    },
    datePublished: page.data.publication_date || null,
    dateModified: page.data.last_modified_date || null,
    mainEntityOfPage: {
      "@type": "WebPage",
      "@id": params.uid || null,
    },
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaData) }}
      />
      <SliceZone slices={page.data.slices} components={components} />
    </>
  );
}

// ... (rest of the component code)

Step 3: Create a Utility Function for Safe JSON Serialization

To prevent potential hydration errors, create a utility function to safely serialize the JSON for the script tag. This ensures that special characters are correctly escaped.

// src/utils/jsonLD.ts
export function safeJSONLD(data: any): string {
  return JSON.stringify(data).replace(/<\/script>/g, '<\\/script>');
}

Step 4: Update the Page Component to Use the Utility Function

Update your page component to use the safeJSONLD function when rendering the JSON-LD script.

// ... (import safeJSONLD from "@/utils/jsonLD")

export default async function Page({ params }: { params: Params }) {
  // ... (rest of the component code)

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: safeJSONLD(schemaData) }}
      />
      <SliceZone slices={page.data.slices} components={components} />
    </>
  );
}

Step 5: Verify Your Data Structure

Ensure that the data returned from the Prismic API matches the SchemaData type, especially the fields used in the schema (title, summary_content, featured_image.url, author_name, publication_date, last_modified_date).

Step 6: Deploy and Test

Deploy your updated Next.js application and navigate to a blog post page. Use the browser's developer tools to inspect the rendered HTML and ensure the schema is correctly included as a JSON-LD script tag.

Step 7: Validate Your Structured Data

Use Google's Structured Data Testing Tool to validate your structured data and ensure everything is set up correctly. This tool will help you identify any errors or potential issues with your schema markup.

Conclusion

By following these steps, you've successfully added structured data to your Next.js blog posts using Prismic. This will help search engines better understand your content and improve your site's SEO. Remember to regularly validate your structured data to ensure its accuracy and effectiveness.

Additional Tips:

  • Use a schema validator: Tools like Google's Structured Data Testing Tool can help you identify and fix errors in your schema markup.
  • Test your implementation: Use the browser's developer tools to inspect the rendered HTML and ensure the schema is correctly included.
  • Monitor your results: Track your website's performance in search results to see the impact of adding structured data.

By implementing Schema.org markup, you can significantly improve your blog's visibility and user experience, leading to better SEO results and increased traffic.

We'd be interested in learning more about your project.