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.
- Vanilla JS
- Vue
- React
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();
}
<script setup lang="ts">
import { ref } from 'vue';
import type { ProductConfigurator } from '@expivi/sdk';
import { expiviConfig } from '../shared/expivi.config';
/**
* 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.
*/
const props = defineProps<{ configurator: ProductConfigurator }>();
const storageKey = `expivi-configuration:${expiviConfig.productId}`;
const hasSavedConfiguration = ref(!!localStorage.getItem(storageKey));
const message = ref<{ text: string; isError: boolean } | null>(null);
async function save() {
// serialize() returns the full configuration as a plain, JSON-serializable object.
const configuration = await props.configurator.serialize();
localStorage.setItem(storageKey, JSON.stringify(configuration));
hasSavedConfiguration.value = true;
message.value = { text: `Configuration saved at ${new Date().toLocaleTimeString()}.`, isError: false };
}
async function restore() {
const savedConfiguration = localStorage.getItem(storageKey);
if (!savedConfiguration) return;
// parse() applies a serialized configuration to the loaded product.
const isRestored = await props.configurator.parse(JSON.parse(savedConfiguration));
message.value = isRestored
? { text: 'Saved configuration restored.', isError: false }
: { text: 'The saved configuration could not be restored.', isError: true };
}
</script>
<template>
<div class="button-row">
<button type="button" class="button" @click="save">Save configuration</button>
<button type="button" class="button button--secondary" :disabled="!hasSavedConfiguration" @click="restore">
Restore saved configuration
</button>
</div>
<p v-if="message" :class="['message', message.isError ? 'message--error' : 'message--success']" role="status">
{{ message.text }}
</p>
</template>
import { useState } from 'react';
import type { ProductConfigurator } from '@expivi/sdk';
import { expiviConfig } from '../shared/expivi.config';
const storageKey = `expivi-configuration:${expiviConfig.productId}`;
type Message = { text: string; isError: boolean };
/**
* 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.
*/
export default function SaveConfiguration({ configurator }: { configurator: ProductConfigurator }) {
const [hasSavedConfiguration, setHasSavedConfiguration] = useState(() => !!localStorage.getItem(storageKey));
const [message, setMessage] = useState<Message | null>(null);
async function save() {
// serialize() returns the full configuration as a plain, JSON-serializable object.
const configuration = await configurator.serialize();
localStorage.setItem(storageKey, JSON.stringify(configuration));
setHasSavedConfiguration(true);
setMessage({ text: `Configuration saved at ${new Date().toLocaleTimeString()}.`, isError: false });
}
async function restore() {
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));
setMessage(
isRestored
? { text: 'Saved configuration restored.', isError: false }
: { text: 'The saved configuration could not be restored.', isError: true },
);
}
return (
<>
<div className="button-row">
<button type="button" className="button" onClick={save}>
Save configuration
</button>
<button type="button" className="button button--secondary" disabled={!hasSavedConfiguration} onClick={restore}>
Restore saved configuration
</button>
</div>
{message && (
<p className={`message ${message.isError ? 'message--error' : 'message--success'}`} role="status">
{message.text}
</p>
)}
</>
);
}
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:
- Vanilla JS
- Vue
- React
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.';
<script setup lang="ts">
import ProductConfiguratorLayout from '../components/ProductConfiguratorLayout.vue';
import SaveConfiguration from '../components/SaveConfiguration.vue';
import ShopLayout from '../components/ShopLayout.vue';
import { useExpiviConfigurator } from '../composables/useExpiviConfigurator';
// 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;
const { configurator, hasError, missingConfig } = useExpiviConfigurator({
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}`,
});
</script>
<template>
<ShopLayout page-id="save-and-share">
<ProductConfiguratorLayout :configurator="configurator" :has-error="hasError" :missing-config="missingConfig">
<template #before-options="{ configurator }">
<section class="panel">
<h2 class="panel__title">Save for later</h2>
<SaveConfiguration :configurator="configurator" />
</section>
<section class="panel">
<h2 class="panel__title">Shared configurations</h2>
<p class="panel__note">
{{ snapshotId ? `Opened snapshot ${snapshotId}.` : 'Open this page with ?snapshotId=… to load a shared configuration.' }}
</p>
</section>
</template>
</ProductConfiguratorLayout>
</ShopLayout>
</template>
import ProductConfiguratorLayout from '../components/ProductConfiguratorLayout';
import SaveConfiguration from '../components/SaveConfiguration';
import ShopLayout from '../components/ShopLayout';
import { useExpiviConfigurator } from '../hooks/useExpiviConfigurator';
// 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;
export default function SaveAndSharePage() {
const { configurator, hasError, missingConfig } = useExpiviConfigurator({
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}`,
});
return (
<ShopLayout pageId="save-and-share">
<ProductConfiguratorLayout
configurator={configurator}
hasError={hasError}
missingConfig={missingConfig}
beforeOptions={(configurator) => (
<>
<section className="panel">
<h2 className="panel__title">Save for later</h2>
<SaveConfiguration configurator={configurator} />
</section>
<section className="panel">
<h2 className="panel__title">Shared configurations</h2>
<p className="panel__note">
{snapshotId
? `Opened snapshot ${snapshotId}.`
: 'Open this page with ?snapshotId=… to load a shared configuration.'}
</p>
</section>
</>
)}
/>
</ShopLayout>
);
}
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.