> For the complete documentation index, see [llms.txt](https://developer.nexx360.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.nexx360.io/integration-methods/direct-integration-n360ortb/api-reference.md).

# API Reference

This page documents all methods available on the `n360ortb` object.

## Methods Overview

| Method                                                | Description                               |
| ----------------------------------------------------- | ----------------------------------------- |
| [n360ortb.init()](#n360ortb-init)                     | Initialize the library with configuration |
| [n360ortb.fetchBids()](#n360ortb-fetchbids)           | Request bids for ad slots                 |
| [n360ortb.setDisplayBids()](#n360ortb-setdisplaybids) | Set bid targeting on GPT slots            |
| [n360ortb.targetingKeys()](#n360ortb-targetingkeys)   | Get available targeting keys              |
| [n360ortb.onEvent()](#n360ortb-onevent)               | Subscribe to an auction or render event   |
| [n360ortb.offEvent()](#n360ortb-offevent)             | Remove an event listener                  |
| [n360ortb.getEvents()](#n360ortb-getevents)           | Get all events fired since page load      |

***

## n360ortb.init()

Initializes the n360ortb library with your configuration. Must be called before `fetchBids()`.

### Syntax

```javascript
n360ortb.init(config)
```

### Parameters

#### config (required)

| Property   | Required | Type                          | Description                                    |
| ---------- | -------- | ----------------------------- | ---------------------------------------------- |
| currency   | Yes      | `'EUR'` \| `'USD'` \| `'GBP'` | Currency for bid values                        |
| bidTimeout | No       | number                        | Auction timeout in milliseconds. Default: 3000 |
| gdpr       | No       | object                        | GDPR/TCF configuration                         |
| gpp        | No       | object                        | GPP (Global Privacy Platform) configuration    |
| usPrivacy  | No       | object                        | US Privacy (CCPA) configuration                |
| schain     | No       | object                        | Supply chain object                            |

#### config.gdpr

| Property   | Required | Type    | Description                                                |
| ---------- | -------- | ------- | ---------------------------------------------------------- |
| cmpTimeout | No       | number  | Time to wait for CMP response in milliseconds. Default: 50 |
| applies    | No       | boolean | Whether GDPR applies (bypasses CMP detection)              |
| consent    | No       | string  | TC consent string (bypasses CMP detection)                 |

{% hint style="info" %}
When `applies` and `consent` are provided directly, n360ortb skips CMP detection. This is useful when running inside a GAM creative iframe where the CMP is not accessible. See [Integration in GAM as Creative](/integration-methods/direct-integration-n360ortb/gam-integration/integration-in-gam-as-creative.md) for details on using GAM macros.
{% endhint %}

#### config.gpp

| Property   | Required | Type   | Description                                                    |
| ---------- | -------- | ------ | -------------------------------------------------------------- |
| cmpTimeout | No       | number | Time to wait for GPP CMP response in milliseconds. Default: 50 |

#### config.usPrivacy

| Property   | Required | Type   | Description                                                    |
| ---------- | -------- | ------ | -------------------------------------------------------------- |
| cmpTimeout | No       | number | Time to wait for USP CMP response in milliseconds. Default: 50 |

#### config.schain

Attached to every bid request at `source.ext.schain` (OpenRTB 2.5 placement). Invalid schain objects (missing `nodes`, malformed nodes, `complete` not 0/1) are silently dropped — enable `debug: true` to log the rejection.

| Property | Required | Type       | Description                                     |
| -------- | -------- | ---------- | ----------------------------------------------- |
| complete | Yes      | `0` \| `1` | `1` if the chain is complete, `0` if not        |
| nodes    | Yes      | array      | Array of supply chain nodes (must be non-empty) |
| ver      | No       | string     | Schain version (e.g. `'1.0'`)                   |

Each node:

| Property | Required | Type       | Description                                                            |
| -------- | -------- | ---------- | ---------------------------------------------------------------------- |
| asi      | Yes      | string     | Canonical domain of the ad system                                      |
| sid      | Yes      | string     | Seller/reseller account ID at the ad system                            |
| hp       | Yes      | `0` \| `1` | `1` if the seller has a direct relationship with the impression source |
| rid      | No       | string     | Bid request ID at the ad system                                        |
| name     | No       | string     | Seller name (human-readable)                                           |
| domain   | No       | string     | Domain of the seller                                                   |

### Example

```javascript
n360ortb.init({
  currency: 'EUR',
  bidTimeout: 2000,
  gdpr: {
    cmpTimeout: 1000
  },
  schain: {
    complete: 1,
    ver: '1.0',
    nodes: [
      {
        asi: 'publisher.com',
        sid: '123',
        hp: 1
      }
    ]
  }
});
```

### TypeScript Definition

```typescript
type Schain = {
  complete: 0 | 1;
  nodes: Array<{
    asi: string;
    sid: string;
    hp: 0 | 1;
    rid?: string;
    name?: string;
    domain?: string;
  }>;
  ver?: string;
};

type InitConfig = {
  currency: 'EUR' | 'USD' | 'GBP';
  bidTimeout?: number;
  gdpr?: {
    enabled?: boolean;
    cmpTimeout?: number;
    applies?: boolean;   // Direct consent passthrough
    consent?: string;    // Direct consent passthrough
  };
  gpp?: {
    cmpTimeout?: number;
  };
  usPrivacy?: {
    cmpTimeout?: number;
  };
  schain?: Schain;
};

function init(config: InitConfig): void;
```

***

## n360ortb.fetchBids()

Requests bids from Nexx360's server-side auction for the specified ad slots.

### Syntax

```javascript
n360ortb.fetchBids(config, callback)
```

### Parameters

#### config (required)

| Property | Required | Type   | Description                               |
| -------- | -------- | ------ | ----------------------------------------- |
| slots    | Yes      | array  | Array of slot configurations              |
| timeout  | No       | number | Override auction timeout for this request |

#### config.slots\[]

Each slot can be configured using either a `tagId` or a `placement`:

| Property              | Required    | Type                                   | Description                                                                                                      |
| --------------------- | ----------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| divId *(or `slotID`)* | Yes         | string                                 | The DOM element ID where the ad will render                                                                      |
| sizes                 | Conditional | `[number, number][]`                   | Array of eligible banner sizes. Required for banner slots; optional for native-only slots                        |
| tagId                 | Conditional | string                                 | Nexx360 tagId (use this OR placement)                                                                            |
| placement             | Conditional | string                                 | Nexx360 placement code (use this OR tagId)                                                                       |
| gpid                  | No          | string                                 | Global Placement ID forwarded as `imp.ext.gpid` in the OpenRTB request (e.g. `/12345/homepage/box#div-gpt-ad-1`) |
| mediaType             | No          | `'display'` \| `'video'` \| `'native'` | Declare the slot as native-only or video-only. Defaults to banner when `sizes` is present                        |
| native                | No          | object                                 | Native configuration — see [Native Ads](/integration-methods/direct-integration-n360ortb/native-integration.md)  |
| video                 | No          | object                                 | OpenRTB Video object for video slots                                                                             |

{% hint style="info" %}
Use either `tagId` or `placement` to identify your ad unit, not both. The `tagId` is available in the Nexx360 console.
{% endhint %}

#### callback (required)

Function called when the auction completes. Receives the bids object as its argument.

### Callback Response

The callback receives a `bids` object with the following structure:

```typescript
type BidResponse = {
  [divId: string]: {
    cpm: number;           // Bid price in configured currency
    width: number;         // Creative width
    height: number;        // Creative height
    adm: string;           // Ad markup (HTML/JavaScript)
    creativeId: string;    // Creative identifier
    ssp: string;           // SSP that won the auction
    currency: string;      // Currency code
    dealId?: string;       // Deal ID if applicable
  };
};
```

### Example

```javascript
n360ortb.fetchBids({
  slots: [
    {
      tagId: 'homepage-leaderboard',
      divId: 'div-leaderboard',
      sizes: [[728, 90], [970, 250]]
    },
    {
      tagId: 'sidebar-mpu',
      divId: 'div-sidebar',
      sizes: [[300, 250], [300, 600]]
    }
  ]
}, function(bids) {
  console.log('Auction complete:', bids);

  // Example bid response:
  // {
  //   'div-leaderboard': {
  //     cpm: 2.50,
  //     width: 728,
  //     height: 90,
  //     adm: '<script>...</script>',
  //     creativeId: 'abc123',
  //     ssp: 'appnexus',
  //     currency: 'EUR'
  //   },
  //   'div-sidebar': {
  //     cpm: 1.80,
  //     width: 300,
  //     height: 250,
  //     adm: '<script>...</script>',
  //     creativeId: 'def456',
  //     ssp: 'rubicon',
  //     currency: 'EUR'
  //   }
  // }
});
```

### TypeScript Definition

```typescript
type Slot = {
  divId: string;
  sizes: [number, number][];
  tagId?: string;
  placement?: string;
};

type FetchBidsConfig = {
  slots: Slot[];
  timeout?: number;
};

type Bid = {
  cpm: number;
  width: number;
  height: number;
  adm: string;
  creativeId: string;
  ssp: string;
  currency: string;
  dealId?: string;
};

type BidResponse = {
  [divId: string]: Bid;
};

function fetchBids(config: FetchBidsConfig, callback: (bids: BidResponse) => void): void;
```

***

## n360ortb.setDisplayBids()

Sets bid targeting values on Google Publisher Tag (GPT) ad slots. Call this method after `fetchBids()` completes and before calling `googletag.pubads().refresh()`.

### Syntax

```javascript
n360ortb.setDisplayBids()
```

### Parameters

None.

### Behavior

This method:

1. Sets targeting key-value pairs on the corresponding GPT slots
2. Registers an event listener on `slotRenderEnded` to clear targeting after each slot renders

### Targeting Keys Set

| Key        | Description                                |
| ---------- | ------------------------------------------ |
| n360\_bid  | Unique bid identifier                      |
| n360\_pb   | Price bucket for line item targeting       |
| n360\_sz   | Ad size (e.g., "300x250")                  |
| n360\_crid | Creative ID                                |
| n360\_ssp  | SSP identifier                             |
| n360\_mt   | Media type: `banner`, `video`, or `native` |

**Native bids** additionally set `n360_native_title`, `n360_native_image`, `n360_native_icon`, `n360_native_brand`, `n360_native_body`, `n360_native_rating`, `n360_native_cta`, and `n360_native_linkurl`. See [Native Ads](/integration-methods/direct-integration-n360ortb/native-integration.md) for details.

{% hint style="info" %}
The `n360_pb` value uses medium granularity (same as Prebid.js). See [Line Item Setup](/integration-methods/direct-integration-n360ortb/gam-integration/line-item-setup.md) for full price bucket ranges and examples.
{% endhint %}

### Example

```javascript
n360ortb.fetchBids({
  slots: [
    { tagId: 'my-tag', divId: 'div-1', sizes: [[300, 250]] }
  ]
}, function(bids) {
  // Set targeting on GPT slots
  n360ortb.setDisplayBids();

  // Refresh the ads
  googletag.pubads().refresh();
});
```

***

## n360ortb.targetingKeys()

Returns an array of all targeting keys used by n360ortb.

### Syntax

```javascript
n360ortb.targetingKeys()
```

### Parameters

None.

### Returns

`string[]` - Array of targeting key names.

### Example

```javascript
const keys = n360ortb.targetingKeys();
console.log(keys);
// ['n360_bid', 'n360_pb', 'n360_sz', 'n360_crid', 'n360_ssp', 'n360_mt',
//  'n360_native_title', 'n360_native_brand', 'n360_native_body',
//  'n360_native_cta', 'n360_native_image', 'n360_native_icon',
//  'n360_native_linkurl', 'n360_native_rating']
```

### Use Case

Use this method to clear n360ortb targeting from slots if needed:

```javascript
googletag.cmd.push(function() {
  var slot = googletag.pubads().getSlots()[0];
  n360ortb.targetingKeys().forEach(function(key) {
    slot.clearTargeting(key);
  });
});
```

***

## Events

n360ortb emits events throughout the bid and render lifecycle, following the same model as [Prebid.js events](https://docs.prebid.org/dev-docs/publisher-api-reference/getEvents.html). Use `onEvent()` / `offEvent()` to subscribe and `getEvents()` to inspect history.

### Event Types

| Event               | Fires when                                                                            | Payload                          |
| ------------------- | ------------------------------------------------------------------------------------- | -------------------------------- |
| `requestBids`       | `fetchBids()` starts, after the OpenRTB request is built                              | `{ slots, request }`             |
| `bidResponse`       | Once for each bid received in the response                                            | A `StoredBid` object             |
| `auctionEnd`        | Winning bids have been stored (also fires with an empty array when there are no bids) | `{ bids }`                       |
| `bidTimeout`        | The bid request errors or times out                                                   | `{ error }`                      |
| `setTargeting`      | Targeting has been applied to GPT slots                                               | `{ [slotID]: { key: value } }`   |
| `bidWon`            | A creative pulls its markup (the bid is committed to render)                          | A `StoredBid` object             |
| `adRenderSucceeded` | A creative reports a successful render                                                | `{ adId, bid }`                  |
| `adRenderFailed`    | A creative reports a failed render, or its bid could not be found                     | `{ reason, message, adId, bid }` |

{% hint style="info" %}
`bidWon`, `adRenderSucceeded` and `adRenderFailed` rely on the creative running the **n360ortbDisplay** library. Under SafeFrame and cross-domain rendering, the render result is reported back to the page via a postMessage signal — see the [Display Library API Reference](/integration-methods/direct-integration-n360ortb/display-api-reference.md).
{% endhint %}

{% hint style="warning" %}
Events are **not** replayed to late subscribers. Register listeners before calling `fetchBids()`, or read past events with `getEvents()`. `bidWon` fires at most once per bid per auction.
{% endhint %}

***

## n360ortb.onEvent()

Registers a listener for an event. Optionally filter by an `id` (slot ID for `bidWon`, ad/bid ID for `adRenderSucceeded` / `adRenderFailed`) so the handler only runs for that specific slot or ad.

### Syntax

```javascript
n360ortb.onEvent(eventType, handler, id)
```

### Parameters

| Parameter | Required | Type     | Description                                                      |
| --------- | -------- | -------- | ---------------------------------------------------------------- |
| eventType | Yes      | string   | One of the [event types](#event-types) above                     |
| handler   | Yes      | function | Callback invoked with the event payload                          |
| id        | No       | string   | Only invoke the handler when the event's id (slot/ad ID) matches |

### Example

```javascript
// Fire a tracker whenever any creative renders successfully
n360ortb.onEvent('adRenderSucceeded', function(data) {
  console.log('Rendered bid', data.adId, data.bid && data.bid.ssp);
});

// Listen only for a specific slot winning
n360ortb.onEvent('bidWon', function(bid) {
  console.log('Slot div-leaderboard won:', bid.price);
}, 'div-leaderboard');
```

***

## n360ortb.offEvent()

Removes a previously registered listener. Pass the same `eventType`, `handler` reference, and `id` used with `onEvent()`.

### Syntax

```javascript
n360ortb.offEvent(eventType, handler, id)
```

### Example

```javascript
function onRender(data) { /* ... */ }

n360ortb.onEvent('adRenderSucceeded', onRender);
// later
n360ortb.offEvent('adRenderSucceeded', onRender);
```

***

## n360ortb.getEvents()

Returns a copy of every event fired since page load, in order. Useful for analytics or debugging — including for listeners registered after an auction already completed.

### Syntax

```javascript
n360ortb.getEvents()
```

### Returns

An array of records:

```typescript
type RecordedEvent = {
  eventType: string;   // e.g. 'bidWon'
  args: unknown;       // the event payload
  id?: string;         // slot/ad id, when the event carries one
  elapsedTime: number; // ms since page load (performance.now())
};
```

### Example

```javascript
const renders = n360ortb.getEvents()
  .filter(function(e) { return e.eventType === 'adRenderSucceeded'; });
console.log(renders.length + ' creatives rendered');
```

### TypeScript Definition

```typescript
type EventType =
  | 'requestBids'
  | 'bidResponse'
  | 'auctionEnd'
  | 'bidTimeout'
  | 'setTargeting'
  | 'bidWon'
  | 'adRenderSucceeded'
  | 'adRenderFailed';

function onEvent(eventType: EventType, handler: (payload: any) => void, id?: string): void;
function offEvent(eventType: EventType, handler: (payload: any) => void, id?: string): void;
function getEvents(): RecordedEvent[];
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://developer.nexx360.io/integration-methods/direct-integration-n360ortb/api-reference.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
