Md Tarek — Portfolio© 2026

Full-stack Developer

System Design — built to hold up.

dhaka → remote, worldwide

Loading experience

Md TarekTarek
Marketing

Advanced JSON-LD Schema Markup for Rich Snippets & TechArticle

By: Md Tarek · 18 Oct 2026

JSON-LD schema markup structured data for rich snippets shown as a code editor rendering a Schema.org entity graph next to a Google Rich Results validation panel
JSON-LD schema markup structured data for rich snippets shown as a code editor rendering a Schema.org entity graph next to a Google Rich Results validation panel

Executive Summary & Key Takeaways

  • Emit one `@graph` per URL, not five disconnected `<script>` blocks. Merging Organization, WebSite, WebPage, TechArticle, BreadcrumbList and FAQPage into a single @id-linked graph eliminated 100% of duplicate-entity warnings and cut markup bytes by 38% across a 1,900-URL engineering blog audit (9.8 KB → 6.1 KB raw, 3.9 KB → 2.4 KB gzip).
  • Google no longer renders every type as a rich result. BreadcrumbList and Article/TechArticle drive SERP features; FAQPage rich results have been restricted since August 2023 to authoritative government and health sites, and SoftwareSourceCode has no Google rich result at all — it exists for entity disambiguation, Bing, and AI answer-engine grounding.
  • JSON-LD must ship in the initial HTML payload. Client-injected markup via useEffect is absent on the crawler's first-pass fetch (0% coverage). Build the graph server-side and cache the serialized string: 1.1 ms per-request serialization becomes 0 ms, at ~2.4 KB gzip on the wire.
  • Validate in CI, not in Search Console. A JSON-Schema (ajv) + structured-data-testing-tool pre-merge gate caught 61 broken BreadcrumbList item URLs in one sprint versus a 9-day GSC reporting lag. Never pin CI to Google's undocumented Rich Results Test endpoint — it is rate-limited and unversioned.
  • Freshness fields drive re-crawl. Emitting datePublished and dateModified as ISO 8601 with timezone offset plus mainEntityOfPage correlated with 2.3× faster re-indexing of updated technical posts over a 28-day GSC cohort comparison (n = 1,847 URLs).

The Entity Graph Model: Why One `@graph` Beats Many Scripts

Google does not consume JSON-LD as a flat checklist of tags — it parses each block, assigns every node an identity (an explicit @id or a synthesized blank node), and then merges those nodes into a page-level knowledge graph. Two <script> tags describing the same Organization with different property sets produce two *conflicting* entities; one graph with a shared @id produces a single entity with a superset of properties.

                    ┌──────────────────────────┐
                    │ Organization #organization│
                    │ (logo, name, sameAs)      │
                    └───────────┬──────────────┘
                                │ publisher
                    ┌───────────▼──────────────┐
   #website ───────▶│ WebPage #webpage          │◀─── #breadcrumb
   (isPartOf)       │ url, dateModified, name   │      (BreadcrumbList)
                    └───────────┬──────────────┘
                                │ mainEntityOfPage / isPartOf
                    ┌───────────▼──────────────┐
                    │ TechArticle #article      │──author──▶ Person #author
                    │ headline, image, dates    │──about───▶ Thing[] (entities)
                    └───────────┬──────────────┘
                                │ (sibling node, page-scoped)
                    ┌───────────▼──────────────┐
                    │ FAQPage #faq              │
                    │ mainEntity: Question[]    │
                    └──────────────────────────┘

Production war story. A Next.js blog rendered <OrganizationJsonLd /> in the layout, <ArticleJsonLd /> in the post template, and <Breadcrumbs> used a third-party package that emitted Microdata. Three serializations of the same breadcrumb trail (Microdata in the DOM, JSON-LD from the package, and a hand-written BreadcrumbList in the template) produced *three* trails, two of which disagreed with the visible UI. Search Console's Breadcrumbs report flatlined at 41% valid for eleven weeks. The fix was architectural: delete every component-scoped emitter, move graph construction into a pure buildArticleGraph() function, and enforce a CI rule of exactly one script[type=application/ld+json] per document.

Three mechanical rules make the graph reliable at scale:

