@thead-vantage/react
v2.26.0
Published
React components and utilities for TheAd Vantage ad platform integration
Downloads
2,814
Maintainers
Readme
TheAd Vantage React Library
This is a Next.js project that integrates with TheAd Vantage platform for ad serving. The integration supports three distinct development modes to accommodate different development and production scenarios.
Getting Started
First, run the development server:
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun devOpen http://localhost:3000 with your browser to see the result.
This project uses next/font to automatically optimize and load Geist, a new font family for Vercel.
TheAd Vantage Integration - Development Modes
The TheAd Vantage integration supports multiple modes of operation to accommodate different development and production scenarios:
1. Production Mode (Default)
Use Case: Platform developers using the component in production deployments.
Behavior:
- Connects to
https://www.thead-vantage.com/api/ads(uses www to avoid 308 redirects) - Full tracking enabled (impressions and clicks are recorded)
- No configuration required
Configuration: None needed - this is the default behavior for production deployments.
Example Usage:
import { AdBanner } from '@/components/AdBanner';
export default function MyPage() {
return (
<AdBanner
platformId="10"
apiKey="your-api-key-here"
size="leaderboard"
/>
);
}2. Localhost Development Mode (Automatic)
Use Case: Platform developers testing locally on localhost (any port).
Behavior:
- Automatically detected when running on
localhost(e.g.,localhost:3000,localhost:3001, etc.) - Connects to
https://thead-vantage.com/api/ads(production API) - Dev flags automatically added:
dev_mode=true,no_track=true,no_click_track=true - No tracking: Impressions and clicks are NOT recorded (prevents polluting production data)
- Perfect for platform developers testing locally without affecting production metrics
Configuration: No configuration needed! The library automatically detects localhost and adds dev flags.
Note: This mode is automatically used when:
- Running on
localhostor127.0.0.1(any port) - AND
NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODEis NOT set totrue
3. Platform Developer Custom API Mode
Use Case: Platform developers testing with their own custom platform instance.
Behavior:
- Connects to a custom API URL (your platform's API endpoint)
- Full tracking enabled (impressions and clicks are recorded)
- Allows testing with your own platform without affecting production
Configuration: Set the NEXT_PUBLIC_THEAD_VANTAGE_API_URL environment variable in .env.local:
# .env.local
NEXT_PUBLIC_THEAD_VANTAGE_API_URL=https://your-platform.com/api/adsExample Usage:
// Option 1: Use environment variable (recommended)
<AdBanner
platformId="10"
apiKey="your-api-key"
size="leaderboard"
/>
// Option 2: Override directly in component
<AdBanner
platformId="10"
apiKey="your-api-key"
size="leaderboard"
apiUrl="https://your-platform.com/api/ads"
/>4. TheAd Vantage Dev Mode
Use Case: TheAd Vantage developers testing the component with a local platform instance running on localhost:3001.
Behavior:
- Connects to
http://localhost:3001/api/ads(local TheAd Vantage platform) - Tracking disabled (impressions and clicks are NOT recorded)
- Returns mock data if local platform is unavailable
- Shows dev mode indicators in the UI
Configuration: Set the NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE environment variable in .env.local:
# .env.local
NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=trueExample Usage:
// Automatically uses localhost:3001 when dev mode is enabled
<AdBanner
platformId="10"
apiKey="your-api-key"
size="leaderboard"
/>Important: This mode overrides localhost detection. When NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=true, the library will always use localhost:3001 instead of the production API, even if you're running on localhost.
Component API
AdBanner Component
The main component for displaying ads from TheAd Vantage.
Props:
| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| platformId | string | Yes | - | Your platform ID from TheAd Vantage |
| apiKey | string | Yes | - | Your API key from TheAd Vantage |
| size | 'leaderboard' \| 'medium-rectangle' \| 'wide-skyscraper' \| 'banner' | No | 'banner' | Ad size specification |
| apiUrl | string | No | - | Override API endpoint URL (highest priority) |
| userId | string \| null | No | null | User ID for ad targeting |
| userSegment | string \| null | No | null | User segment for ad targeting |
| className | string | No | '' | Additional CSS classes |
| clickMetadata | Record<string, unknown> | No | - | Optional metadata to send with click tracking events |
| impressionMetadata | Record<string, unknown> | No | - | Optional metadata to send with impression tracking events |
| showImpressionFinished | boolean | No | false | Show spinning checkmark during impression timer (2s), then green checkmark when complete |
| development | boolean | No | false | Explicitly enable development mode (disables tracking, handles CORS errors gracefully) |
Example:
import { AdBanner } from '@/components/AdBanner';
export default function ArticlePage() {
const userData = {
id: 'user-123',
email: '[email protected]',
school: 'University of Example',
grade: 'Senior',
major: 'Computer Science',
role: 'student',
};
return (
<div>
<article>
<h1>My Article</h1>
<p>Article content...</p>
</article>
<aside>
<AdBanner
platformId="10"
apiKey="abc123xyz"
size="medium-rectangle"
userId={userData.id}
userSegment="premium"
className="my-4"
clickMetadata={{
userId: userData.id,
email: userData.email,
school: userData.school,
grade: userData.grade,
major: userData.major,
role: userData.role,
}}
impressionMetadata={{
userId: userData.id,
email: userData.email,
school: userData.school,
grade: userData.grade,
major: userData.major,
role: userData.role,
}}
showImpressionFinished={true}
/>
</aside>
</div>
);
}Metadata Tracking
The AdBanner component supports optional metadata that is sent with click and impression tracking events. This allows you to pass additional context about the user or session to TheAd Vantage for analytics purposes.
Metadata Props:
clickMetadata: Optional object with key-value pairs sent with click eventsimpressionMetadata: Optional object with key-value pairs sent with impression events
Example with Metadata:
<AdBanner
platformId="10"
apiKey="abc123xyz"
size="medium-rectangle"
clickMetadata={{
userId: userData?.id,
email: userData?.email,
school: userData?.school,
grade: userData?.grade,
major: userData?.major,
role: userData?.role,
}}
impressionMetadata={{
userId: userData?.id,
email: userData?.email,
school: userData?.school,
grade: userData?.grade,
major: userData?.major,
role: userData?.role,
}}
/>Note: The metadata is sent to the /api/ads/track endpoint on thead-vantage.com. Ensure the API has been updated to support receiving metadata (see other/thead-vantage-api-metadata-prompt.md for implementation details).
Impression Finished Indicator
The showImpressionFinished prop enables a visual indicator that shows when an impression has been recorded:
- Spinning Checkmark: A gray spinning checkmark appears in the top-right corner of the ad during the 2-second impression timer
- Green Checkmark: After 2 seconds, the checkmark turns green to indicate the impression has been recorded
Example:
<AdBanner
platformId="10"
apiKey="abc123xyz"
size="banner"
showImpressionFinished={true}
/>This feature is useful for debugging and providing visual feedback that impressions are being tracked correctly.
Development Mode
The development prop explicitly enables development mode, which:
- Disables tracking: Impressions and clicks are not recorded (even if the API call succeeds)
- Handles CORS gracefully: CORS errors are logged as warnings instead of breaking the component
- Prevents error display: Network errors don't show error messages to users in development mode
Use Case: When developing locally and you can't configure CORS for localhost, use this prop to prevent CORS errors from breaking your development workflow.
Example:
<AdBanner
platformId="10"
apiKey="abc123xyz"
size="banner"
development={process.env.NODE_ENV === 'development'}
/>Note: When development={true}, the component will:
- Automatically skip all tracking (impressions and clicks)
- Log CORS errors as warnings instead of throwing errors
- Continue to work even if the API is unreachable (won't show error state)
Utility Functions
You can also use the utility functions directly:
import { fetchAdBanner, trackImpression, trackClick, collectFingerprint } from '@/lib/ads';
// Fetch an ad
const response = await fetchAdBanner({
platformId: '10',
apiKey: 'your-api-key',
size: 'leaderboard',
userId: 'user-123',
userSegment: 'premium',
});
// Track events (automatically skipped in TheAd Vantage dev mode)
// Note: trackImpression and trackClick now require apiKey parameter
// They automatically include client fingerprinting data for fraud detection
// Optional metadata can be passed as the last parameter
trackImpression(adId, apiKey, apiUrl, {
userId: 'user-123',
email: '[email protected]',
school: 'University of Example',
});
trackClick(adId, apiKey, apiUrl, {
userId: 'user-123',
email: '[email protected]',
});
// You can also collect fingerprint data manually if needed
const fingerprint = collectFingerprint();
console.log('Client fingerprint:', fingerprint);Environment Variables
For Platform Developers
No environment variables needed for localhost development! The library automatically detects localhost and uses the production API with dev flags (no tracking).
Optional: If you want to test with a custom platform instance:
# .env.local
# Point to your own platform instance (full tracking enabled)
NEXT_PUBLIC_THEAD_VANTAGE_API_URL=https://your-platform.com/api/adsFor TheAd Vantage Developers
# .env.local
# Enable TheAd Vantage dev mode (uses localhost:3001, disables tracking)
# This overrides localhost detection and always uses localhost:3001
NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=trueSummary Table
| Scenario | API Endpoint | Tracking | Configuration |
|----------|-------------|----------|--------------|
| Production deployment | https://thead-vantage.com/api/ads | ✅ Enabled | None (default) |
| Platform dev on localhost | https://thead-vantage.com/api/ads | ❌ Disabled (dev flags) | None (auto-detected) |
| Custom platform URL | Custom URL | ✅ Enabled | NEXT_PUBLIC_THEAD_VANTAGE_API_URL |
| TheAd Vantage dev | localhost:3001/api/ads | ❌ Disabled | NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=true |
Priority Order (highest to lowest):
- Explicit
apiUrlprop in component (highest priority) NEXT_PUBLIC_THEAD_VANTAGE_API_URLenvironment variable (custom platform)NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=true→ useslocalhost:3001(TheAd Vantage developers)- Localhost detection → uses
https://thead-vantage.com/api/adswith dev flags (platform developers on localhost) - Production mode (default:
https://thead-vantage.com/api/adswith full tracking)
API Routes
The integration includes Next.js API routes that proxy requests to TheAd Vantage:
GET /api/ads- Fetches ads from TheAd Vantage platform- Automatically handles all three modes
- Adds
dev_mode,no_track, andno_click_trackparameters in dev mode - Returns mock data if platform is unavailable in TheAd Vantage dev mode
POST /api/ads- Tracks ad impressions/clicks- Automatically skipped in TheAd Vantage dev mode
- Logs dev mode messages when tracking is skipped
Development Mode Features
Localhost Development (Automatic)
When running on localhost (any port, without NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=true):
- ✅ Production API: Connects to
https://thead-vantage.com/api/ads - ✅ No Tracking: Dev flags automatically added (
dev_mode=true,no_track=true,no_click_track=true) - ✅ Real Ads: Gets real ads from production (but doesn't record impressions/clicks)
- ✅ No Configuration: Automatically detected - no setup needed!
TheAd Vantage Dev Mode
When NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=true:
- ✅ Local API: Connects to
http://localhost:3001/api/ads - ✅ No Tracking: Impressions and clicks are NOT recorded
- ✅ Mock Fallback: If localhost:3001 is unavailable, uses mock ad data
- ✅ Dev Indicators: UI shows "[DEV] No tracking active" message
- ✅ Console Logging: Dev mode actions are logged to console
- ✅ Error Resilience: Connection failures won't break your development workflow
Learn More
To learn more about Next.js, take a look at the following resources:
- Next.js Documentation - learn about Next.js features and API.
- Learn Next.js - an interactive Next.js tutorial.
You can check out the Next.js GitHub repository - your feedback and contributions are welcome!
Deploy on Vercel
The easiest way to deploy your Next.js app is to use the Vercel Platform from the creators of Next.js.
Check out our Next.js deployment documentation for more details.
AI Agent Implementation Guide
For AI Agents (Cursor, GitHub Copilot, etc.): This section provides comprehensive instructions for implementing and using TheAd Vantage integration in this codebase.
System Architecture
The TheAd Vantage integration uses a smart mode detection system to support different development scenarios:
- Production Mode: Default behavior, connects to
https://thead-vantage.com/api/adswith full tracking - Localhost Development: Automatically detected, uses
https://thead-vantage.com/api/adswith dev flags (no tracking) - Custom Platform Mode: Custom API URL via
NEXT_PUBLIC_THEAD_VANTAGE_API_URLenv var - TheAd Vantage Dev Mode: Local development via
NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=trueenv var → useslocalhost:3001
Key Files and Their Purposes
Configuration
src/lib/thead-vantage-config.ts: Core configuration utility that determines API URL based on mode prioritygetApiBaseUrl(explicitApiUrl?): Returns the appropriate API base URLisTheadVantageDevMode(): Checks if TheAd Vantage dev mode is activesetTheadVantageConfig(config): Runtime configuration for browser contexts
API Routes
src/app/api/ads/route.ts: Next.js API route that proxies requests to TheAd VantageGET /api/ads: Fetches ads, handles all three modes, adds dev flags when neededPOST /api/ads: Tracks impressions/clicks, skips tracking in dev mode
Components
src/components/AdBanner.tsx: Main React component for displaying ads- Props:
platformId,apiKey,size,apiUrl?,userId?,userSegment?,className?,clickMetadata?,impressionMetadata?,showImpressionFinished? - Automatically handles loading, error states, and dev mode indicators
- Supports optional metadata for click and impression tracking
- Optional impression finished indicator (spinning checkmark → green checkmark)
- Props:
Utilities
src/lib/ads.ts: Utility functions for fetching and tracking adsfetchAdBanner(params): Fetches ads with full parameter supporttrackImpression(adId, apiKey, apiUrl?, metadata?): Tracks ad impressions with fingerprinting and optional metadata (skipped in dev mode)trackClick(adId, apiKey, apiUrl?, metadata?): Tracks ad clicks with fingerprinting and optional metadata (skipped in dev mode)collectFingerprint(): Collects client fingerprinting data for fraud detection
Implementation Instructions for AI Agents
When Adding TheAd Vantage Integration to a New Component
Import the AdBanner component:
import { AdBanner } from '@/components/AdBanner';Use the component with required props:
<AdBanner platformId="10" apiKey="your-api-key" size="leaderboard" />For platform developers using custom API: Ensure they set
NEXT_PUBLIC_THEAD_VANTAGE_API_URLin.env.localFor TheAd Vantage developers: Ensure they set
NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=truein.env.local
When Debugging Ad Loading Issues
- Check environment variables: Verify
.env.localhas correct configuration - Check console logs: Look for
[AdBanner]prefixed messages - Verify API URL resolution: The
getApiBaseUrl()function logs which mode is active - Check network tab: Verify requests are going to the correct endpoint
When Implementing Custom Ad Fetching
- Use
fetchAdBanner()utility instead of direct fetch calls - Pass
apiUrlparameter if you need to override the default - Handle
dev_modeflag in response to show appropriate UI indicators - Use
trackImpression()andtrackClick()for tracking (automatically skipped in dev mode)
Mode Detection Priority (Important for AI Agents)
The system uses this priority order to determine which API URL to use:
- Explicit
apiUrlprop (highest priority) - passed directly to component NEXT_PUBLIC_THEAD_VANTAGE_API_URLenv var - for platform developers using custom platformNEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=true- for TheAd Vantage developers (useslocalhost:3001)- Localhost detection - automatically uses
https://thead-vantage.com/api/adswith dev flags (no tracking) - Production mode (lowest priority) - default:
https://thead-vantage.com/api/adswith full tracking
Key Points for AI Agents:
- Localhost is automatically detected by checking
window.location.hostname(browser) orNODE_ENV === 'development'(server) - When on localhost, dev flags (
dev_mode,no_track,no_click_track) are automatically added to requests - TheAd Vantage dev mode (
NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=true) overrides localhost detection - Platform developers on localhost get real ads from production but don't pollute tracking data
Common Patterns
Pattern 1: Basic Ad Display
<AdBanner platformId="10" apiKey="key" size="banner" />Pattern 2: Ad with User Targeting
<AdBanner
platformId="10"
apiKey="key"
size="leaderboard"
userId={user?.id}
userSegment={user?.segment}
/>Pattern 3: Ad with Metadata Tracking
<AdBanner
platformId="10"
apiKey="key"
size="medium-rectangle"
clickMetadata={{
userId: userData?.id,
email: userData?.email,
school: userData?.school,
grade: userData?.grade,
}}
impressionMetadata={{
userId: userData?.id,
email: userData?.email,
school: userData?.school,
grade: userData?.grade,
}}
/>Pattern 4: Ad with Impression Finished Indicator
<AdBanner
platformId="10"
apiKey="key"
size="banner"
showImpressionFinished={true}
/>Pattern 5: Custom API URL Override
<AdBanner
platformId="10"
apiKey="key"
size="banner"
apiUrl="https://custom-api.com/ads"
/>Pattern 6: Programmatic Ad Fetching
const response = await fetchAdBanner({
platformId: '10',
apiKey: 'key',
size: 'medium-rectangle',
apiUrl: customUrl, // Optional override
});Error Handling
- The component automatically handles loading and error states
- In TheAd Vantage dev mode, connection failures return mock data instead of errors
- Tracking failures are logged but don't throw errors (non-blocking)
Testing Checklist for AI Agents
When implementing or modifying TheAd Vantage integration:
- [ ] Verify production mode connects to
https://thead-vantage.com/api/adswith full tracking - [ ] Verify localhost detection automatically uses production API with dev flags (no tracking)
- [ ] Verify platform dev mode respects
NEXT_PUBLIC_THEAD_VANTAGE_API_URL - [ ] Verify TheAd Vantage dev mode uses
localhost:3001when flag is set (overrides localhost detection) - [ ] Verify tracking is disabled when on localhost (dev flags added automatically)
- [ ] Verify tracking is disabled in TheAd Vantage dev mode
- [ ] Verify mock data is returned when platform is unavailable in TheAd Vantage dev mode
- [ ] Verify explicit
apiUrlprop overrides all other settings - [ ] Verify component handles loading states correctly
- [ ] Verify component handles error states gracefully
- [ ] Verify dev mode indicators show in UI when appropriate
Environment Variable Reference
# Platform Developer Dev Mode
NEXT_PUBLIC_THEAD_VANTAGE_API_URL=https://your-platform.com/api/ads
# TheAd Vantage Dev Mode
NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=trueTypeScript Types
Key types for reference:
AdBannerProps: Component props interfaceAd: Ad data structureAdsResponse: API response structureFetchAdBannerParams: Parameters forfetchAdBanner()function
All types are exported from @/lib/ads and @/components/AdBanner.
Quick Reference
For Platform Developers
Default Behavior:
- Production: Connects to
https://thead-vantage.com/api/adswith full tracking - Localhost: Automatically uses
https://thead-vantage.com/api/adswith dev flags (no tracking) - no configuration needed!
Optional Custom Platform: Add NEXT_PUBLIC_THEAD_VANTAGE_API_URL to .env.local if testing with custom platform
Component Import:
import { AdBanner } from '@thead-vantage/react';
// or
import { AdBanner } from '@thead-vantage/react/components/AdBanner';Utility Import:
import { fetchAdBanner, trackImpression, trackClick } from '@thead-vantage/react';
// or
import { fetchAdBanner, trackImpression, trackClick } from '@thead-vantage/react/lib/ads';For TheAd Vantage Developers
Setup: Add NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=true to .env.local
Behavior: Uses localhost:3001/api/ads (overrides localhost detection)
Common Scenarios
| You Are | Running On | API Used | Tracking | Config Needed |
|---------|-----------|----------|----------|---------------|
| Platform Developer | Production | thead-vantage.com | ✅ Yes | None |
| Platform Developer | localhost:3000 | thead-vantage.com | ❌ No (dev flags) | None (auto) |
| Platform Developer | Custom platform | Custom URL | ✅ Yes | NEXT_PUBLIC_THEAD_VANTAGE_API_URL |
| TheAd Vantage Dev | localhost:3000 | localhost:3001 | ❌ No | NEXT_PUBLIC_THEAD_VANTAGE_DEV_MODE=true |
CORS Configuration for Production
Important: The thead-vantage.com server needs to be configured to allow CORS requests from registered production platforms.
For Platform Developers
When deploying your platform to production:
- Contact TheAd Vantage support to register your production domain(s)
- Provide your production URLs (e.g.,
https://minotsbugle.com,https://www.minotsbugle.com) - Verify CORS is working by checking browser console for CORS errors
The TheAd Vantage team will add your domains to the allowed origins list for your platform's API key.
For TheAd Vantage Platform Developers
See CORS_CONFIGURATION.md for:
- Database schema for storing allowed origins per platform
- CORS middleware implementation examples
- Security best practices
- Testing procedures
The CORS system allows each platform to have multiple allowed origins stored in the database, and the middleware validates requests against these origins before setting CORS headers.
