Skip to content
ad-platform

JavaScript SDK

The Topsort JavaScript SDK is the official client library to integrate with Topsort’s auction and event tracking APIs. Built in TypeScript, this SDK simplifies the integration, allowing the creation of an end-to-end flow in minutes.

How it Works

You can install the library using npm or yarn, or load the SDK directly in your HTML file by including a <script> tag:

<script async type="module" src="https://unpkg.com/@topsort/sdk@latest/dist/index.mjs"></script>
<script>
// Global configuration for Topsort
window.TS = {
token: "TSE_XXXXXXXXXXXX" // Replace with your Topsort API key
};
</script>

Creating an Auction

Once you have the SDK available (via npm or unpkg), you can initialize a client and create an auction. For example:

import { TopsortClient } from "https://unpkg.com/@topsort/sdk@latest/dist/index.mjs";
// For npm installations, use: import { TopsortClient } from "@topsort/sdk";
const topsortClient = new TopsortClient({ apiKey: window.TS.token });
const auctionDetails = {
auctions: [
{
type: "listings", // For product listings
slots: 3,
// Use a search query or category targeting to retrieve winners
searchQuery: "winter"
},
{
type: "banners", // For banner ads
slots: 1,
device: "desktop",
slotId: "slot123"
}
],
};
topsortClient.createAuction(auctionDetails)
.then(result => console.log("Auction Result", result))
.catch(error => console.error("Auction Error", error));

This example sends an auction request for both listings and banners.

Sample response

These are typical 200 and 400 responses for the auction call:

200:

{
"results": [
{
"resultType": "listings",
"winners": [
{
"rank": 1,
"type": "product",
"id": "24-MG03",
"resolvedBidId": "ChAGf9V-tPN3_a4ECXDMEzPrEhBbDgqxTDRL5rZF-059khwLGhAGQSBhleFxoaQkWgDwxTQeIgsKBzI0LU1HMDMQATD72AE",
"campaignId": "5b0e0ab1-4c34-4be6-b645-fb4e7d921c0b"
}
],
"error": false
},
{
"resultType": "banners",
"winners": [
{
"rank": 1,
"asset": [
{
"url": "https://topsortassets.com/asset_01jrtrsxc7fe5vef6b7etd3t82.png"
}
],
"type": "vendor",
"id": "1",
"resolvedBidId": "ChAGf9V-tPJ-KpYECW_MEzPrEhABljWNEN1xcqsgjpFkr-IRGhAGQHZZomFz9LwkmzXwxTQeIgUKATEQAzDx2AE",
"vendorId": "1",
"campaignId": "0196358d-10dd-7172-ab20-8e9164afe211"
}
],
"error": false
}
]
}

400:

{
"status": 400,
"statusText": "No Content",
"body": {
"errCode": "bad_request",
"docUrl": "https://docs.topsort.com/reference/errors",
"message": "The request could not be parsed."
}
}

Reporting an Event

After you receive auction results, you can report events (such as user impressions or clicks). Here’s an example that sends impression events for all auction winners. For this example, the id of the impression and the opaqueUserID are autogenerated. Check the API documentation for more details.

// Assume auctionResult is the response from createAuction:
const winners = auctionResult.results.flatMap(result => result.winners || []);
if (winners.length > 0) {
const impressions = winners.map(winner => ({
resolvedBidId: winner.resolvedBidId,
// Auto-generate a unique event ID and opaque user ID
id: crypto.randomUUID(),
occurredAt: new Date().toISOString(),
opaqueUserId: crypto.randomUUID(),
placement: { path: "/search/winter" }
}));
const eventPayload = { impressions };
topsortClient.reportEvent(eventPayload)
.then(result => console.log("Event Result", result))
.catch(error => console.error("Event Error", error));
} else {
console.warn("No winners were found in the auction result.");
}

Retryable Errors

The reportEvent function returns an object with retry: true when the response status code is 429 (Too Many Requests) or any 5xx server error occurs. This allows you to implement retry logic. For example:

topsortClient.reportEvent(eventPayload)
.then(result => {
if (result.retry) {
console.warn("Transient error encountered. You may want to retry the call.");
// Add your retry logic here
} else {
console.log("Event successfully reported:", result);
}
})
.catch(error => console.error("Event Error", error));

Sample response

These are typical 200, 400 and 429 responses for the events call:

200:
{
"ok": true,
"retry": false
}
400:
{
"status": 400,
"statusText": "No Content",
"body": {
"errCode": "bad_request",
"docUrl": "https://docs.topsort.com/reference/errors",
"message": "The request could not be parsed."
}
}
429:
{
"ok": false,
"retry": true
}

End to End Example

This is an example of how our JavaScript library can be used to request winners from product listing and banners campaigns, and at the same time send impression events to Topsort.

<script>
window.TS = {
token: "<your API token>" // Replace with your testing API key
};
</script>
<script async type="module">
import { TopsortClient } from "https://unpkg.com/@topsort/sdk@latest/dist/index.mjs";
const output = document.getElementById("output");
const log = (label, data) => {
output.textContent += `\n${label}:\n${JSON.stringify(data, null, 2)}\n`;
};
const topsort = new TopsortClient({
apiKey: window.TS.token,
});
const auctionPayload = {
auctions: [
{
type: "listings",
slots: 2,
searchQuery: "winter" // A campaign targeting the keyword "winter" should exist to return winners
},
{
type: "banners",
slots: 2,
device: "desktop",
slotId: "example" // A campaign configured in the slot "example" should exist to return winners
},
],
};
const opaqueUserId = crypto.randomUUID(); // Setting an opaque user ID to be used in this context
const auctionResult = await topsort.createAuction(auctionPayload);
log("Auction Result", auctionResult);
// Extract winners from auction result
const winners = auctionResult.results.flatMap(result => result.winners || []);
const resolvedBidId = winners[0]?.resolvedBidId || resolvedBidId;
// Build and send impression events for all winners
if (winners.length > 0) {
const impressions = winners.map((winner, index) => ({
resolvedBidId: winner.resolvedBidId,
id: crypto.randomUUID(),
occurredAt: new Date().toISOString(),
opaqueUserId: opaqueUserId,
placement: {
path: "/search/winter",
},
}));
const eventPayload = { impressions };
try {
const eventResult = await topsort.reportEvent(eventPayload);
log("Event Result", eventResult);
} catch (err) {
log("Event Error", err);
}
} else {
log("No Winners", "No winners were found in the auction result, so no impression events were sent.");
}
</script>
<body>
<pre id="output"></pre>
</body>