Feature |
Browser SDK 2.0 |
Javascript SDK |
---|---|---|
Package |
||
Logger provider |
Amplitude Logger by Default. Fully customizable. |
Amplitude Logger by default. Not customizable. |
Storage provider |
LocalStorage by default. Fully customizable. |
Limited storage - cookies, localStorage, sessionStorage, or none available. Not able to be customized. |
Customization |
Plugins |
Not supported |
Bundle size |
Tree shaking for optimization |
No Optimization |
Server endpoint |
HTTP V2 API |
HTTP V1 API |
Batch API |
Supported, with configuration. |
Not supported |
Amplitude Browser SDK 2.0 (@amplitude/analytics-browser@2+
) features:
Browser SDK 2.0 isn't backwards compatible with amplitude-js
.
To migrate to @amplitude/analytics-browser@2+
, update your dependencies and instrumentation.
When migrating to @amplitude/analytics-browser@2+
, your implementation may experience disruption to web attribution. Before you upgrade, choose whether attribution occurs during a session. After upgrading, attribution can happen during the session, and is no longer configurable.
In both versions, attribution can occur during initialization.
amplitude-js
: Maintenance Browser SDK@amplitude/analytics-browser@2+
: Browser SDK 2.0For snippet installation, update your project's snippet loader.
For Node projects, update your dependency list in package.json.
1{2 "dependencies": {3 "amplitude-js": "^8"4 }5}
1{2 "dependencies": {3 "@amplitude/analytics-browser": "^2.11.8"4 }5}
Browser SDK 2.0 offers an API to instrument events. To migrate to the Browser SDK 2.0, update a few calls. The following sections detail which calls have changed.
getInstance()
has been removed. To initialize the SDK, call init()
, with the same parameters. However, config
comes in a different shape. See Configuration.
1import amplitude from "amplitude-js"2 3amplitude.getInstance().init(API_KEY, OPTIONAL_USER_ID, config)
1import * as amplitude from "@amplitude/analytics-browser"2 3amplitude.init(API_KEY, OPTIONAL_USER_ID, config)
Configuration options
amplitude-js
@amplitude/analytics-browser@2+
config.apiEndpoint
config.serverUrl
config.batchEvents
config.flushQueueSize
config.cookieExpiration
config.cookieOptions.expiration
config.secureCookie
config.cookieOptions.secure
config.sameSiteCookie
config.cookieOptions.sameSite
config.cookieName
NOT SUPPORTED
config.cookieForceUpgrade
NOT SUPPORTED
config.deferInitialization
NOT SUPPORTED. See Defer initialization.
config.disableCookies
config.identityStorage
. Set it to 'localStorage'
to disable cookies
config.deviceId
config.deviceId
config.deviceIdFromUrlParam
Device Id is pulled from URL parameter by default. See Browser SDK 2.0 Cross-domain tracking.
config.domain
NOT SUPPORTED
config.eventUploadPeriodMillis
config.flushIntervalMillis
config.eventUploadThreshold
config.flushQueueSize
config.forceHTTPs
NOT SUPPORTED
config.includeFbclid
NOT SUPPORTED. See Web attribution.
config.includeGclid
NOT SUPPORTED. See Web attribution.
config.includeReferrer
NOT SUPPORTED. See Web attribution.
config.includeUtm
NOT SUPPORTED. See Web attribution.
config.language
NOT SUPPORTED. See Plugins.
config.library
NOT SUPPORTED. See Plugins.
config.logLevel
config.logLevel
config.logAttributionCapturedEvent
NOT SUPPORTED
config.optOut
config.optOut
config.onError
NOT SUPPORTED
config.onExitPage
NOT SUPPORTED. See Flush.
config.platform
NOT SUPPORTED.
platform
isn't supported at the configuration level, but it does still exist in the event object. Overwrite this by either assigning a platform while tracking an event, or enriching the event.platform using the enrichment plugin. See Plugins.
config.savedMaxCount
NOT SUPPORTED
config.saveEvents
NOT SUPPORTED
config.saveParamsReferrerOncePerSession
NOT SUPPORTED.
config.sessionTimeout
config.sessionTimeout
config.storage
config.storageProvider
config.trackingOptions
config.trackingOptions
config.transport
config.transportProvider
config.unsetParamsReferrerOnNewSession
NOT SUPPORTED. Default behavior.
config.unsentKey
NOT SUPPORTED
config.unsentIdentifyKey
NOT SUPPORTED
config.uploadBatchSize
config.flushQueueSize
config.headers
NOT SUPPORTED
config.serverZone
config.serverZone
config.useDynamicConfig
NOT SUPPORTED
config.serverZoneBasedApi
NOT SUPPORTED
config.sessionId
config.sessionId
config.partnerId
config.partnerId
The maintenance Browser SDK offered a variety of logEvent
APIs like logEventWithTimestamp
, logEventWithGroups
to override specific properties in the event payload. Instead of these, use the unified track
API in @amplitude/analytics-browser@2+
.
The logEvent()
API maps to track()
.
1const eventType = "Button Clicked"2const eventProperties = {3 type: "primary",4}5amplitude.getInstance().logEvent(6 eventType,7 eventProperties,8)
1const eventType = "Button Clicked"2const eventProperties = {3 type: "primary",4}5amplitude.track(6 eventType,7 eventProperties,8)
The logEventWithTimestamp()
API maps to track()
.
1const eventType = "Button Clicked" 2const eventProperties = { 3 type: "primary", 4} 5const timestamp = Date.now() 6amplitude.getInstance().logEventWithTimestamp( 7 eventType, 8 eventProperties, 9 timestamp,10)
1const eventType = "Button Clicked" 2const eventProperties = { 3 type: "primary", 4} 5const eventOptions = { 6 time = Date.now() 7} 8amplitude.track( 9 eventType,10 eventProperties,11 eventOptions12)
The logEventWithGroups()
API maps to track()
.
1const eventType = "Button Clicked" 2const eventProperties = { 3 type: "primary", 4} 5const groups = { 6 orgId: "12345", 7} 8amplitude.getInstance().logEventWithGroups( 9 eventType,10 eventProperties,11 groups,12)
1const event_type = "Button Clicked" 2const event_properties = { 3 type: "primary", 4} 5const groups = { 6 orgId: "12345", 7} 8const event = { 9 event_type,10 event_properties,11 groups12}13amplitude.track(event)
sendEvents()
The sendEvents()
API maps to flush()
.
1amplitude.getInstance().sendEvents()
1amplitude.flush()
The APIs for setting user properties are the same, except for the removal of getInstance()
. Here are code snippets to migrate APIs for user properties.
The maintenance SDK uses an old SDK endpoint (api2.amplitude.com
) which enforces no length limit for deviceId
and userId
. The latest SDK uses Amplitude's HTTP V2 API (api2.amplitude.com/2/httpapi
) and requires identifiers to be at least five characters by default. When you migrate to the latest SDK, set config.minIdLength
to a smaller value if you allowed identifiers with fewer than five characters.
Set a userId
when you invoke amplitude
without calling getInstance()
1const userId = "1"2amplitude.getInstance().setUserId(userId)
1const userId = "1"2amplitude.setUserId(userId)
The maintenance SDK uses an old SDK endpoint (api2.amplitude.com
) which enforces no length limit for deviceId
and userId
. The latest SDK uses Amplitude's HTTP V2 API (api2.amplitude.com/2/httpapi
) and requires identifiers to be at least five characters by default. When you migrate to the latest SDK, set config.minIdLength
to a smaller value if you allowed identifiers with fewer than five characters.
Set a deviceId
when you invoke amplitude
without calling getInstance()
1const deviceId = "1"2amplitude.getInstance().setDeviceId(deviceId)
1const deviceId = "1"2amplitude.setDeviceId(deviceId)
Set a sessionId
when you invoke amplitude
without calling getInstance()
1const sessionId = Date.now()2amplitude.getInstance().setSessionId(sessionId)
1const sessionId = Date.now()2amplitude.setSessionId(sessionId)
The clearUserProperties
API has been removed. Use the unified identify
API to remove user properties.
1amplitude.getInstance().clearUserProperties()
1amplitude.identify(2 new amplitude.Identify().identify.clearAll()3)
The setUserProperties
API has been removed. Use the unified identify
API to add user properties.
1amplitude.getInstance().setUserProperties({2 membership, "paid",3 payment, "bank",4})
1const identify = new amplitude.Identify()2identify3 .set("membership", "paid")4 .set("payment", "bank")5amplitude.identify(identify)
Make an identify call on amplitude
without calling getInstance()
.
1const identify = new amplitude.Identify()2identify.set("membership", "paid")3amplitude.getInstance().identify(identify)
1const identify = new amplitude.Identify()2identify.set("membership", "paid")3amplitude.identify(identify)
Make an identify call on amplitude
without calling getInstance()
.
1const identify = new amplitude.Identify()2identify.set("membership", "paid")3amplitude.getInstance().groupIdentify(identify)
1const identify = new amplitude.Identify()2identify.set("membership", "paid")3amplitude.groupIdentify(identify)
Track revenue using revenue()
API on amplitude
without calling getInstance()
.
1const revenue = new amplitude.Revenue()2revenue3 .setProductId("productId")4 .setPrice(10)5amplitude.getInstance().logRevenueV2(revenue)
1const revenue = new amplitude.Revenue()2revenue3 .setProductId("productId")4 .setPrice(10)5amplitude.revenue(revenue)
The configs config.language
, config.library
, config.platform
were available in amplitude-js
to allow modification of event payloads for these specific fields. Although @amplitude/analytics-browser@2+
doesn't support these configurations, you can add plugins to the new Browser SDK to enrich event payloads.
1import { BrowserConfig, EnrichmentPlugin, Event, PluginType } from "@amplitude/analytics-types" 2 3export class LibraryModifierPlugin implements EnrichmentPlugin { 4 name = 'library-modifier' 5 type = PluginType.ENRICHMENT as const 6 7 /** 8 * setup() is called on plugin installation 9 * example: client.add(new LibraryModifierPlugin());10 */11 setup(config: BrowserConfig): Promise<undefined> {12 this.config = config13 }14 15 /**16 * execute() is called on each event instrumented17 * example: client.track('New Event');18 */19 execute(event: Event): Promise<Event> {20 event.library = 'my-library-name/1.0.0'21 return Promise.resolve(event)22 }23}
To install your custom plugin, use add()
with your custom plugin as a parameter.
1import * as amplitude from '@amplitude/analytics-browser'2 3amplitude.add(new LibraryModifierPlugin())4amplitude.init(API_KEY, OPTIONAL_USER_ID)
To defer initialization in amplitude-js
, call init with config.deferInitialization
set to true
, and eventually call enableTracking()
to formalize initialization and send all enqueued events.
1amplitude.getInstance().init(API_KEY, OPTIONAL_USER_ID, {2 deferInitialization: true,3})4 5amplitude.getInstance().logEvent("Event 1")6amplitude.getInstance().logEvent("Event 2")7amplitude.getInstance().logEvent("Event 3")8 9amplitude.getInstance().enableTracking()
init()
at a later time than track()
. All track()
calls are processed after initialization completes.
1amplitude.track("Event 1")2amplitude.track("Event 2")3amplitude.track("Event 3")4 5amplitude.init(API_KEY, OPTIONAL_USER_ID)
In amplitude-js
, enable web attribution through the following configurations:
config.includeGclid
config.includeFbclid
config.includeReferrer
config.includeUtm
In @amplitude/analytics-browser@2+
, the single configuration config.autocapture.attribution
controls the web attribution. This configuration's default setting is true
, and it captures all campaign parameters. These are the same campaign parameters supported in amplitude-js
.
Sometimes you should send events immediately, like when a user navigates away from a page. This is common when tracking button clicks that direct the user to another page while sending event payload in batches.
In amplitude-js
do this by using onExitPage()
callback.
1amplitude.getInstance().init(API_KEY, OPTIONAL_USER_ID, {2 onExitPage: () => {3 amplitude.sendEvents()4 },5})
pagehide
event.
1window.addEventListener('pagehide', () => {2 // Set https transport to use sendBeacon API3 amplitude.setTransport('beacon')4 // Send all pending events to server5 amplitude.flush()6});
amplitude-js
passes one init
callback function for executing any function after initialization and two separate callback functions for success and error network requests. With @amplitude/analytics-browser@2+
supporting promises (and async/await), the asynchronous methods like init()
, track()
, identify()
, groupIdentify()
return a custom promise interface.
1const initResult = await amplitude.init("YOUR_API_KEY").promise 2if (initResult.code === 200) { 3 // success logic 4} else { 5 // error logic 6} 7 8const result = await amplitude.track("Button Clicked").promise 9if (result.code === 200) {10 // success logic11} else {12 // error logic13}
Thanks for your feedback!
May 2nd, 2024
Need help? Contact Support
Visit Amplitude.com
Have a look at the Amplitude Blog
Learn more at Amplitude Academy
© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.