Schema-Driven Data Extraction: Using Zod & JSON Schema to Extract Structured Data from Any URL | Context.dev

Web data ingestion has reached an architectural inflection point in 2026. Historically, extracting information from the web required developers to write and maintain fragile scraping pipelines built on CSS selectors, XPath expressions, or complex regular expressions. These traditional implementations suffer from continuous maintenance overhead—a minor change in a website's DOM structure or frontend framework can break downstream data processing instantly. Today, modern developer teams are abandoning these legacy methods in favor of contract-first methodologies.

This guide explores how to build highly resilient data pipelines using TypeScript schema engines like Zod in conjunction with modern web extraction endpoints to convert unstructured web content into fully validated, strongly typed JSON objects.

What is Schema-Driven Data Extraction?

Schema-driven data extraction replaces brittle DOM parsing with contract-first data extraction. By defining the exact shape, type constraints, and semantic descriptions of desired data using a schema validation library, developers delegate the actual crawling and parsing logic to an intelligent extraction engine.

Rather than telling a scraper where to look (e.g., div.pricing-card > h3), you define what you want (e.g., monthlyPriceUSD: z.number()). The extraction infrastructure decouples web crawling from the underlying HTML structure, executing intelligent page navigation, content parsing, and data structuring to return a JSON payload that perfectly matches your predefined specification.

"The main point of failure in classical scraping isn't network blocking—it is DOM drift. Schema-driven extraction abstracts the DOM away entirely, treating the web as a queryable database governed by structured type contracts."Web Infrastructure Benchmark Analysis

The Three-Layer Extraction Architecture

Schema-driven extraction relies on three tightly integrated layers: compile-time type validation, universal exchange formats, and intelligent web extraction APIs.

1. Zod: The TypeScript Schema Definition

Zod has firmly established itself as the standard validation library in the TypeScript ecosystem. With over 31 million weekly npm downloads reported in the Zod v4 release notes, it provides static type inference alongside runtime validation. Zod 4 notably introduced native JSON Schema export capabilities (z.toJSONSchema()), alongside a 14x faster string parser and 6.5x faster object validation, making it ideal for high-throughput serverless data pipelines.

2. JSON Schema: The Universal Interchange Protocol

While Zod operates natively within TypeScript, web data APIs require a language-agnostic format. JSON Schema serves as this universal protocol. It securely communicates exact object keys, nested arrays, primitive types, required parameters, and contextual metadata from the client application to the remote extraction engine.

3. Web Context APIs: The Extraction Engine

Traditional scraping engines yield raw HTML or unparsed text, forcing developers to host their own LLMs or manage complex orchestration workflows. Modern infrastructure APIs like Context.dev's Extract API absorb this complexity. They combine proxy rotation, headless browser rendering, PDF parsing, multi-page link following, and LLM-powered structured extraction into a single HTTP request.

Step-by-Step Guide: Extracting Structured Data Using Zod

The following code-first guide demonstrates how to define a Zod schema, serialize it for extraction via Context.dev, and enforce runtime type safety on the returned payload. In this scenario, we will extract competitive intelligence and product tier details from a SaaS marketing URL.

Step 1: Install Required Dependencies

First, install the official web context SDK and Zod into your Node.js or TypeScript project:

npm install context.dev zod

Step 2: Define the Schema and Execute Extraction

In your application code, you will use Zod to define the target data structure. Crucially, the .describe() method is used to provide natural language prompts directly in the schema, which guides the underlying AI extraction engine on nuanced fields.

import { Context } from 'context.dev';
import { z } from 'zod';
 
// Initialize Context.dev SDK (automatically reads CONTEXT_DEV_API_KEY)
const client = new Context();
 
// 1. Define the target output schema using Zod
const ProductExtractionSchema = z.object({
  companyName: z.string().describe("The official brand or company name"),
  valueProposition: z.string().describe("Primary core value proposition or headline slogan"),
  pricingTiers: z.array(
    z.object({
      tierName: z.string().describe("Name of the pricing plan (e.g. Free, Pro, Enterprise)"),
      monthlyPriceUSD: z.number().nullable().describe("Monthly billing price in USD; null if custom/contact sales"),
      keyFeatures: z.array(z.string()).describe("List of prominent features included in this tier"),
    })
  ).describe("Array of publicly listed pricing plans and tiers"),
  supportedIntegrations: z.array(z.string()).describe("Key integrations or third-party platforms mentioned"),
  hasFreeTrial: z.boolean().describe("Whether a free trial or free tier is explicitly offered"),
});
 
