# TD JS SDK APIs ## Treasure(config) Creates a new Treasure logger instance. If the database does not exist and you have permissions, it will be created for you. #### **Core Parameters** | Name | Type | Description | | --- | --- | --- | | config.database | `string` | database name, must consist only of lower case letters, numbers, and `_`, must be longer than or equal to 3 chars, and the total length of database and table must be shorter than 129 chars. | | config.writeKey | `string` | write-only key, get it from your user profile | | [config.pathname] | `string` | path to append after host. Default: `/js/v3/events` | | [config.host] | `string` | host to which events get sent. Default version 4.0: `records.in.treasuredata.com`. Default version 3.1: `in.treasuredata.com` | | [config.development] | `boolean` | triggers development mode which causes requests to be logged and not get sent. Default: `false` | | [config.logging] | `boolean` | enable or disable logging. Default: `true` | | [config.globalIdCookie] | `string` | cookie td_globalid name. Default: `_td_global` | | [config.startInSignedMode] | `boolean` | Tell the SDK to default to Signed Mode if no choice is already made. Default: `false` | | [config.jsonpTimeout] | `number` | JSONP timeout (in milliseconds) Default: `10000` | | [config.storeConsentByLocalStorage] | `boolean` | Tell the SDK to use localStorage to store user consent. Default: `false` | #### **Track/Storage Parameters** | Name | Type | Description | | --- | --- | --- | | [config.clientId] | `string` | uuid for this client. When undefined it will attempt fetching the value from a cookie if storage is enabled, if none is found it will generate a v4 uuid | | [config.storage] | `object` or `string` | storage configuration object. When `none` it will disable cookie storage | | [config.storage.name] | `string` | cookie name. Default: `_td` | | [config.storage.expires] | `integer` | cookie expiration in seconds. When 0 it will expire with the session. Default: `63072000` (2 years) | | [config.storage.domain] | `string` | cookie domain. Default: result of `document.location.hostname` | #### **Server Side Cookie Parameters** | Name | Type | Description | | --- | --- | --- | | [config.useServerSideCookie] | `boolean` | enables/disable using ServerSide Cookie. Default: `false` | | [config.sscDomain] | `string` | Domain against which the Server Side Cookie is set. Default: `window.location.hostname` | | [config.sscServer] | `string` | hostname to request server side cookie from. Default: `ssc.${sscDomain}` | #### **Personalization Parameters** | Name | Type | Description | | --- | --- | --- | | [config.cdpHost] | `string` | The host to use for the Personalization API. Default: `cdp.in.treasuredata.com` | #### **Consent Parameters** | Name | Type | Description | | --- | --- | --- | | [config.consentManager] | `object` | Consent Manager configuration, setup along with the TD JavaScript SDK initialization.Every time when a page is loaded, TD JS Consent Extension will check the consent expiry date and if there's any expired consent, then the expiredConsentCallback is triggered. It also updates status of the expired consent to expired | | [config.consentManager.storageKey] | `string` | Name of the local storage. Default: `td_consent_preferences` | | [config.consentManager.consentTable] | `string` | Name of the consent table. Default: `td_cm_consent` | | [config.consentManager.contextTable] | `string` | Name of the context table. Default: `td_cm_context` | | [config.consentManager.issuer] | `string` | Name of the consent management platform. Default: `treasuredata` | | [config.consentManager.dateFormat] | `string` | Date format string. Default: `YYYY-MM-DD` | | [config.consentManager.successConsentCallback] | `function` | Successful saving consent callback | | [config.consentManager.failureConsentCallback] | `function` | Failed to save consent callback | | [config.consentManager.expiredConsentsCallback] | `function` | Expired consent callback | | [config.consentManager.expiredConsentsCallback] | `function` | Expired consent callback | **Returns:** * Treasure logger instance object **Example:** ```javascript var foo = new Treasure({ database: 'foo', writeKey: 'your_write_only_key' }); ``` ## Treasure#addRecord(table, record, success, error) Sends an event to Treasure Data. If the table does not exist it will be created for you. Records will have additional properties applied to them if `$global` or table-specific attributes are configured using `Treasure#set`. Warning: This function will not send `td_ip`, `td_client_id`, `td_global_id` automatically, so if you want to send those information along with this function you have to do it manually, as follows: ``` td.ready(function () { td.set('$global', 'td_ip', 'ip value'); td.set('$global', 'td_client_id', td.getTrackValues().td_client_id); td.set('$global', 'td_global_id', 'global id value'); td.addRecord(...) }); ``` **Parameters:** * **table** : String (required) - table name, must consist only of lower case letters, numbers, and _ (underscore), must be longer than or equal to 3 chars, the total length of database and table must be shorter than 129 chars. * **record** : Object (required) - Object that will be serialized to JSON and sent to the server * **success** : Function (optional) - Callback for when sending the event is successful * **error** : Function (optional) - Callback for when sending the event is unsuccessful **Example:** ```javascript var company = new Treasure({...}); var sale = { itemId: 100, saleId: 10, userId: 1 }; var successCallback = function () { // celebrate(); }; var errorCallback = function () { // cry(); } company.addRecord('sales', sale, successCallback, errorCallback); ``` ## Treasure#fetchGlobalID(success, error, forceFetch, options) This function calls the endpoint specified in the `host` configuration file. **Parameters:** * **success** : Function (optional) - Callback for when sending the event is successful * **error** : Function (optional) - Callback for when sending the event is unsuccessful * **forceFetch** : Boolean (optional) - Forces a refetch of global id and ignores cached version (default false) * **options** : Object (optional) - Cookie options **Cookie options:** ```javascript { path: '/', domain: 'abc.com', secure: true|false, maxAge: Number | String | Date, sameSite: 'None | Lax | Strict' } ``` **Note:** If you set the `sameSite` value to `None`, the `Secure` property of the cookie will be set to true (it overwrites the `secure` option). More details on [SameSite cookies](https://web.dev/samesite-cookies-explained/). **Example:** ```javascript var td = new Treasure({...}) var successCallback = function (globalId) { // celebrate(); }; var errorCallback = function (error) { // cry(); } td.fetchGlobalID(successCallback, errorCallback) // with cookie options td.fetchGlobalID(successCallback, errorCallback, false, { path: '/', secure: true, maxAge: 5 * 60 // 5 minutes, sameSite: 'None' }) ``` ## Treasure#fetchUserSegments(options, success, error) **Parameters:** * **options** : Object (required) - User Segment object * **options.audienceToken** : String or Array (required) - Audience Token(s) for the userId * **options.keys** : Object (required) - Key Value to be sent for this segment * **success** : Function (optional) - Callback for receiving the user key and segments * **error** : Function (optional) - Callback for when sending the event is unsuccessful **Example:** ```javascript var td = new Treasure({...}) var successCallback = function (values) { /* values format => [... { key: { [key]:value }, values: ["1234"], attributes: { age: 30 }, } ... ]*/ // celebrate(); }; var errorCallback = function (error) { // cry(); }; td.fetchUserSegments({ audienceToken: ['token1', 'token2'], keys: { someKey: 'someValue', someOtherKey: 'someOtherValue', } }, successCallback, errorCallback) ``` info This feature is not enabled on accounts by default. Contact Technical Support or your Customer Success representative to enable it. ## fetchPersonalization(config, data, successCallback, errorCallback) | Name | Type | Description | | --- | --- | --- | | config | `object` | configuration object | | config.endpoint | `string` | Personalization endpoint | | config.database | `string` | Database name | | config.table | `string` | Table name | | config.token | `string` | Personalization token | | data | `object` | (Optional) payload to send with the request | | successCallback | `function` | Callback for successful request | | errorCallback | `function` | Callback for failed quest | **Example:** ```javascript var td = new Treasure({...}) var successCallback = function (values) { //values format => { "offers": { "offer": { "attributes": { "first_name": "test", "nickname": "tet" }, "batch_segments": 55352 } } } // celebrate(); } var errorCallback = function (error) { // cry(); } td.fetchPersonalization({ endpoint: 'endpoint', database: 'database', table: 'table', token: 'personalization token' }, null, successCallback, errorCallback) ``` info Any information that is marked as sensitive information will be excluded from the response. ## Treasure#blockEvents Block all events from being sent to Treasure Data. **Example:** ```javascript var td = new Treasure({...}) td.trackEvent('customevent') td.blockEvents() td.trackEvent('willnotbetracked') ``` ## Treasure#unblockEvents Unblock all events; events will be sent to Treasure Data. **Example:** ```javascript var td = new Treasure({...}) td.blockEvents() td.trackEvent('willnotbetracked') td.unblockEvents() td.trackEvent('willbetracked') ``` ## Treasure#areEventsBlocked Informational method, expressing whether events are blocked or not. **Example:** ```javascript var td = new Treasure({...}) td.areEventsBlocked() // false, default td.blockEvents() td.areEventsBlocked() // true ``` ## Treasure#setSignedMode Allow sending Personally Identifying Information over the wire: `td_ip`, `td_client_id`, and `td_global_id`. **Example:** ```javascript var td = new Treasure({...}) td.setSignedMode() td.trackEvent('willbetracked') // will send td_ip and td_client_id; td_global_id will also be sent if set. ``` ## Treasure#setAnonymousMode Prohibit sending of Personally Identifying Information over the wire: `td_ip`, `td_client_id`, and `td_global_id`. **Parameters**: * **keepIdentifier**: Boolean (optional) - Keep the cookies By default `setAnonymousMode` will remove all cookies that are set by Treasure Data JavaScript SDK, you can set `keepIdentifier` parameter to `true` to not remove the cookies. **Example:** ```javascript var td = new Treasure({...}) td.setAnonymousMode() td.trackEvent('willbetracked') // will NOT send td_ip and td_client_id; td_global_id will also NOT be sent if set. ``` ## Treasure#inSignedMode Informational method, indicating whether `trackEvents` method will automatically collect `td_ip`, `td_client_id`, and `td_global_id` if set. **Example:** ```javascript var td = new Treasure({...}) td.inSignedMode() // false, default td.trackEvent('willbetracked') // will NOT send td_ip and td_client_id; td_global_id will also NOT be sent if set. td.setSignedMode() td.inSignedMode() // true td.trackEvent('willbetracked') // will send td_ip and td_client_id; td_global_id will also be sent if set. ``` ## Treasure#fetchServerCookie(success, error, forceFetch) This functionality complies with ITP 1.2 tracking. Contact Technical Support or your Customer Success representative to enable this feature. **Parameters:** * **success** : Function (optional) - Callback for when sending the event is successful * **error** : Function (optional) - Callback for when sending the event is unsuccessful * **forceFetch** : Boolean (optional) - Forces a refetch of server side id and ignores cached version (default false) **Example:** ```javascript var td = new Treasure({...}) var successCallback = function (serverSideId) { // celebrate(); }; var errorCallback = function (error) { // cry(); } td.fetchServerCookie(successCallback, errorCallback) ``` ## Treasure#resetUUID **Parameters:** * **suggestedStorage** : Object (optional) - Custom storage configuration * **suggestedClientId** : String (optional) - Custom client id Reset the client's UUID, set to Treasure Data as `td_client_id`. You can specify custom storage and custom client id. See [Track/Storage parameters](#trackstorage-parameters) section for more information on storage's configuration **Example:** ```javascript var td = new Treasure({...}) td.resetUUID() // set td_client_id as random uuid ``` ```javascript var td = new Treasure({...}) td.resetUUID( { name: '_td', // cookie name expires: 63072000, domain: 'domain', customDomain: true/false path: '/' }, 'xxx-xxx-xxxx' // client id ) ``` ## Treasure#trackClicks Setup an event listener to automatically log clicks. The event will be hooked only follows - `role=button` or `role=link` - `` - `