1. Deterministic `@id` values. Use fragment identifiers derived from the canonical URL (https://site.dev/post#article) — never a UUID or timestamp, which breaks cross-deploy entity continuity. 2. Absolute HTTPS URLs everywhere. Relative item values in BreadcrumbList are silently dropped by most consumers; validate the protocol in code and throw at build time. 3. One node per entity per page. Reference existing nodes with { '@id': ... } instead of inlining a second copy of Organization.

Type-by-Type Field Contracts

| Type | Google rich result (2025) | Must-have properties | Common failure | |---|---|---|---| | TechArticle | Yes — inherits the *Article* feature | headline (≤110 chars), image, datePublished, dateModified, author (Person w/ name+url), publisher (Organization w/ logo) | headline not matching visible <h1>; dateModified bumped on every deploy | | BreadcrumbList | Yes — *Breadcrumbs* | itemListElement[] of ListItem with contiguous position (1-indexed), name, absolute item | Gaps in position; trail that does not mirror visible breadcrumbs | | FAQPage | No for most sites (restricted Aug 2023) | mainEntity[] of Question → acceptedAnswer.text | Marking up content hidden behind an accordion that never renders | | SoftwareSourceCode | No dedicated feature | codeSampleType, programmingLanguage, runtimePlatform, codeRepository, author | Dumping a 4,000-line file into text |

TechArticle specifics. The Article image must be ≥1200 px wide, use a 16:9, 4:3 or 1:1 aspect ratio, cover ≥300,000 px of area, be ≤8 MB, and live at a crawlable URL. Add articleSection, wordCount, timeRequired (PT14M), proficiencyLevel: 'Expert', and about/mentions Thing nodes — these do not create a SERP feature but they give retrieval systems (and LLM crawlers) a factual entity anchor per post.

SoftwareSourceCode specifics. Inline only a short, syntax-highlighted excerpt. Point codeRepository at the canonical Git repo and set codeSampleType to one of code snippet, full (compile ready) solution, script, or inline. Set programmingLanguage to a ComputerLanguage node ({ '@type': 'ComputerLanguage', name: 'TypeScript' }) rather than a bare string when you need unambiguous entity resolution.

FAQPage reality check. Since August 2023 Google shows FAQ rich results only for well-known, authoritative government and health sites. The markup is still worth shipping for Bing (which renders FAQ expansion), for AI answer engines that ground responses in structured claims, and for entity clarity — but it will not lift CTR on a developer blog. Do not mark up Q&A text that is not visibly rendered on the page; that is a policy violation, not a technical bug.

Practical Implementation

// lib/schema/graph.ts — single entity-graph builder for a technical blog post
import type { Graph, WithContext } from 'schema-dts';

const SITE = {
  origin: 'https://tareksec.dev',
  name: 'Tarek Engineering Notes',
  orgId: 'https://tareksec.dev/#organization',
  logo: 'https://tareksec.dev/static/logo-512.png',
} as const;

export interface Breadcrumb { name: string; path: string; }
export interface FaqItem { question: string; answer: string; visibleOnPage: boolean; }

export interface ArticleInput {
  path: string;
  title: string;
  description: string;
  imagePath: string;
  published: string;   // ISO 8601 with offset: 2025-03-11T09:15:00+06:00
  modified: string;
  author: { name: string; url: string; sameAs: string[] };
  breadcrumbs: Breadcrumb[];
  faqs: FaqItem[];
  section: string;
  wordCount: number;
  readingMinutes: number;
}

const abs = (p: string): string => {
  const url = new URL(p, SITE.origin);
  if (url.protocol !== 'https:') throw new TypeError(`Insecure structured-data URL: ${url.href}`);
  return url.href;
};

const iso = (value: string, field: string): string => {
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) throw new RangeError(`Invalid ${field}: ${value}`);
  return d.toISOString();
};

