shopware/frontends - composables
Set of Vue.js composition functions that can be used in any Vue.js project. They provide state management, UI logic and data fetching and are the base for all guides in our building section.
Features
createShopwareContextmethod to create a Vue 3 plugin to install- State management
- Logic for UI
- Communication with Store-API via api-client package
Setup
Install npm packages (composables & api-client):
# Using pnpm
pnpm add @shopware/composables @shopware/api-client @shopware/api-gen
# Using yarn
yarn add @shopware/composables @shopware/api-client @shopware/api-gen
# Using npm
npm i @shopware/composables @shopware/api-client @shopware/api-genNow generate your types ysing the CLI:
pnpm shopware-api-gen generate --apiType=storeInitialize the api-client instance:
import { createAPIClient } from "@shopware/api-client";
import type { operations } from "#shopware";
export const apiClient = createAPIClient<operations>({
baseURL: "https://your-api-instance.com",
accessToken: "your-sales-channel-access-token",
});
// and then provide it in the Vue app
app.provide("apiClient", apiClient);Now, we can create a Vue 3 plugin to install a Shopware context in an app:
import { createShopwareContext } from "@shopware/composables";
// app variable in type of App
const shopwareContext = createShopwareContext(app, {
devStorefrontUrl: "https://your-sales-channel-configured-domain.com",
});
// register a plugin in a Vue instance
app.use(shopwareContext);Exclude @shopware/composables package from pre-building process:
// vite.config.js or .ts
...
optimizeDeps: {
exclude: ["@shopware/composables"],
},
...The example does not provide the session handling and that means you need to do few additional steps if you need to keep your session after the page reload (see the chapter below with 🍪)
Basic usage
Now you can use any composable function in your setup function:
<script setup>
import { useUser, useSessionContext } from "@shopware/composables/dist";
const { login } = useUser();
const { refreshSessionContext, sessionContext } = useSessionContext();
refreshSessionContext();
</script>
<template>
<pre>{{ sessionContext }}</pre>
<button @click="login({
username: "some-user",
password: "secret-passwd"
})">
Try to login!
</button>
</template>Session persistence with 🍪
By default, the API-Client is stateless, but accepts an optional context token as a parameter while initializing an instance. In order to keep a session, install some cookie parser to work with cookies easier:
# Using pnpm
pnpm add js-cookie
# Using yarn
yarn add js-cookie
# Using npm
npm i js-cookieLet's get back to the step where the api-client was initialized:
import { createAPIClient } from "@shopware/api-client";
import Cookies from "js-cookie";
import type { operations } from "#shopware";
const shopwareEndpoint = "https://demo-frontends.shopware.store/store-api";
export const apiClient = createAPIClient<operations>({
baseURL: shopwareEndpoint,
accessToken: "SWSCBHFSNTVMAWNZDNFKSHLAYW",
contextToken: Cookies.get("sw-context-token"),
});
apiClient.hook("onContextChanged", (newContextToken) => {
Cookies.set("sw-context-token", newContextToken, {
expires: 365, // days
path: "/",
sameSite: "lax",
secure: shopwareEndpoint.startsWith("https://"),
});
});Thanks to this, the session will be kept to the corresponding sw-context-token saved in the cookie, so it can be reachable also in the SSR. Check the example to see it in action:
TypeScript support
All composable functions are fully typed with TypeScript and they are registed globally in Nuxt.js application, so the type hinting will help you to work with all of them.
Links
👥 Community Discord (
#composable-frontend)
Changelog
Full changelog for stable version is available here
Latest changes: 1.12.0
Minor Changes
#2486
5678fb0Thanks @mkucmus! -useSessionContext: exposecurrentLocaleCode— the active language's locale code (e.g."en-GB"), read directly from the context'slanguageInfo. The current locale can now be derived from the session context alone, without loading the full language list viauseInternationalization().getAvailableLanguages()just to map the currentlanguageIdto a locale.#2473
22611e5Thanks @mkucmus! - Add an opt-incacheableReadsflag that routes anonymous Store API reads through their cacheable GET variants instead of POST. Criteria is compressed into the_criteriaquery param viaencodeForQueryfrom@shopware/api-client/helpers, which lets CDNs / reverse proxies / the browser cache the responses.Disabled by default — fully backwards compatible. Enable it in
nuxt.config(shopware: { cacheableReads: true }) or viacreateShopwareContext(app, { cacheableReads: true })for non-Nuxt setups. It is surfaced on the Shopware context and read by the affected composables; public composable signatures are unchanged.Affected composables:
useNavigation,useNavigationSearch,useCountries,useUser(country + salutation lookups),useSalutations,useInternationalization,useProductConfigurator,useProductSearch, anduseCategorySearch.advancedSearch.useListing(product-listing), single-categoryuseCategorySearch.search, anduseLandingSearchremain POST for now: the generated Store API schema does not type_criteriaon those GET routes (a Shopware OpenAPI gap). The backend does honor_criteriaon product-listing GET at runtime, so that one can be migrated later once the types are augmented.
Patch Changes
- #2462
8be060dThanks @mkucmus! -useProductAssociations: add optionalincludeSeoUrlsoption. Whentrue, the cross-selling request sendssw-include-seo-urls: trueso returned products include theseoUrlsassociation. Defaults tofalseto avoid extra backend overhead.