// Infer the TypeScript type statically from the Zod schema
type ProductExtractionData = z.infer<typeof ProductExtractionSchema>;
 
async function extractWebsiteData(targetUrl: string): Promise<ProductExtractionData> {
  // 2. Convert Zod Schema to standardized JSON Schema
  const jsonSchema = z.toJSONSchema(ProductExtractionSchema);
 
  console.log(`Extracting structured data from: ${targetUrl}...`);
 
  // 3. Call Web Context API for extraction
  const response = await client.web.extract({
    url: targetUrl,
    schema: jsonSchema,
    instructions: "Prioritize pricing tables, feature lists, and footer integration links.",
    maxPages: 5,         // Crawl up to 5 relevant pages on the domain
    factCheck: true,      // Disallow hallucinations or inferred non-explicit facts
    timeoutMS: 60000,     // Request timeout threshold
  });
 
  // 4. Enforce Runtime Validation
  const validatedData = ProductExtractionSchema.parse(response.data);
 
  console.log("Analyzed pages:", response.urls_analyzed);
  return validatedData;
}
 
// Example Execution
extractWebsiteData("https://example.com/pricing")
  .then((data) => console.log("Extracted Payload:", JSON.stringify(data, null, 2)))
  .catch((err) => console.error("Extraction error:", err));

Handling Multi-Page Synthesis and Hallucinations

When deploying AI for web data extraction, two primary challenges arise: distributed context and model hallucination. Modern schema-driven approaches address both programmatically.

Multi-Page Crawling

Single-page HTML parsing often misses crucial corporate information distributed across distinct routes. A pricing table might live on /pricing, while integrations live on /features. By utilizing parameters like maxPages: 5, modern extraction APIs perform targeted domain crawls. The engine autonomously navigates relevant internal links to synthesize a complete entity profile into your single JSON response.

Anti-Hallucination Enforcements

A common failure point in LLM-assisted extraction is the model inferring missing attributes (such as guessing a price point or a founding year). Modern platforms implement strict verification mechanisms. Enabling a directive like factCheck: true explicitly prohibits the extraction engine from generating inferred values, forcing it to return null or omit fields when the underlying web source lacks explicit backing text.

Traditional Scraping vs. Schema-Driven Extraction

Schema-driven extraction resolves systemic limitations inherent in legacy architectures like Cheerio or Playwright. The shift from imperative scraping to declarative extraction drastically reduces maintenance burdens.

Feature DimensionLegacy DOM ScrapingSchema-Driven API Extraction
Data TargetingCSS Selectors (.price > span), XPath, RegexDeclarative TypeScript (Zod) & JSON Schema
Resilience to ChangeZero. Renaming a CSS class breaks production.High. Self-healing AI extraction adapts to HTML refactoring automatically.
Scope of CrawlManual pagination and recursive URL navigation required.Automated internal link navigation across multiple pages (maxPages).
Content IngestionRequires custom parsers for PDFs or non-HTML binaries.Handles mixed media, inline PDFs, and raw text seamlessly.
Type SafetyRequires manual parsing and defensive try/catch logic.Native compile-time and runtime validation (z.infer and schema.parse).

Preparing Pipelines for Autonomous Agents

As developer ecosystems continue migrating toward agentic AI architectures in 2026, the demand for live, structured, and strictly typed web data has never been higher.

By coupling compile-time type safety with an intelligent web extraction engine like Context.dev, developer teams can eliminate scraper maintenance entirely. Whether you are building automated CRM enrichment pipelines, populating vector databases, or feeding autonomous agents, schema-driven data extraction guarantees that your application only ingests clean, factual, and perfectly structured JSON.

Ship an agent that actually knows things.

Free tier, 10-minute integration, and the same API powering agents at Mintlify, daily.dev, and Propane. No credit card to start.