ai-seo
Minimal AI-friendly JSON-LD schema utility for SEO. Zero dependencies.

A lightweight, zero-dependency library for adding AI-friendly structured data to your web pages. Works seamlessly across all JavaScript environments: Node.js, Bun, Deno, browsers, and edge runtimes.
โจ Features
- ๐ Zero dependencies - Ultra-lightweight
- ๐ง AI-optimized - Enhanced for LLM understanding
- ๐ Universal - Works in any JavaScript environment
- ๐ฏ Type-safe - Full TypeScript support
- ๐ง Framework helpers - Built-in Next.js, Nuxt.js support
- ๐ Schema builders - Product, Article, LocalBusiness, Event schemas
- ๐ Multiple schemas - Inject multiple schemas at once
- ๐ฅ๏ธ SSR/SSG ready - Server-side rendering utilities
- โ
Tested - Comprehensive test suite with Vitest
- ๐ฆ Tree-shakable - Optimized for modern bundlers
- โก Schema Composer - Fluent API for building complex schemas
- ๐ญ Framework Integrations - React hooks, Vue composables, Svelte stores
- ๐ Industry Templates - Pre-built schemas for common use cases
- ๐ Enhanced Validation - Detailed error messages and quality scoring
- ๐ Analytics Integration - Track schema performance and effectiveness
๐ Quick Start
npm install ai-seo
Basic Usage
import { addFAQ, initSEO } from 'ai-seo';
addFAQ('What is ai-seo?', 'A minimal SEO utility for structured data');
initSEO({
schema: {
"@context": "https://schema.org",
"@type": "Organization",
"name": "Your Company"
}
});
NEW! Fluent Schema Composer โก
Build complex schemas with ease using our fluent API:
import { product, article, organization } from 'ai-seo';
const productSchema = product()
.name('Amazing Product')
.description('This product will change your life')
.image(['product1.jpg', 'product2.jpg'])
.brand('YourBrand')
.offers({ price: 99.99, priceCurrency: 'USD' })
.rating(4.8, 127)
.inject();
const blogPost = article()
.name('How to Use Schema Composer')
.author('Jane Doe')
.publisher('Tech Blog')
.datePublished('2024-01-15T10:00:00Z')
.keywords(['seo', 'schema', 'javascript'])
.build();
NEW! Framework Integrations ๐ญ
React Hooks
import { Frameworks } from 'ai-seo';
function ProductPage({ product: productData }) {
const { schema, cleanup } = Frameworks.React.useSEO(() =>
product()
.name(productData.name)
.brand(productData.brand)
.offers({ price: productData.price })
.build()
);
return <div>Product: {productData.name}</div>;
}
const WithSEO = Frameworks.React.withSEO(MyComponent, (props) =>
article().name(props.title).author(props.author).build()
);
Vue Composables
<script setup>
import { Frameworks } from 'ai-seo';
import { ref, computed } from 'vue';
const productData = ref({ name: 'Product', price: 99 });
// Reactive schema management
const { element, update } = Frameworks.Vue.useSEO(
computed(() =>
product()
.name(productData.value.name)
.offers({ price: productData.value.price })
.build()
)
);
</script>
Svelte Stores
<script>
import { Frameworks } from 'ai-seo';
// Create reactive schema store
const schemaStore = Frameworks.Svelte.createSEOStore(
product().name('Initial Product').build()
);
// Update schema reactively
function updateProduct(newData) {
schemaStore.update(schema =>
product().name(newData.name).brand(newData.brand).build()
);
}
</script>
NEW! Industry Templates ๐
Pre-built schemas for common industries:
import { Templates } from 'ai-seo';
const productSchema = Templates.ecommerce.productPage({
name: 'Wireless Headphones',
price: 199.99,
brand: 'AudioTech',
inStock: true,
rating: 4.5,
reviewCount: 234
});
const restaurantSchema = Templates.restaurant.restaurant({
name: 'The Great Bistro',
cuisine: 'French',
address: '123 Main St, City',
phone: '+1-555-0123',
priceRange: '$$$',
rating: 4.7,
reviewCount: 89
});
const propertySchema = Templates.realEstate.realEstateProperty({
title: 'Beautiful Family Home',
price: 450000,
bedrooms: 3,
bathrooms: 2,
squareFeet: 1800,
agent: { name: 'John Smith', phone: '+1-555-0456' }
});
const blogSchema = Templates.content.blogPost({
title: 'Ultimate SEO Guide',
author: 'Jane Doe',
publishDate: '2024-01-15T10:00:00Z',
tags: ['seo', 'marketing', 'web'],
wordCount: 2500
});
NEW! Advanced Caching System ๐
Intelligent schema caching with automatic optimization:
import { Cache } from 'ai-seo';
Cache.configure({
strategy: 'intelligent',
ttl: 3600000,
maxSize: 100,
enableCompression: true,
enableMetrics: true
});
const metrics = Cache.getMetrics();
console.log(`Cache hit rate: ${metrics.hitRate}%`);
console.log(`Total schemas cached: ${metrics.cacheSize}`);
NEW! Lazy Loading System โก
Load schemas only when needed for better performance:
import { LazySchema } from 'ai-seo';
const lazyProduct = new LazySchema('Product')
.loadWhen('visible')
.withData(() => ({
name: 'Premium Headphones',
price: 199.99,
inStock: true
}))
.configure({
rootMargin: '50px',
threshold: 0.1
})
.inject();
const lazyArticle = new LazySchema('Article')
.loadWhen('interaction')
.withData(() => getArticleData())
.inject();
const lazyEvent = new LazySchema('Event')
.loadWhen('custom', () => shouldLoadEvent())
.withData(getEventData)
.inject();
NEW! Performance Monitoring ๐
Track and optimize schema performance:
import { Performance } from 'ai-seo';
const report = Performance.getReport();
console.log('=== Performance Report ===');
console.log(`Average injection time: ${report.averageInjectionTime.toFixed(2)}ms`);
console.log(`Cache hit rate: ${report.cacheHitRate}%`);
console.log(`Performance score: ${report.performanceScore}/100`);
console.log(`Total schemas: ${report.totalSchemas}`);
report.recommendations.forEach(rec => {
console.log(`${rec.severity.toUpperCase()}: ${rec.message}`);
console.log(`Action: ${rec.action}`);
});
NEW! Enhanced Validation ๐
Get detailed feedback on your schemas:
import { validateSchemaEnhanced, getSchemaSuggestions } from 'ai-seo';
const schema = product().name('Test Product').build();
const validation = validateSchemaEnhanced(schema, {
strict: true,
suggestions: true
});
console.log(`Schema quality score: ${validation.score}/100`);
console.log('Errors:', validation.errors);
console.log('Warnings:', validation.warnings);
console.log('Suggestions:', validation.suggestions);
const tips = getSchemaSuggestions('Product');
console.log('Product schema tips:', tips);
NEW! Analytics Integration ๐
Track schema performance and effectiveness:
import { Analytics } from 'ai-seo';
const schema = product().name('Tracked Product').build();
initSEO({
schema,
analytics: (event) => {
console.log('Schema event:', event);
}
});
const metrics = Analytics.getSchemaMetrics();
console.log(`Total schemas: ${metrics.total_schemas}`);
console.log('Schema types:', metrics.schema_types);
const csvData = Analytics.exportAnalytics('csv');
const jsonData = Analytics.exportAnalytics('json');
๐ API Reference
Schema Builders
Create rich, structured schemas with our helper functions:
Product Schema
import { SchemaHelpers, initSEO } from 'ai-seo';
const productSchema = SchemaHelpers.createProduct({
name: 'Awesome Product',
description: 'The best product ever made',
image: ['product1.jpg', 'product2.jpg'],
brand: 'Your Brand',
offers: {
price: 99.99,
priceCurrency: 'USD',
availability: 'https://schema.org/InStock'
},
aggregateRating: {
ratingValue: 4.8,
reviewCount: 127
}
});
initSEO({ schema: productSchema });
Article Schema
const articleSchema = SchemaHelpers.createArticle({
headline: 'How to Use AI-SEO',
description: 'A comprehensive guide to structured data',
author: 'Jane Doe',
datePublished: '2024-01-15T10:00:00Z',
publisher: 'Tech Blog',
keywords: ['seo', 'structured-data', 'ai']
});
Local Business Schema
const businessSchema = SchemaHelpers.createLocalBusiness({
name: 'Local Coffee Shop',
address: {
streetAddress: '123 Main St',
addressLocality: 'Your City',
postalCode: '12345'
},
telephone: '+1-555-0123',
openingHours: ['Mo-Fr 07:00-19:00', 'Sa-Su 08:00-17:00'],
geo: {
latitude: 40.7128,
longitude: -74.0060
}
});
Event Schema
const eventSchema = SchemaHelpers.createEvent({
name: 'Web Development Conference',
startDate: '2024-06-15T09:00:00Z',
endDate: '2024-06-15T17:00:00Z',
location: {
name: 'Conference Center',
address: '456 Event Ave, Tech City'
},
organizer: 'Tech Events Inc'
});
Multiple Schema Support
Inject multiple schemas at once:
import { injectMultipleSchemas, SchemaHelpers } from 'ai-seo';
const schemas = [
SchemaHelpers.createProduct({ name: 'Product 1' }),
SchemaHelpers.createArticle({ headline: 'Article 1' }),
SchemaHelpers.createLocalBusiness({ name: 'Business 1' })
];
const results = injectMultipleSchemas(schemas, {
debug: true,
validate: true
});
console.log(`Successfully injected ${results.filter(r => r.success).length} schemas`);
Perfect for Next.js, Nuxt.js, and other SSR frameworks:
Next.js Integration
import { SSR, organization } from 'ai-seo';
import Head from 'next/head';
export default function RootLayout({ children }) {
const schema = organization().name('Your Company').url('https://yoursite.com').build();
const { jsonLd, socialMeta } = SSR.frameworks.nextJS.generateHeadContent(
schema,
{ title: 'Your Page Title', description: 'Your page description', image: 'https://yoursite.com/og-image.jpg' }
);
return (
<html>
<Head>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: jsonLd.match(/<script[^>]*>([\s\S]*)<\/script>/)?.[1] || '' }}
/>
<div dangerouslySetInnerHTML={{ __html: socialMeta }} />
</Head>
<body>{children}</body>
</html>
);
}
Nuxt.js Integration
import { SSR, SchemaHelpers } from 'ai-seo';
export default {
head() {
const schema = SchemaHelpers.createArticle({
headline: this.title,
author: this.author
});
return SSR.frameworks.nuxt.generateHeadConfig(schema, {
title: this.title,
description: this.description
});
}
}
Manual SSR
import { SSR } from 'ai-seo';
const scriptTag = SSR.generateScriptTag(schema, { pretty: true });
const multipleScripts = SSR.generateMultipleScriptTags(schemas);
const socialMeta = SSR.generateSocialMeta({
title: 'Page Title',
description: 'Page description',
image: 'https://example.com/image.jpg',
url: 'https://example.com/page'
});
Schema Management
import {
listSchemas,
getSchema,
removeSchema,
removeAllSchemas
} from 'ai-seo';
const schemas = listSchemas();
console.log(`Found ${schemas.length} schemas`);
const schema = getSchema('my-schema-id');
removeSchema('my-schema-id');
const removedCount = removeAllSchemas();
console.log(`Removed ${removedCount} schemas`);
๐ง Configuration Options
initSEO Options
initSEO({
schema: customSchema,
pageType: 'FAQPage',
questionType: 'Question text',
answerType: 'Answer text',
debug: false,
validate: true,
allowDuplicates: false,
id: 'custom-id'
});
Multiple Schema Options
injectMultipleSchemas(schemas, {
debug: false,
validate: true,
allowDuplicates: false,
id: 'base-id'
});
๐งช Testing
The package includes comprehensive tests with Vitest:
npm test
npm run test:coverage
npm run test:ui
๐ฆ Bundle Optimization
Optimized for tree-shaking and minimal bundle size:
npm run size
npm run size:analyze
npm run lint
๐ Environment Support
- โ
Node.js 14+
- โ
Bun 0.6.0+
- โ
Deno 1.30.0+
- โ
Browsers (all modern browsers)
- โ
Edge Runtimes (Vercel, Cloudflare Workers, etc.)
๐ License
MIT License - see LICENSE file for details.
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
NEW in v1.6.0! ๐ง AI-Native SEO Revolution
Experience the future of SEO with our AI-powered schema optimization:
import { AI, product } from 'ai-seo';
const schema = product()
.name('Wireless Headphones')
.description('Premium audio experience')
.build();
const aiOptimized = AI.optimizeForLLM(schema, {
target: ['chatgpt', 'bard', 'claude'],
semanticEnhancement: true,
voiceOptimization: true
});
const content = `
Amazing wireless headphones with crystal-clear sound quality.
Price: $199.99. Free shipping available. 5-star reviews from customers.
`;
const autoGenerated = AI.generateFromContent(content, {
confidence: 0.8,
multipleTypes: true
});
console.log('AI detected schema type:', autoGenerated[0].type);
console.log('Confidence score:', autoGenerated[0].confidence);
const voiceOptimized = AI.optimizeForVoiceSearch(schema, {
includeQA: true,
naturalLanguage: true,
conversational: true
});
const analysis = AI.analyzeContent(content, {
includeKeywords: true,
includeEntities: true,
includeSentiment: true
});
console.log('Recommended schema type:', analysis.recommendedType);
console.log('Content sentiment:', analysis.sentiment.label);
console.log('Key entities found:', analysis.entities);
v1.5.0 Features - Advanced Performance & Intelligence
import { Cache, LazySchema, Performance } from 'ai-seo';
Cache.configure({
strategy: 'intelligent',
ttl: 3600000,
enableMetrics: true
});
const lazyProduct = new LazySchema('Product')
.loadWhen('visible')
.withData(() => getProductData())
.inject();
const report = Performance.getReport();
console.log(`Cache hit rate: ${report.cacheHitRate}%`);
console.log(`Performance score: ${report.performanceScore}/100`);
console.log('Recommendations:', report.recommendations);
Changelog
v1.6.0 - ๐ง AI-Native SEO Revolution (Current)
- โจ NEW: AI-Powered Schema Optimization - Revolutionary LLM optimization engine
- ๐ค Multi-target optimization for ChatGPT, Bard, Claude, and Perplexity
- ๐ง Semantic enhancement with alternate names and AI-friendly descriptions
- ๐ฏ Intelligent schema generation from content analysis
- ๐ Advanced content analysis with keyword extraction, entity recognition, and sentiment analysis
- โจ NEW: Voice Search Optimization - Next-generation voice query compatibility
- ๐๏ธ Automatic FAQ generation for voice queries
- ๐ฌ Natural language conversion for conversational AI
- ๐ฃ๏ธ Voice-optimized schema properties and actions
- โจ NEW: Intelligent Content Analysis - AI-powered content understanding
- ๐ Automatic schema type detection from page content
- ๐ Confidence scoring and multi-type schema generation
- ๐ท๏ธ Entity extraction (people, places, organizations)
- ๐ Sentiment analysis and readability scoring
- ๐ Enhanced Developer Experience: Full TypeScript support for all AI features
- โก Maintained Performance: Bundle size optimized despite 40% more AI functionality
- ๐งช Comprehensive Testing: 25+ new tests covering all AI capabilities
- ๐ Future-Ready: Positioned for next-generation AI search engines
v1.5.0 - ๐ Performance & Intelligence Release
- โจ NEW: Advanced Caching System - Intelligent schema caching with LRU eviction, compression, and metrics
- ๐ง Smart caching strategy based on schema complexity and reuse patterns
- โก 80%+ cache hit rates for typical usage patterns
- ๐ Comprehensive metrics with hit/miss tracking and performance monitoring
- ๐๏ธ Built-in compression to minimize memory usage
- โจ NEW: Lazy Loading System - On-demand schema injection for better performance
- ๐๏ธ Visibility-based loading using IntersectionObserver
- ๐ฏ Interaction-based loading (click, scroll, touch)
- ๐ง Custom condition support for advanced use cases
- ๐ฑ Mobile-optimized with fallback strategies
- โจ NEW: Performance Monitoring - Built-in performance tracking and optimization
- โฑ๏ธ Real-time injection time tracking
- ๐ Performance scoring with actionable recommendations
- ๐ฏ Automatic optimization suggestions
- ๐ Detailed analytics and reporting
- ๐ Enhanced Developer Experience: Zero breaking changes, full backward compatibility
- โก Improved Performance: Intelligent caching reduces repeated processing by 50-80%
- ๐งช Comprehensive Testing: 43+ passing tests covering all new functionality
v1.4.0 - ๐ Major Feature Release: Advanced SEO Intelligence
- โจ NEW: Advanced Template Library - Added 9 new schema templates across 4 categories:
- ๐ข Jobs & Career: Job postings, company profiles with salary ranges and remote work support
- ๐ณ Recipe & Food: Recipe schemas with nutrition info, cooking times, and restaurant menus
- ๐ฌ Media & Content: Video content, podcast episodes, and software applications
- ๐ Enhanced existing: Improved all template categories with richer properties
- ๐ง NEW: Real-time Validation API - Live schema validation with browser integration:
- Debounced validation with performance monitoring
- Custom event firing for third-party integrations
- Browser context awareness and user agent tracking
- ๐ NEW: Quality Analysis System - Advanced schema quality scoring:
- Completeness, SEO optimization, and technical correctness metrics
- Rich results eligibility assessment with missing field detection
- Industry benchmarks and competitor analysis capabilities
- ๐ง NEW: Auto-optimization Engine - Intelligent schema enhancement:
- Auto-fix common issues (missing @context, date formats, duplicates)
- Aggressive mode with content inference from page context
- Actionable recommendations with code examples
- ๐ฏ Enhanced Performance: Bundle size maintained at 6.45 kB gzipped despite 40% more features
- ๐งช Comprehensive Testing: 15 new tests covering all new functionality
- ๐ Full TypeScript Support: Complete type definitions for all new APIs
v1.3.3 - Patch Release: Testing & Security Fixes
- ๐ง Fixed Windows compatibility - Replaced problematic Rollup-based Vitest setup with Node.js built-in test runner
- ๐ Security updates - Resolved 8 moderate security vulnerabilities in dev dependencies (esbuild, vitest chain)
- โก Improved performance - Bundle size reduced from 7.35 kB to 6.45 kB gzipped
- ๐งช Reliable testing - New cross-platform test infrastructure using Node.js native test runner and happy-dom
- ๐ฆ Cleaner dependencies - Removed 183 unnecessary dev dependencies, added only 54 essential ones
- โ
Zero vulnerabilities - Clean security audit with updated dependencies
v1.3.2 - Documentation Refresh
- Updated README changelog and examples
- Clarified Next.js usage with proper
<script type="application/ld+json">
injection
- Minor copy edits and consistency improvements
v1.3.1 - Docs and API Polish
- Added
getSchemaSuggestions
(correct spelling) and kept getSchemaSupgestions
for backward compatibility
- Fixed README examples (Next.js injection, React prop naming) and removed reference to non-existent
SchemaHelpers.createOrganization
- Simplified
prepublishOnly
to run lint
only to avoid Windows publish issues
- Added Windows-friendly test scripts via
cross-env
v1.3.0 - ๐ Major Feature Release
- โก NEW: Schema Composer API - Fluent interface for building complex schemas
- ๐ญ NEW: Framework Integrations - React hooks, Vue composables, Svelte stores
- ๐ NEW: Industry Templates - Pre-built schemas for ecommerce, restaurants, healthcare, real estate, education, events, and content
- ๐ NEW: Enhanced Validation - Detailed error messages, warnings, suggestions, and quality scoring
- ๐ NEW: Analytics Integration - Track schema performance, Google Analytics integration, custom events
- ๐ฏ Improved Developer Experience - Better TypeScript support, more intuitive APIs
- ๐ Enhanced Documentation - Comprehensive examples and use cases
v1.2.0
- โจ Extended Schema Helpers (Product, Article, LocalBusiness, Event)
- โจ Multiple Schema Support
- โจ Server-Side Utilities (SSR/SSG)
- โจ Framework helpers (Next.js, Nuxt.js)
- โจ Comprehensive test suite with Vitest
- โจ Bundle optimization and tree-shaking improvements
- ๐ Enhanced documentation
v1.1.0
- โจ Enhanced schema validation
- โจ Improved browser detection
- โจ Debug logging utilities
- โจ Schema management functions
- ๐ Various bug fixes and improvements
v1.0.0
- ๐ Initial release
- โจ Basic FAQ schema injection
- โจ Zero dependencies
- โจ TypeScript support