Elements SDK | ShipEngine

ShipEngine is becoming ShipStation API

Over the next few months you'll notice the ShipEngine website, documentation portal, and dashboard being rebranded as ShipStation API. For our ShipEngine customers, you don't need to take any action or change any of your integrations in any way. All endpoints will remain the same and continue to function as they always have.

To learn more about what's coming, review our New ShipStation API page.

Elements SDK

The Elements SDK is a JavaScript SDK for implementing ShipEngine Elements. You can install it via NPM or access it through our CDN.

Quick Start

npm install @shipengine/elements-sdk

Install Peer Dependencies:

npm install react@17.x react-dom@17.x i18next@22.x react-i18next@11.x @emotion/react@11.x

Elements CDN

The ShipEngine Elements SDK can be included in any page by loading the bundle directly from the Elements CDN. If desired, you may specify a particular version of the SDK by using the following filename format:

https://cdn.shipengine.com/shipengine-elements-sdk.<major_version>.<minor-version>.<patch-version>.mjs

You may omit any level of version number to always load the latest at that level. For example, shipengine-elements-sdk.1.2.34.mjs will pull version 1.2.34, while shipengine-elements-sdk.1.mjs will pull the latest minor and patch version for major version 1.

import { ElementsSDK } from 'https://cdn.shipengine.com/shipengine-elements-sdk.mjs';

// or

<script src="https://cdn.shipengine.com/shipengine-elements-sdk.mjs"></script>

Initialize Elements

You'll need to use the Elements SDK class constructor to initialize Elements. This constructor has three arguments:

  1. Token Callback Function (required): This function, a key component of the Elements SDK, fetches and refreshes the tokens used by Elements. Check out the Elements Getting Started guide for more detailed information about generating Elements tokens.
  2. Initialization Parameters (optional): This object allows you to customize various aspects of the Elements SDK. It's optional; See the initialization parameters section
  3. Container (optional): An HTML ID or HTML element that the Elements React root and CSS reset will be mounted to. The SDK uses a shadow root to isolate its CSS styles from the rest of your application, preventing conflicts and ensuring consistent styling. If you provide a container, the SDK will create a shadow root on that container and render the elements within it. If you don't provide a container, the SDK will create a new container element with a shadow root and append it to the document body.
const elements = new ElementsSDK(
  getToken,
  {
    onError: (err: Error) => console.error(err),
    baseURL: 'https://elements.shipengine.com',
    themeConfig: themeConfig,
    locale: 'en-US',
    features: {
      globalFeatures: {
        enabledShipEngineCarriers: ['ups', 'stamps_com'],
        enabledExternalCarriers: [
          'apc',
          'asendia',
          'better_trucks',
          'courierpost',
          'dpd',
          'seko',
          'ups',
          'yodel',
        ],
      },
    },
  },
  'elementsRoot'
);

Initialization Parameters

Args/Props Description
baseURL string, optional A fully qualified domain name used as the base URL to route all API calls from the Elements. This is defaulted to https://elements.shipengine.com
defaultQueryClientOptions object, optional Initialization options of the ReactQuery client. See the QueryClient Docs for more info.
emotionCacheShadowRootContainer ShadowRoot, optional Deprecated A reference to a shadow root used for isolating the Elements style sheets, CSS resets, and emotion.js cache.
features object, optional A feature flag configuration object for turning features on and off. See Configuring Elements Features for a comprehensive list of features.
headers object, optional Optional HTTP headers to be sent with all requests.
locale string, optional Defaults to en-us
onApiError object, optional Callback function that will be executed whenever there is an error within the API.
onError function, optional An optional callback function to be invoked when an error occurs during a request to the API.
scope string, optional Element id to apply the theme, font family, and CSS reset. By default, the font will be applied to the body element, and the reset will be applied to the root HTML element.
themeConfig object, optional The theme configuration object. Check out the theming documentation to learn more about theming your Elements integration.

Configuring Elements Features

features={{
        globalFeatures: {
          enabledShipEngineCarriers: [
            'ups',
            'stamps_com'
          ],
          enabledExternalCarriers: [
            'apc',
            'asendia',
            'better_trucks',
            'courierpost',
            'dpd',
            'seko',
            'ups',
            'yodel',
          ],
        },
          purchaseLabelFeatures: { ... },
          shipmentSummaryFeatures: { ... },
          accountSettingsFeatures: { ... },
          labelsGridFeatures: { ... }
      }}

Global Features

Params Description
enabledExternalCarriers string[], optional List external carrier codes for carriers that can be registered through the Connect External Carrier Element. If this is omitted, external carriers cannot be registered.
enabledShipEngineCarriers string[], optional List of ShipEngine carrier codes for carriers that can be registered through the Onboarding Element.
poweredByShipEngine boolean, optional Enables the Powered by ShipEngine logo in the footer various elements.

