Vue Storefront is now Alokai! Learn More
Adding Additional Currencies

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 currency
  • getCurrencies 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:

middleware.config.ts
export const unifiedApiExtension = createUnifiedExtension<Context>()({
  normalizers,
  apiMethods: {
    ...methods<typeof normalizers>(),
  },
  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" }

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:

Next.js

We recommend setting the currency cookie in createGetServerSideProps.ts. This function is a wrapper around Next.js' getServerSideProps that the storefront can use to set request headers before fetching any data. For example, this code snippet will set the vsf-currency cookie to the default currency:

// createGetServerSideProps.ts
// ...
const { setCookie } = await import("cookies-next");

const currencies = await sdk.unified.getCurrencies();

setCookie("vsf-currency", currencies.defaultCurrency, {
  req: context.req,
  res: context.res,
});

// your getServerSideProps function will run after the cookie is set

Nuxt 3

In Nuxt 3, you can create a Nuxt plugin that will set the vsf-currency cookie on the server side during the initial page setup:

plugins/localization.ts
import { getCookie } from "h3";

export default defineNuxtPlugin((nuxtApp) => {
  // This plugin will run only on the server side
  if (import.meta.client) {
    return;
  }
  nuxtApp.hook("vue:setup", async () => {
    const { cookieNames } = useAppConfig();
    const event = useRequestEvent();
    const cookieCurrency = getCookie(event, cookieNames.currency);
    const { data: currenciesData, fetchCurrencies } = useCurrenciesData();

    if (!currenciesData.value) {
      await fetchCurrencies();
    }

    if (!cookieCurrency && currenciesData.value) {
      setCookie(
        event,
        cookieNames.currency,
        currenciesData.value.defaultCurrency,
      );
    }
  });
});

However, Nuxt's setCookie function will only set the cookie for response headers, but for the middleware to also get our vsf-currency cookie, it needs to be set for request headers. This can be achieved by creating a custom setCookie function that will set the cookie for both request and response headers:

plugins/localization.ts
import { type H3Event, setCookie as setResponseCookie, parseCookies } from "h3";

function setRequestCookie(event: H3Event, name: string, value: string) {
  const { headers } = event.node.req;
  const cookiesObject = {
    ...parseCookies(event),
    [name]: value,
  };

  try {
    headers.cookie = Object.entries(cookiesObject)
      .map(
        (item) =>
          `${encodeURIComponent(item[0])}=${encodeURIComponent(item[1])}`,
      )
      .join("; ");
  } catch {
    throw new Error(`Failed to set cookie ${name}=${value}`);
  }
}
function setCookie(event: H3Event, name: string, value: string) {
  setRequestCookie(event, name, value);
  setResponseCookie(event, name, value, {
    sameSite: "strict",
    secure: true,
  });
}

export default defineNuxtPlugin((nuxtApp) => {
  // ...
});

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.