Skip to main content

Save and restore configurations

A webshop needs to keep the configuration that the shopper made: in the cart, in an order, or to let the shopper continue later. In this tutorial you save a configuration, restore it, and open configurations that Expivi shares as a link.

The finished code is the save-and-share.html page of the example apps.

Save a configuration​

configurator.serialize() returns the complete configuration as a plain object that you can turn into JSON:

const configuration = await configurator.serialize();
const json = JSON.stringify(configuration);

The object contains everything needed to restore the configuration: the products (for a bundle, every added product), the selected value of every attribute, and the data of extensions. Treat it as an opaque value: store it as it is and give it back to the SDK unchanged.

The serialized configuration can be large, for example tens of kilobytes for a bundle. Store it on your server or in the browser, not in a URL.

Restore a configuration​

configurator.parse(configuration) applies a serialized configuration to the loaded product. Call it once the configurator is READY. It returns true when the configuration was restored.

const isRestored = await configurator.parse(JSON.parse(json));

The example: save for later​

The example saves the configuration in the browser's localStorage, and restores it with a button. That also works after a reload: the page loads the product, and the restore button applies the saved configuration.

src/components/save-configuration.js
import { expiviConfig } from '../shared/expivi.config.js';

/**
* Save and restore buttons. In this demo the configuration is kept in localStorage; in a webshop
* you would send it to your backend, for example together with the cart item.
*
* @param {HTMLElement} container
* @param {import('@expivi/sdk').ProductConfigurator} configurator
*/
export function mountSaveConfiguration(container, configurator) {
const storageKey = `expivi-configuration:${expiviConfig.productId}`;

container.innerHTML = `
<div class="button-row">
<button type="button" class="button" data-save>Save configuration</button>
<button type="button" class="button button--secondary" data-restore>Restore saved configuration</button>
</div>
<p class="message" role="status" hidden></p>`;

const restoreButton = container.querySelector('[data-restore]');
const message = container.querySelector('.message');

container.querySelector('[data-save]').addEventListener('click', async () => {
// serialize() returns the full configuration as a plain, JSON-serializable object.
const configuration = await configurator.serialize();
localStorage.setItem(storageKey, JSON.stringify(configuration));
updateRestoreButton();
showMessage(`Configuration saved at ${new Date().toLocaleTimeString()}.`);
});

restoreButton.addEventListener('click', async () => {
const savedConfiguration = localStorage.getItem(storageKey);
if (!savedConfiguration) return;

// parse() applies a serialized configuration to the loaded product.
const isRestored = await configurator.parse(JSON.parse(savedConfiguration));
showMessage(isRestored ? 'Saved configuration restored.' : 'The saved configuration could not be restored.', !isRestored);
});

function updateRestoreButton() {
restoreButton.disabled = !localStorage.getItem(storageKey);
}

function showMessage(text, isError = false) {
message.textContent = text;
message.hidden = !text;
message.className = `message ${isError ? 'message--error' : 'message--success'}`;
}

updateRestoreButton();
}

In a webshop: save with the cart item​

In a webshop, you save the configuration together with the cart item, so you can show it in the cart, edit it later and pass it on with the order. Send it to your backend when the shopper adds the product to the cart:

// Adding to the cart: send the configuration with the cart item to your own backend.
async function addToCart() {
const configuration = await configurator.serialize();

await fetch('/your-shop/cart/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId, quantity: 1, configuration }),
});
}

// Editing a cart item: load the product, then restore the configuration once it is READY.
async function editCartItem(cartItem) {
await configurator.parse(cartItem.configuration);
}

The /your-shop/cart/items endpoint is your own; the SDK doesn't prescribe how you store configurations.

Share configurations with snapshots​

A snapshot is a configuration that is saved in Expivi, with an ID. Expivi creates one when a shopper requests a quote, and the quote email can link to it.

To restore a snapshot, pass its ID as the snapshotId option. The configurator then restores it while the product loads, before it reports READY:

const snapshotId = new URLSearchParams(window.location.search).get('snapshotId') ?? undefined;

const configurator = new ProductConfigurator({
apiBaseUrl,
apiToken,
snapshotId,
// Expivi uses this to build the links to a snapshot, such as in quote emails.
getConfigurationLink: (id) => `${window.location.origin}${window.location.pathname}?snapshotId=${id}`,
});

Without getConfigurationLink, the link is the URL of the page the shopper was on, with a snapshotId parameter added. Set it when that URL is not the right one, for example to link to the product's canonical URL. Either way, the link opens your product page, where the snapshotId parameter restores the configuration. To open a snapshot after the product has loaded, call configurator.loadSnapshot(snapshotId).

The example page passes both options:

src/pages/save-and-share.js
import '../shared/setup.js';

import { mountSaveConfiguration } from '../components/save-configuration.js';
import { mountProductConfigurator, startConfigurator } from '../shared/configurator.js';
import { renderShopHeader } from '../shared/navigation.js';

renderShopHeader('save-and-share');

// Configuration links from Expivi (for example in quote emails) carry a snapshot id.
// Passing it to the configurator restores that configuration while the product loads.
const snapshotId = new URLSearchParams(window.location.search).get('snapshotId') ?? undefined;

startConfigurator({
options: {
snapshotId,
// Expivi uses this to build the configuration links it sends, so they open this page.
getConfigurationLink: (id) => `${window.location.origin}${window.location.pathname}?snapshotId=${id}`,
},
onReady(configurator) {
mountProductConfigurator(configurator);
mountSaveConfiguration(document.querySelector('#save-configuration'), configurator);
},
});

document.querySelector('#snapshot-info').textContent = snapshotId
? `Opened snapshot ${snapshotId}.`
: 'Open this page with ?snapshotId=… to load a shared configuration.';

To restore a configuration that is saved in Expivi with an identifier, pass it as the productConfigurationIdentifier option instead. When both are set, snapshotId wins.