Adding Additional Currencies
Learn how to configure additional currencies in your storefront and switch between them.
By default, Alokai Storefront ships with both UI and logic to help implement dynamic currency switching:
LocationSelectorsModal
component that allows users to select their language and currencygetCurrencies
Unified Method that returns the list of available currencies based on your middleware configuration
Configuring currencies
First, to configure multiple currencies to your app, you can add a currencies
(compliant to ISO 4217) in your Unified Extension config and set defaultCurrency
value:
// apps/storefront-middleware/integrations/<integration>/extensions/unified.ts
export const unifiedApiExtension = createUnifiedExtension({
config: { currencies: ["USD", "EUR"], defaultCurrency: "USD", }, });
Fetching currencies data
The Unified Methods provide a getCurrencies()
method that your frontend can use to fetch the configured currency information in your middleware configuration:
const currencies = await sdk.unified.getCurrencies();
console.log(currencies); // { currencies: ["USD", "EUR"], defaultCurrency: "USD" }
Setting the vsf-currency
cookie
In order to properly fetch and return prices in a specific currency, the middleware looks for a cookie named vsf-currency
that contains the desired currency code. This currency code is then used for requests to the commerce platform.
To ensure that the correct currency is retrieved, vsf-currency
have to be set in a request headers on the initial application load. Depending on the framework you are using, you can set the vsf-currency
cookie in different ways:
In the App router application, you can set the vsf-currency
cookie by calling the getCurrencies
function from the root layout. Since the vsf-currency
cookie is set by an API response, this will ensure that the currency cookie is set on initial page setup:
// apps/storefront-unified-nextjs/app/[locale]/layout.tsx
import { getSdk } from '@/sdk';
export default async function RootLayout({ children, params: { locale } }) {
const currencies = await getSdk().unified.getCurrencies();
return (
<html lang={locale}>
<body>
{children}
</body>
</html>
);
}
Some platforms don't support currency switching at every stage of the transaction process
For instance, in Commercetools, the Cart object is initialized with a designated currency, which cannot be modified once set. Additionally, line items within the cart will not be recalculated to reflect a different currency.