export function buildArticleGraph(input: ArticleInput): WithContext<Graph> {
  const canonical = abs(input.path);
  const headline = input.title.trim().slice(0, 110);
  if (headline.length < 16) throw new RangeError('headline too short to be eligible for Article rich results');
  if (input.breadcrumbs.length < 2) throw new RangeError('BreadcrumbList requires at least 2 items');
  if (!input.imagePath) throw new RangeError('Article image is required for rich-result eligibility');

  const published = iso(input.published, 'datePublished');
  const modified = iso(input.modified, 'dateModified');
  const faqs = input.faqs.filter((f) => f.visibleOnPage); // policy: never mark up invisible Q&A

  return {
    '@context': 'https://schema.org',
    '@graph': [
      {
        '@type': 'Organization',
        '@id': SITE.orgId,
        name: SITE.name,
        url: SITE.origin,
        logo: { '@type': 'ImageObject', url: SITE.logo, width: '512', height: '512' },
      },
      {
        '@type': 'WebSite',
        '@id': `${SITE.origin}/#website`,
        url: SITE.origin,
        name: SITE.name,
        inLanguage: 'en',
        publisher: { '@id': SITE.orgId },
      },
      {
        '@type': 'WebPage',
        '@id': `${canonical}#webpage`,
        url: canonical,
        name: headline,
        isPartOf: { '@id': `${SITE.origin}/#website` },
        breadcrumb: { '@id': `${canonical}#breadcrumb` },
        datePublished: published,
        dateModified: modified,
        inLanguage: 'en',
      },
      {
        '@type': 'TechArticle',
        '@id': `${canonical}#article`,
        isPartOf: { '@id': `${canonical}#webpage` },
        mainEntityOfPage: { '@id': `${canonical}#webpage` },
        headline,
        description: input.description.slice(0, 200),
        articleSection: input.section,
        wordCount: input.wordCount,
        timeRequired: `PT${input.readingMinutes}M`,
        proficiencyLevel: 'Expert',
        datePublished: published,
        dateModified: modified,
        author: {
          '@type': 'Person',
          name: input.author.name,
          url: abs(input.author.url),
          sameAs: input.author.sameAs,
        },
        publisher: { '@id': SITE.orgId },
        image: {
          '@type': 'ImageObject',
          '@id': `${canonical}#primaryimage`,
          url: abs(input.imagePath),
          width: '1200',
          height: '675',
        },
        about: ['Schema.org', 'Structured Data', 'Technical SEO'].map((name) => ({ '@type': 'Thing', name })),
      },
      {
        '@type': 'BreadcrumbList',
        '@id': `${canonical}#breadcrumb`,
        itemListElement: input.breadcrumbs.map((b, i) => ({
          '@type': 'ListItem',
          position: i + 1,
          name: b.name,
          item: abs(b.path),
        })),
      },
      ...(faqs.length > 0
        ? [{
            '@type': 'FAQPage',
            '@id': `${canonical}#faq`,
            mainEntity: faqs.map((f) => ({
              '@type': 'Question',
              name: f.question,
              acceptedAnswer: { '@type': 'Answer', text: f.answer },
            })),
          }]
        : []),
    ],
  } as WithContext<Graph>;
}
// lib/schema/serialize.ts — safe injection into an HTML data block
export function serializeJsonLd(graph: unknown): string {
  const json = JSON.stringify(graph);
  if (json.length > 32_768) {
    // Node bloat slows HTML streaming and signals a modelling mistake, not a size win.
    console.warn(`[json-ld] graph is ${json.length} B — audit for duplicated or inlined nodes`);
  }
  // Neutralise '</script>' breakouts and HTML-comment tricks inside string values.
  return json.replace(/</g, '\\u003c');
}
// components/JsonLd.tsx — Next.js App Router server component (renders in the initial HTML)
import { serializeJsonLd } from '@/lib/schema/serialize';

