Skip to main content

VelocitySDK

Constructor

new VelocitySDK(config: SDKConfig)
SDKConfig
PropertyTypeRequiredDefaultDescription
publisherKeystringYesYour unique publisher key from Velocity
timeoutnumberNo30000Request timeout in milliseconds
retriesnumberNo0Number of retry attempts (max 3)
loggerLoggerNoconsoleCustom logger implementation
sdkMode'development' | 'production'NoDevelopment mode returns mock ads. For local testing only

init()

Initializes the SDK and establishes a session. Must be called before fetchAd().
const result = await sdk.init(params?: InitParams): Promise<InitResponse>
InitParams
ParameterTypeRequiredDescription
publisherUserIdstringNoUnique identifier for the user
The SDK automatically detects and includes: user agent, language, country, viewport size, screen resolution, and timezone. Returns: InitResponse
type InitResponse =
  | {
      success: true;
      data: {
        sessionId: string;
        status: string;
        message: string;
      };
    }
  | {
      success: false;
      error: VelocitySDKError;
    };
Example
const initResult = await sdk.init({ publisherUserId: 'user-123' });

if (initResult.success) {
  console.log('Session ID:', initResult.data.sessionId);
} else {
  console.error('Init failed:', initResult.error.message);
}

fetchAd()

Fetches a contextual ad. SDK must be initialized first.
const result = await sdk.fetchAd(params: FetchAdParams): Promise<FetchAdResponse>
FetchAdParams
ParameterTypeRequiredDescription
promptstringYesUser’s query or prompt text
aiResponsestringYesAI-generated response text
dimensions{ width: number; height: number }YesAd container dimensions in pixels
adUnitIdstringNoOptional identifier for the ad placement
The SDK automatically includes: user ID and session ID from initialization, current timestamp, browser language and country. Returns: FetchAdResponse
type FetchAdResponse =
  | {
      success: true;
      data: {
        ads: Array<{
          network: string;
          bidPrice: number;
          adPayload: {
            id: string;
            title: string;
            description: string;
            callToAction: string;
            imageUrl: string;
            clickUrl: string;
            impressionUrl: string;
            category: string;
            tags: string[];
            reviewCount: number;
          };
        }>;
        auctionMetadata: {
          bids: Record<string, number>;
          timestamp: number;
          totalNetworks: number;
        };
      };
    }
  | {
      success: false;
      error: VelocitySDKError;
    };
Ads in data.ads are sorted by bidPrice descending — use ads[0] for the winning ad. Example
const adsResult = await sdk.fetchAd({
  prompt: 'best laptops for programming',
  aiResponse: 'Based on your needs, I recommend...',
  dimensions: { width: 728, height: 90 },
  adUnitId: 'sidebar-ad'
});

if (adsResult.success && adsResult.data.ads.length > 0) {
  const ad = adsResult.data.ads[0];
  console.log('Title:', ad.adPayload.title);
  console.log('Click URL:', ad.adPayload.clickUrl);
} else {
  console.error('No ads:', adsResult.success ? 'empty' : adsResult.error.message);
}

VelocitySDKError

All SDK errors are instances of VelocitySDKError.
PropertyTypeDescription
messagestringHuman-readable error description
codestringError code
statusCodenumber | undefinedHTTP status code, if applicable

Error Codes

CodeDescriptionWhen It Occurs
VALIDATION_ERRORInvalid parametersRequired parameters missing or invalid
AUTH_ERRORAuthentication failedpublisherKey invalid or unauthorized
CONFIG_ERRORSDK misconfiguredInvalid SDK configuration at init
NETWORK_ERRORNetwork failureRequest fails due to connectivity or timeout
AD_SERVER_ERRORServer errorAd server unavailable or unexpected error
Example
if (!initResult.success) {
  switch (initResult.error.code) {
    case 'AUTH_ERROR':
      console.error('Check your publisherKey');
      break;
    case 'NETWORK_ERROR':
      console.error('Network unavailable');
      break;
    default:
      console.error('SDK error:', initResult.error.message);
  }
}

Logger

Custom logger interface for SDK internals.
interface Logger {
  log(message: string): void;
  error(message: string): void;
  warn(message: string): void;
}
Example
const sdk = new VelocitySDK({
  publisherKey: 'YOUR_PUBLISHER_KEY',
  logger: {
    log: msg => console.log('[Velocity]', msg),
    error: msg => console.error('[Velocity]', msg),
    warn: msg => console.warn('[Velocity]', msg)
  }
});