Element specific Features

Params Description
purchaseLabelFeatures string[], optional See Purchase Label Features for a comprehensive list.
shipmentSummaryFeatures string[], optional See Shipment Summary Features for a comprehensive list.
accountSettingsFeatures string[], optional See Account Settings Features for a comprehensive list.
labelsGridFeatures string[], optional See Labels Grid Features for a comprehensive list.

Rendering Elements

elements.create(element)

Params Description
element string, required The name of the Element to be created.

Elements

elements.destroy()

Removes Elements from the DOM and destroys it. A destroyed Element instance can not be re-activated or re-mounted to the DOM.

elements.getClient()

Returns an instance of the ShipEngine Elements API JavaScript client. This client can be used to interact directly with the ShipEngine API.

If no parameters are passed to getClient(), the client will be configured based off of the initialization parameters passed to the Elements SDK constructor. If desired, you may pass a token and configuration object to the getClient() method to specify a different configuration:

const token = await getToken();
const apiClient = elements.getClient(token, {
  getToken,
  onApiError: myOtherErrorHandler,
});

Side Panel Methods (deprecated)

While working with the Elements SDK, you probably noticed methods for rendering individual Elements in a side panel. Methods like onboardUser or purchaseLabel, accessible via the Elements SDK class, have been deprecated in Elements v2 and will be removed in future versions.

Element Render Methods

There are two ways to render Elements in your application:

The Elements SDK allows you to place Elements in any container in your app, but the Elements were designed to look best at a viewport width of 440 to 800 pixels.

element.mount(domElement, props)

Before you mount an Element, you must create a container DOM element. The mount method attaches your Element to the DOM. mount accepts either an ID Attribute (e.g., purchaseLabelId) or a DOM element as well as the Elements props. See the documentation for that Element for more information on its props.

<div id="purchaseLabelId">
  <!-- Purchase Label Element will be inserted here. -->
</div>

<script>
  purchaseLabel.mount('purchaseLabelId');
</script>

element.update(props)

Updates the props for the element

// updates the shipment Id of the purchase label element
purchaseLabel.update({ shipmentId: 'se-1198001' });

element.unmount()

Unmounts the Element from the DOM. Call the element.mount() method to re-attach it to the DOM.

purchaseLabel.unmount();

element.renderSidePanel(props)

Renders the Element inside a side panel. The method accepts the Elements props as well as the props for the side panel that it is rendered in side of.

purchaseLabel.renderSidePanel({
  elementProps: { shipmentId: 'se-11975001' },
  sidePanelHeaderProps: { title: 'Purchase a Label' },
  sidePanelProps: { position: 'left' },
});

element.closeSidePanel()

Closes the currently opened side panel.

purchaseLabel.closeSidePanel();

Creating Shipments

If you wish to purchase a label using pre-populated values in the Purchase label forms, the recommended way to define the shipment values is to create a new shipment using the ShipEngine API, and then pass the new Shipment ID to the PurchaseLabel or LabelWorkflow Element.

The Elements SDK provides an API client which can be used to generate the shipment using the same authentication token used by Elements. See the example below:

const client = elements.getClient(await getToken());
const response = await client.shipments.create({
  ship_to: {
    name: 'Benjamin Biggs',
    phone: '+44 44 4444 4444',
    address_line1: "Dean's Yard",
    city_locality: 'London',
    postal_code: 'SW1P 3PA',
    country_code: 'UK',
  },
  ship_from: {
    name: 'John Doe',
    company_name: 'Example Corp',
    phone: '333-333-3333',
    address_line1: '4301 Bull Creek Rd',
    city_locality: 'Austin',
    state_province: 'TX',
    postal_code: '78731',
    country_code: 'US',
  },
  packages: [
    {
      weight: { value: 20, unit: 'ounce' },
      dimensions: { height: 6, width: 12, length: 24, unit: 'inch' },
      products: [
        {
          description: 'Pizza',
          quantity: 2,
          value: {
            currency: 'USD',
            amount: 20,
          },
          sku: '1234ABCD',
          harmonized_tariff_code: '1905.90.9060',
          country_of_origin: 'US',
        },
      ],
    },
  ],
});
const shipmentId = response.data.shipments[0].shipmentId;

const purchaseLabel = elements.create('purchaseLabel');
purchaseLabel.renderSidePanel({
  elementProps: {
    shipmentId: this.shipmentId,
  },
});

Only the ship_to and ship_from properties are required; The rest may be left blank to be filled in by the user in the Element. The packages.products array is used for Customs information, and is not generally required for local shipments.

For more information on the available fields within the Shipment object, see the ShipEngine API documentation. For additional functionality provided by the Elements API Client, see the ShipEngine Elements API Clients documentation.