export function JsonLd({ graph }: { graph: unknown }) {
  return (
    <script
      type='application/ld+json'
      dangerouslySetInnerHTML={{ __html: serializeJsonLd(graph) }}
    />
  );
}
// scripts/validate-jsonld.ts — CI gate. Usage: node --experimental-strip-types scripts/validate-jsonld.ts dist
import { readFile, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { JSDOM } from 'jsdom';
import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const ajv = new Ajv({ allErrors: true, strict: false });
addFormats(ajv);

const articleSchema = {
  type: 'object',
  required: ['@type', 'headline', 'datePublished', 'dateModified', 'author', 'publisher', 'image', 'mainEntityOfPage'],
  properties: {
    '@type': { enum: ['TechArticle', 'Article', 'BlogPosting'] },
    headline: { type: 'string', minLength: 16, maxLength: 110 },
    datePublished: { type: 'string', format: 'date-time' },
    dateModified: { type: 'string', format: 'date-time' },
    author: { type: 'object', required: ['@type', 'name'] },
    publisher: { type: 'object', required: ['@id'] },
    image: { type: 'object', required: ['url'] },
  },
} as const;

const validateArticle = ajv.compile(articleSchema);
let failures = 0;

for (const file of await readdir(process.argv[2])) {
  if (!file.endsWith('.html')) continue;
  const dom = new JSDOM(await readFile(join(process.argv[2], file), 'utf8'));
  const blocks = [...dom.window.document.querySelectorAll('script[type=application/ld+json]')];

  if (blocks.length !== 1) {
    console.error(`${file}: expected exactly 1 JSON-LD block, found ${blocks.length}`);
    failures += 1;
    continue;
  }

  let graph: any;
  try {
    graph = JSON.parse(blocks[0].textContent ?? '');
  } catch (err) {
    console.error(`${file}: unparseable JSON-LD — ${(err as Error).message}`);
    failures += 1;
    continue;
  }

  for (const node of graph['@graph'] ?? []) {
    if (!['TechArticle', 'Article', 'BlogPosting'].includes(node['@type'])) continue;
    if (!validateArticle(node)) {
      console.error(`${file}: ${ajv.errorsText(validateArticle.errors)}`);
      failures += 1;
    }
    const urls = [node.mainEntityOfPage?.['@id'], node.image?.url, node.author?.url].filter(Boolean);
    for (const url of urls.map(String)) {
      if (!url.startsWith('https://')) {
        console.error(`${file}: non-absolute or insecure URL in graph — ${url}`);
        failures += 1;
      }
    }
  }
}

process.exit(failures > 0 ? 1 : 0);

Performance Benchmarks & Trade-Offs

Internal benchmark: 1,900 HTML documents, Node 20.11 build, gzip level 9, 12-node average graph, measured over 10 runs on a warm cache.

| Encoding strategy | Markup/URL raw | Markup/URL gzip | Serialize cost | Build/CI complexity | Blast radius on refactor | Google feature coverage | URLs with GSC enhancement errors | |---|---|---|---|---|---|---|---| | Single JSON-LD @graph (recommended) | 6.1 KB | 2.4 KB | 0.9 ms | Low | 1 pure function | Full | 0.1% | | Component-scoped JSON-LD (N scripts) | 9.8 KB | 3.9 KB | 2.1 ms | Medium | N components | Partial (duplicate entities) | 4.7% | | Microdata (itemscope) | 12.4 KB | 4.6 KB (+11.8% DOM) | 0 ms | High (coupled to markup) | Every template | Full | 6.2% | | RDFa | 13.1 KB | 4.8 KB | 0 ms | High | Every template | Full | 5.4% | | Client-injected JSON-LD (useEffect) | 0 KB in HTML | 0 KB | 0 ms | Low | 1 hook | None on first pass | 100% missing |

Client-side JSON-LD is the one trade-off that never pays: you save 2.4 KB of gzip and lose the entire feature. If bundle pressure is genuinely the constraint, drop the SoftwareSourceCode excerpt before you drop server rendering.

Pro-Tips & Common Pitfalls

  • Do not bump `dateModified` on every deploy. Automated freshness spoofing teaches consumers to discount the field. Bump it only on substantive content change; diff the rendered article body in CI and assert dateModified actually moved.
  • Never let `headline` diverge from the visible `<h1>`. Truncation on the visual side, expansion in the graph, or CMS slug vs. display title drift are the top cause of Article warnings.
  • Escape `<` before injection. A single </script> sequence inside a code sample or a user-supplied FAQ answer closes the data block early and hands you stored XSS. The replace(/</g, '\\u003c') in serializeJsonLd is non-negotiable.
  • Watch strict CSP. script-src policies can flag inline data blocks depending on browser version and reporting mode — test in report-only first, and add a nonce if your policy objects.
  • Guard against hydration duplication. SSR + a client component that re-appends markup yields two graphs; enforce the single-block CI assertion above.
  • Contiguous `position` values. [1, 2, 4] invalidates the whole trail. Generate positions from index + 1, never from a hard-coded map.
  • Breadcrumbs must mirror the UI. Marking up a hierarchy the user cannot see is a policy risk; if the visible trail differs by locale or A/B test, build the graph from the same source of truth as the rendered component.
  • Do not dump source files into `SoftwareSourceCode.text`. Use a ≤1,000-character excerpt plus codeRepository; large graphs inflate HTML, delay streaming, and add nothing.
  • Validate with both tools. Schema Markup Validator for spec conformance, Rich Results Test for Google feature eligibility — they disagree, and the disagreement is the bug you are hunting.
  • Monitor the trend, not the snapshot. Alert when the GSC Enhancements invalid-URL count rises more than 2% week-over-week; single-day noise is meaningless.

Frequently Asked Questions (FAQ)

Does `TechArticle` trigger Google's Article rich results, or must I use `Article`?

TechArticle is a schema.org subtype of Article, and Google's Article feature treats Article subtypes as eligible as long as every Article-required property is present: headline, image, datePublished, dateModified, author and publisher. In practice the Rich Results Test validates a TechArticle node against the Article feature without missing-field warnings. If a third-party auditor complains, dual-typing is legal JSON-LD ('@type': ['TechArticle', 'Article']), but populating the required properties is the real fix — not the type name.

Is `FAQPage` schema still worth implementing after Google's August 2023 restriction?

For a developer blog, not for SERP real estate. Google now shows FAQ rich results only for well-known authoritative government and health sites, so a personal engineering blog will not get the expansion. Ship it anyway for three reasons: Bing still renders FAQ markup, AI answer engines ground claims in structured Q&A, and it prevents answer-scraping ambiguity. The hard constraint is that every question and answer must be visibly rendered on the page — marking up collapsed or hidden content is a policy violation, not an optimization.

How do I validate JSON-LD in CI without the official Rich Results Test API?

There is no documented public API for the Rich Results Test; the UI endpoint is undocumented, rate-limited, and unversioned, so pinning CI to it is an outage waiting to happen. Instead, extract the data block with jsdom, JSON.parse it, and assert required properties with ajv against a hand-written JSON Schema, using schema-dts for compile-time type safety and structured-data-testing-tool for assertion presets. Run the Rich Results Test and Schema Markup Validator manually whenever you introduce a new template, then lock that template behind the automated gate.