JavaScript SDK Integration: Setup & Configuration
A step-by-step guide to adding Adgentek ads to your website with a simple script tag
Overview
The Adgentek JavaScript SDK is the fastest way to start serving contextual ads on your website or in your web-based chatbot. With a single script tag and a few lines of configuration, the SDK handles ad fetching, rendering, impression tracking, and click tracking automatically.
This integration method is ideal for publishers who want a drop-in solution without building custom API calls. For more control over the request lifecycle, see the Publisher – REST API Integration: Setup & Configuration article.
Quick Reference
|
Integration Type |
Client-side JavaScript (script tag or npm) |
|
SDK URL |
https://api.adgentek.ai/storage/v1/object/public/sdk/sdk.js |
|
Complexity |
No backend required — paste and go |
|
Tracking |
Automatic (impressions, clicks, conversions) |
|
Framework Support |
Vanilla JS, React, Vue, or any web framework |
Prerequisites
Before starting the integration, make sure you have the following:
- An active Adgentek publisher account
- A Publisher API key (create or manage keys in your Adgentek dashboard)
- A configured ad slot with its corresponding slot_id
- A website or web application where you can add script tags
- An ad container element (a <div> where ads will render)
Step 1: Add the Script Tag
Paste the following code before the closing </body> tag on your website. This loads the Adgentek SDK and initializes it with your credentials.
|
<script src="https://api.adgentek.ai/storage/v1/object/public/sdk/sdk.js"> </script> <script> AdgentekAds.init({ apiKey: 'YOUR_API_KEY', slotId: 'YOUR_SLOT_ID' }); </script> |
Initialization Parameters
|
Parameter |
Type |
Required |
Description |
|
apiKey |
string |
Yes |
Your Publisher API key from the Adgentek dashboard. |
|
slotId |
string |
Yes |
The ad slot identifier where ads will be served. |
|
baseUrl |
string |
No |
Override the default API endpoint. Only needed for custom environments. |
|
containerId |
string |
No |
The DOM element ID where ads render. Defaults to "adgentek-ad". |
Step 2: Add an Ad Container
Add a <div> element where you want the ad to appear on your page. The SDK will render ad content inside this container.
|
<div id="adgentek-ad"></div> |
|
Placement Tip Place the ad container near your chatbot’s response area for the most natural user experience. The SDK handles all styling and layout within the container. |
Step 3: Show Ads in Your Chat
Call AdgentekAds.showAd() after your chatbot generates a response. Pass the conversation history as an array of role/content message objects. The SDK uses this context to serve a relevant ad.
|
// After your chatbot responds, show a relevant ad AdgentekAds.showAd([ { role: 'user', content: 'What CRM do you recommend?' }, { role: 'assistant', content: 'Here are the top CRM options...' } ]); |
|
That’s It! The SDK automatically handles ad rendering, impression tracking, and click tracking. No additional code is required for basic implementations. |
Step 4: Full Working Example
Copy this complete HTML file to test the integration end-to-end. Replace the placeholder values with your actual API key and slot ID, then open the file in a browser.
|
<html> <body> <h1>Hello Adgentek world.</h1> <div id="adgentek-ad"></div> <p> User: What CRM do you recommend?<br> Assistant: Here are the top CRM options..<br> </p> <button onclick="AdgentekAds.showAd([ { role: 'user', content: 'What CRM do you recommend?' }, { role: 'assistant', content: 'Here are the top CRM options...' } ])">Click Me</button> <script src="https://api.adgentek.ai/storage/v1/object/public/sdk/sdk.js"> </script> <script> AdgentekAds.init({ apiKey: 'YOUR_API_KEY', slotId: 'YOUR_SLOT_ID', baseUrl: 'https://api.adgentek.ai/functions/v1/mcp-ad-server', containerId: 'adgentek-ad' }); </script> </body> </html> |
React Integration
For React applications, use the custom hook pattern below. This approach gives you full control over ad placement and rendering while the hook manages the API calls, loading state, and impression tracking.
useAdgentekAds Hook
|
import { useState, useCallback, useRef } from 'react'; // Stable session_id — persists for the browser session function getSessionId() { let sid = sessionStorage.getItem('adgentek_sid'); if (!sid) { sid = 'sid_' + crypto.randomUUID(); sessionStorage.setItem('adgentek_sid', sid); } return sid; } function useAdgentekAds(apiKey, slotId) { const [ad, setAd] = useState(null); const [loading, setLoading] = useState(false); const impressionFired = useRef(false); const fetchAd = useCallback(async (messages) => { setLoading(true); try { const response = await fetch( 'https://api.adgentek.ai/functions/v1/mcp-ad-server/get-ad', { method: 'POST', headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ slot_id: slotId, context: { messages: messages.slice(-10), session_id: getSessionId() } }) } ); const data = await response.json(); setAd(data.ad || null); impressionFired.current = false; } catch (err) { console.error('Ad fetch error:', err); setAd(null); } finally { setLoading(false); } }, [apiKey, slotId]); return { ad, loading, fetchAd, impressionFired }; } |
Usage in a Component
|
function ChatWithAds() { const { ad, loading, fetchAd, impressionFired } = useAdgentekAds( 'YOUR_API_KEY', 'YOUR_SLOT_ID' ); // Call fetchAd(messages) after each AI response return ( <div> {/* Your chat UI here */} {ad && ( <div className="ad-card"> {ad.impression_url && !impressionFired.current && ( <img src={ad.impression_url} alt="" width={1} height={1} style= onLoad={() => { impressionFired.current = true; }} /> )} <span>Sponsored</span> <h4>{ad.title}</h4> <p>{ad.content}</p> <a href={ad.click_url}>{ad.cta}</a> </div> )} </div> ); } |
|
Session ID Best Practice The session_id must persist across requests for the same user session. The getSessionId() helper uses sessionStorage to maintain a stable ID. Do not regenerate it on every request — this enables proper frequency capping and ad deduplication. |
Automatic Tracking
|
No Manual Tracking Required Adgentek handles all ad tracking automatically for security and fraud prevention. You do not need to build any custom tracking infrastructure. |
|
Tracking Type |
How It Works |
|
Impressions |
Logged automatically when the SDK renders an ad, or when you fire the impression_url pixel in custom implementations. |
|
Clicks |
Tracked via Adgentek’s click-redirect URLs. Users are redirected to the advertiser landing page after the click is recorded. |
|
Conversions |
Handled through advertiser-side pixels and server-to-server postbacks. No publisher action required. |
Best Practices
|
Practice |
Guidance |
|
Script Placement |
Load the SDK script before the closing </body> tag to avoid blocking page rendering. The SDK loads asynchronously but placing it at the bottom is safest. |
|
Container Placement |
Position the ad container near your chatbot’s response area for the most natural user experience and highest engagement. |
|
Message Context |
Pass the most recent conversation messages (up to 10) to showAd() or fetchAd() for the best ad targeting accuracy. |
|
Error Handling |
The SDK handles errors silently by default. For custom React implementations, wrap API calls in try/catch and handle null ad responses gracefully. |
|
Security |
Store API keys in environment variables for server-rendered apps. For client-side-only implementations, use domain-restricted API keys from your Adgentek dashboard. |
|
Async Loading |
Never let ad loading block your chat experience. The SDK and React hook both operate asynchronously by design. |
Troubleshooting
|
Issue |
Resolution |
|
Ad not appearing |
Verify the ad container div exists in the DOM with the correct ID. Check that your API key and slot_id are correct. Open the browser console for error messages. |
|
SDK not loading |
Confirm the script URL is correct and your network can reach api.adgentek.ai. Check for content security policy (CSP) restrictions that may block external scripts. |
|
401 Unauthorized |
Your API key is invalid or missing. Regenerate it in the Adgentek dashboard and update your init() call. |
|
No ad returned |
This is normal — not every request returns an ad. Ensure your application handles this case gracefully. The SDK hides the container automatically when no ad is available. |
|
Ads not contextually relevant |
Send more conversation messages to showAd(). The SDK needs sufficient context (at least 2–3 message pairs) for accurate targeting. |
|
CORS errors (React) |
If using the REST API directly in a browser-side React app, ensure you are calling the API from an allowed origin. Contact Adgentek support to whitelist your domain if needed. |
Need Help?
If you run into issues or have questions about the JavaScript SDK integration, reach out to the Adgentek publisher support team. When contacting support, include your publisher ID, the slot_id you are working with, your browser and version, and any console error messages.