JavaScript/Node.js SDK
Official JavaScript SDK for SearchHive APIs. Works seamlessly in Node.js, browsers, and edge runtime environments with full TypeScript support.
Latest Version Available
Quick Start
1. Installation
Install SearchHive JavaScript SDK
2. Basic Usage
Your First Search Request
import { SearchHive } from 'searchhive-js';
// Initialize the client
const client = new SearchHive({
apiKey: 'sk_live_your_key_here',
baseURL: 'https://www.searchhive.dev/api/v1', // optional
timeout: 30000, // optional, default 30s
retries: 3 // optional, default 3
});
// Basic search
async function basicSearch() {
try {
const result = await client.search({
query: 'latest AI developments 2025',
maxResults: 10
});
console.log(`Found ${result.searchResults.length} results`);
console.log(`Credits used: ${result.creditsUsed}`);
result.searchResults.forEach((item, index) => {
console.log(`${index + 1}. ${item.title}`);
console.log(` URL: ${item.link}`);
console.log(` Snippet: ${item.snippet}`);
});
} catch (error) {
console.error('Search failed:', error.message);
}
}
Key Features
Built with modern JavaScript, optimized for speed and efficiency
Full TypeScript support with comprehensive type definitions
Intuitive API design with extensive error handling and debugging
Works in Node.js, browsers, and edge runtime environments
Core Methods
Method | Description | Returns |
---|---|---|
search(options) | Perform real-time web search with automatic result extraction | Promise<SearchResponse> |
scrape(options) | Extract content from single webpage with advanced parsing | Promise<ScrapeResponse> |
scrapeBulk(options) | Scrape multiple URLs concurrently with progress tracking | Promise<ScrapeResponse[]> |
research(options) | AI-powered research across multiple sources with summarization | Promise<ResearchResponse> |
getUsage() | Get current API usage statistics and remaining credits | Promise<UsageResponse> |
validateKey() | Validate API key and check account status | Promise<boolean> |
Web Scraping Examples
Extract content from any webpage with advanced parsing and bulk operations:
Web Scraping and Bulk Operations
// Scrape webpage content
async function scrapeWebpage() {
try {
const result = await client.scrape({
url: 'https://example.com/article',
extractOptions: ['title', 'text', 'links', 'images'],
followRedirects: true,
waitForSelector: '.content', // optional
removeSelectors: ['.ads', '.popup'] // optional
});
console.log('Page title:', result.primaryContent.title);
console.log('Content length:', result.primaryContent.text.length);
console.log('Found links:', result.extractedData.links.length);
console.log('Found images:', result.extractedData.images.length);
} catch (error) {
console.error('Scraping failed:', error.message);
}
}
// Bulk scraping
async function bulkScrape() {
const urls = [
'https://example.com/page1',
'https://example.com/page2',
'https://example.com/page3'
];
try {
const results = await client.scrapeBulk({
urls: urls,
extractOptions: ['title', 'text'],
concurrent: 2 // Process 2 URLs at once
});
results.forEach((result, index) => {
if (result.success) {
console.log(`${urls[index]}: ${result.data.primaryContent.title}`);
} else {
console.error(`${urls[index]} failed: ${result.error}`);
}
});
} catch (error) {
console.error('Bulk scraping failed:', error.message);
}
}
AI-Powered Research
Leverage AI to research topics across multiple sources with automatic summarization:
DeepDive Research API
// AI-powered research
async function researchTopic() {
try {
const result = await client.research({
topic: 'sustainable energy solutions 2025',
maxSources: 10,
includeImages: true,
language: 'en'
});
console.log('Research summary:');
console.log(result.summary);
console.log('\nKey insights:');
result.keyInsights.forEach((insight, index) => {
console.log(`${index + 1}. ${insight}`);
});
console.log('\nSources analyzed:');
result.sources.forEach((source, index) => {
console.log(`${index + 1}. ${source.title}`);
console.log(` URL: ${source.url}`);
console.log(` Credibility: ${source.credibilityScore}`);
});
} catch (error) {
console.error('Research failed:', error.message);
}
}
Advanced Configuration
Customize the SDK behavior with advanced configuration options:
Advanced SDK Configuration
import { SearchHive } from 'searchhive-js';
// Advanced configuration
const client = new SearchHive({
apiKey: process.env.SEARCHHIVE_API_KEY,
// Network settings
timeout: 60000, // 60 second timeout
retries: 5, // Retry up to 5 times
retryDelay: 1000, // Start with 1 second delay
// Rate limiting
rateLimit: {
requestsPerMinute: 100,
burstLimit: 10
},
// Custom headers
headers: {
'User-Agent': 'MyApp/1.0.0',
'X-Custom-Header': 'value'
},
// Proxy support
proxy: {
host: 'proxy.example.com',
port: 8080,
auth: {
username: 'user',
password: 'pass'
}
},
// Response customization
responseFormat: 'detailed', // 'simple' or 'detailed'
// Error handling
throwOnError: true, // Default: true
// Logging
debug: process.env.NODE_ENV === 'development'
});
// Override settings per request
const result = await client.search({
query: 'test query',
maxResults: 5
}, {
timeout: 10000, // Override timeout for this request
retries: 1 // Override retries for this request
});
Error Handling
Robust error handling with specific exception types and retry logic:
Comprehensive Error Handling
import {
SearchHiveError,
RateLimitError,
AuthenticationError,
InsufficientCreditsError
} from 'searchhive-js';
async function robustApiCall() {
try {
const result = await client.search({
query: 'example query',
maxResults: 10
});
return result;
} catch (error) {
if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter} seconds`);
// Wait and retry
await new Promise(resolve =>
setTimeout(resolve, error.retryAfter * 1000)
);
return robustApiCall(); // Recursive retry
} else if (error instanceof AuthenticationError) {
console.error('Authentication failed. Check your API key.');
throw error;
} else if (error instanceof InsufficientCreditsError) {
console.error('No credits remaining. Upgrade your plan.');
throw error;
} else if (error instanceof SearchHiveError) {
console.error(`API error (${error.statusCode}): ${error.message}`);
// Log additional context
console.error('Request ID:', error.requestId);
console.error('Response:', error.response);
throw error;
} else {
console.error('Unexpected error:', error);
throw error;
}
}
}
TypeScript Support
Full TypeScript support with comprehensive type definitions:
TypeScript Integration
// TypeScript support with full type definitions
import {
SearchHive,
SearchResponse,
ScrapeResponse,
ResearchResponse,
SearchOptions,
ScrapeOptions,
ResearchOptions
} from 'searchhive-js';
const client = new SearchHive({
apiKey: process.env.SEARCHHIVE_API_KEY!
});
// Typed search function
async function typedSearch(options: SearchOptions): Promise<SearchResponse> {
return await client.search(options);
}
// Interface for custom result processing
interface ProcessedResult {
title: string;
url: string;
summary: string;
relevanceScore: number;
}
async function processSearchResults(query: string): Promise<ProcessedResult[]> {
const response: SearchResponse = await client.search({
query,
maxResults: 20
});
return response.searchResults.map((result): ProcessedResult => ({
title: result.title,
url: result.link,
summary: result.snippet,
relevanceScore: result.relevanceScore ?? 0
}));
}
// Generic function with constraints
async function performOperation<T extends SearchOptions | ScrapeOptions>(
operation: 'search' | 'scrape',
options: T
): Promise<T extends SearchOptions ? SearchResponse : ScrapeResponse> {
if (operation === 'search') {
return client.search(options as SearchOptions) as any;
} else {
return client.scrape(options as ScrapeOptions) as any;
}
}
Advanced Features
Streaming & Progress Tracking
Real-time Streaming and Progress
// Streaming responses (Enterprise feature)
async function streamingSearch() {
try {
const stream = await client.searchStream({
query: 'real-time news updates',
maxResults: 50,
stream: true
});
// Handle streaming data
stream.on('data', (chunk) => {
console.log('Received result:', chunk.result);
});
stream.on('error', (error) => {
console.error('Stream error:', error);
});
stream.on('end', () => {
console.log('Stream completed');
});
} catch (error) {
console.error('Streaming failed:', error.message);
}
}
// Progress tracking for large operations
async function trackProgress() {
const urls = Array.from({length: 100}, (_, i) =>
`https://example.com/page${i + 1}`
);
const results = await client.scrapeBulk({
urls: urls,
extractOptions: ['title', 'text'],
concurrent: 5,
onProgress: (completed, total) => {
const percent = Math.round((completed / total) * 100);
console.log(`Progress: ${percent}% (${completed}/${total})`);
}
});
console.log('Bulk operation completed:', results.length);
}
Custom Middleware
Request/Response Middleware
// Custom middleware for request/response processing
client.use('request', async (config) => {
// Add custom authentication
config.headers['X-Custom-Auth'] = generateCustomAuth();
// Log outgoing requests
console.log(`Making request to ${config.url}`);
return config;
});
client.use('response', async (response) => {
// Log response times
console.log(`Request took ${response.timing.total}ms`);
// Transform response data
if (response.data.searchResults) {
response.data.searchResults = response.data.searchResults.map(result => ({
...result,
processedAt: new Date().toISOString()
}));
}
return response;
});
client.use('error', async (error) => {
// Custom error logging
console.error('API Error:', {
status: error.statusCode,
message: error.message,
requestId: error.requestId,
timestamp: new Date().toISOString()
});
// Don't modify the error, just log it
return error;
});
Environment Support
Full support for Node.js 14+ with native modules and filesystem access.
- • Express/Fastify integration
- • File system operations
- • Native HTTP client
- • Environment variables
Works in modern browsers with CORS support and fetch API.
- • React/Vue/Angular apps
- • Webpack/Vite bundling
- • Progressive Web Apps
- • Service Workers
Optimized for edge computing platforms and serverless functions.
- • Vercel Edge Functions
- • Cloudflare Workers
- • AWS Lambda@Edge
- • Deno Deploy