Implementing JSON-LD in Next.js – Structured Data for SEO and Smart Engines

JSON-LD is a structured data format that helps search engines and AI understand the content and context of your pages. This article explains how to embed JSON-LD in Next.js pages, prevent XSS vulnerabilities, validate schema markup, and type your data with TypeScript.

JSON-LDSEOSchema.orgXSS Sanitization

~2 دقیقه مطالعه · آخرین به‌روزرسانی ۶ آبان ۱۴۰۴

Introduction


JSON-LD is a structured data format used by search engines like Google to better understand the meaning and relationships within your page content. It can describe entities such as products, events, people, books, recipes, and more.


Embedding JSON-LD in Next.js Pages


The recommended approach is to render JSON-LD as a <script type="application/ld+json"> tag inside your layout.tsx or page.tsx components.

Example:

export default async function Page({ params }) {
  const { id } = await params
  const product = await getProduct(id)

  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'Product',
    name: product.name,
    image: product.image,
    description: product.description,
  }

  return (
    <section>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c'),
        }}
      />
      {/* Other page content */}
    </section>
  )
}

Preventing XSS Vulnerabilities


JSON.stringify does not sanitize malicious strings. To prevent XSS injection, replace characters like < with their Unicode equivalents (e.g. \u003c) or use libraries like serialize-javascript for safer serialization.


Typing JSON-LD with TypeScript


Use community packages like schema-dts to type your JSON-LD objects:

import { Product, WithContext } from 'schema-dts'

const jsonLd: WithContext<Product> = {
  '@context': 'https://schema.org',
  '@type': 'Product',
  name: 'Next.js Sticker',
  image: 'https://nextjs.org/imgs/sticker.png',
  description: 'Dynamic at the speed of static.',
}

Validating Structured Data


Use the following tools to test and validate your JSON-LD:


Conclusion


Adding JSON-LD to your Next.js application improves SEO and helps search engines understand your content. By embedding structured data securely and using TypeScript for validation, you can deliver rich, machine-readable pages with confidence.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Advanced Client-Side Routing and Performance Hooks in Next.js

Next.js provides a rich set of client-side hooks and caching utilities that empower developers to build dynamic, responsive, and secure applications. From reading route parameters to tracking navigation state and reporting performance metrics, this guide walks you through the most important tools available in the App Router.

ادامه

Handling Authorization and Caching in Next.js: A Developer’s Guide

Next.js introduces powerful experimental features for access control and smart caching. This guide covers the unauthorized() function for custom 401 handling, unstable_cache for persistent memoization, updateTag for instant cache invalidation, and useLinkStatus for inline navigation feedback. Learn how to use these tools to build secure, performant, and responsive applications.

ادامه

redirect and refresh in Next.js — Smart Redirects and Client Refreshing via Server Actions

The redirect function in Next.js allows you to navigate users to a new route, returning either a 307 or 303 HTTP response depending on context. It works in Server Components, Client Components, Route Handlers, and Server Actions. The refresh function is used exclusively within Server Actions to refresh the client router. This article explains how both functions work, with practical examples and key considerations.

ادامه

NextRequest and NextResponse in Next.js — Managing Cookies, Headers, Redirects, and Rewrites

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse, offering powerful tools for managing cookies, headers, redirects, rewrites, and JSON responses. These utilities simplify server-side logic and improve control over routing, personalization, and security. This guide walks through their capabilities with practical examples and best practices.

ادامه

headers, ImageResponse, notFound, and permanentRedirect in Next.js — Request Handling, Dynamic Images, Errors, and Redirects

Next.js offers powerful tools for handling HTTP requests and responses in Server Components. The headers function lets you read incoming request headers. ImageResponse allows you to generate dynamic images using JSX and CSS. The notFound function renders a custom 404 page, and permanentRedirect enables permanent redirection to another route. This article explains how to use each feature with practical examples.

ادامه

A Complete Guide to Using metadata and generateMetadata in Next.js

In modern versions of Next.js, managing page metadata is more powerful and intuitive than ever. Metadata is automatically injected into the <head> of your pages and plays a vital role in SEO, social sharing, and user experience. This guide explains the two main ways to define metadata: using the static metadata object and the dynamic generateMetadata function.

ادامه