Prerequisites
System Requirements
- Modern browser with ES2017+ support
- Node.js 16+ (for NPM usage)
Installation
The Velocity Ads Web SDK is available via NPM or CDN.
NPM
npm install @velocityio/web-sdk
yarn add @velocityio/web-sdk
pnpm add @velocityio/web-sdk
CDN
Include the script directly in your HTML:
<script src="https://cdn.vlcapi.net/web-sdk/v-0.5.0/velocity-sdk-0.5.0.min.js"></script>
SDK Initialization
Initialize the SDK once per session, typically on app load. The SDK must be initialized before fetching ads.
import { VelocitySDK } from '@velocityio/web-sdk';
const sdk = new VelocitySDK({
publisherKey: 'YOUR_PUBLISHER_KEY'
});
const initResult = await sdk.init({
publisherUserId: 'user-123' // Optional: user identifier
});
if (!initResult.success) {
console.error('Failed to initialize:', initResult.error.message);
}
Important:
- ⚠️ Initialize once per session
- ⚠️ Must be called before fetching any ads
The SDK automatically detects and includes the following browser parameters during initialization:
- User agent
- Language and country
- Viewport size and screen resolution
- Timezone
Fetching Ads
Use fetchAd() to retrieve a contextual ad after initialization.
const adsResult = await sdk.fetchAd({
prompt: 'What are the best running shoes?',
aiResponse: 'Here are some great running shoe options...',
dimensions: {
width: 300,
height: 250
},
adUnitId: 'ad_unit_123' // Optional
});
if (adsResult.success) {
const topAd = adsResult.data.ads[0];
renderAd(topAd);
} else {
console.error('Failed to fetch ads:', adsResult.error.message);
}
Ad Response
A successful fetchAd() returns an array of ads sorted by bid price (highest first). Each ad contains:
| Field | Description |
|---|
adPayload.title | Ad headline text |
adPayload.description | Ad body text |
adPayload.imageUrl | Product/service image URL |
adPayload.callToAction | CTA button text |
adPayload.clickUrl | Destination URL when ad is clicked |
adPayload.impressionUrl | URL to track impressions |
bidPrice | Winning bid price |
network | Ad network name |
Conversation History
For better ad targeting in chat applications, the SDK uses the prompt and aiResponse fields as conversational context. Pass the current turn’s prompt and AI response on each call:
// First call
await sdk.fetchAd({
prompt: 'What are the best running shoes?',
aiResponse: 'Here are some great running shoe options...',
dimensions: { width: 300, height: 250 }
});
// Subsequent calls — pass the latest prompt and response
await sdk.fetchAd({
prompt: 'Which ones are best for marathons?',
aiResponse: 'For marathons, I recommend...',
dimensions: { width: 300, height: 250 }
});
Providing accurate prompt and aiResponse values improves contextual ad targeting and revenue.
Rendering Ads
The fetchAd() response includes all data needed to display ads. Use clickUrl to make the ad clickable.
Basic Rendering
function renderAd(ad) {
const container = document.getElementById('ad-container');
const adLink = document.createElement('a');
adLink.href = ad.adPayload.clickUrl;
adLink.target = '_blank';
adLink.rel = 'noopener noreferrer';
adLink.style.display = 'block';
adLink.style.textDecoration = 'none';
adLink.innerHTML = `
<div style="border: 1px solid #ddd; padding: 16px; border-radius: 8px;">
<img
src="${ad.adPayload.imageUrl}"
alt="${ad.adPayload.title}"
style="width: 100%; height: 200px; object-fit: cover; border-radius: 4px;"
/>
<h3 style="margin: 8px 0 4px;">${ad.adPayload.title}</h3>
<p style="margin: 0 0 8px; color: #555;">${ad.adPayload.description}</p>
<span style="font-weight: bold;">${ad.adPayload.callToAction}</span>
</div>
`;
container.appendChild(adLink);
}
React Example
import { VelocitySDK } from '@velocityio/web-sdk';
import { useState, useEffect } from 'react';
function AdComponent() {
const [ads, setAds] = useState([]);
useEffect(() => {
const sdk = new VelocitySDK({ publisherKey: 'YOUR_PUBLISHER_KEY' });
async function loadAds() {
const initResult = await sdk.init({ publisherUserId: 'user-123' });
if (!initResult.success) return;
const adsResult = await sdk.fetchAd({
prompt: 'search query',
aiResponse: 'AI response',
dimensions: { width: 300, height: 250 }
});
if (adsResult.success) {
setAds(adsResult.data.ads);
}
}
loadAds();
}, []);
return (
<div>
{ads.map((ad, index) => (
<a
key={index}
href={ad.adPayload.clickUrl}
target="_blank"
rel="noopener noreferrer"
>
<img src={ad.adPayload.imageUrl} alt={ad.adPayload.title} />
<h3>{ad.adPayload.title}</h3>
<p>{ad.adPayload.description}</p>
<span>{ad.adPayload.callToAction}</span>
</a>
))}
</div>
);
}
Ad Load Example
This example shows a full integration in a chat application:
import { VelocitySDK } from '@velocityio/web-sdk';
const sdk = new VelocitySDK({ publisherKey: 'YOUR_PUBLISHER_KEY' });
async function initializeSDK() {
const result = await sdk.init({ publisherUserId: 'user-123' });
if (!result.success) {
console.error('SDK init failed:', result.error.message);
}
}
async function onUserMessage(prompt: string, aiResponse: string) {
// Display AI response in chat UI
displayMessage(aiResponse);
// Load contextual ad
const adsResult = await sdk.fetchAd({
prompt,
aiResponse,
dimensions: {
width: document.getElementById('ad-container').offsetWidth,
height: 250
}
});
if (adsResult.success && adsResult.data.ads.length > 0) {
renderAd(adsResult.data.ads[0]);
} else {
// Continue without ad
console.error('Ad load failed:', adsResult.success ? 'No ads available' : adsResult.error.message);
}
}
initializeSDK();
Key Points
- Initialize the SDK once at app load
- Pass the current prompt and AI response on each
fetchAd() call
- Handle errors gracefully by continuing without ads
- Use
ads[0] — ads are sorted by bid price (highest first)