shopware/frontends - helpers
Welcome to @shopware/helpers package.
For getting started documentation visit https://developer.shopware.com/frontends/
Documentation specific for this package: helpers
Reusable classes
The helpersCssClasses variable, defined in the cms/layoutClasses.ts helper file, comprises an array of class names utilized within the CMS.
To enhance type support, a union type HelpersCssClasses is defined, which encompasses all class names present in the helpersCssClasses array.
const visibilityMap: Record<CmsVisibility, HelpersCssClasses> = {
mobile: "max-md:hidden",
tablet: "md:max-lg:hidden",
desktop: "lg:hidden",
};These classes can be integrated into a custom template, thereby ensuring consistency across different packages. For example as a safelist classes in unocss configuration file
import { helpersCssClasses } from "@shopware/helpers";
export default defineConfig({
safelist: helpersCssClasses,
});getBackgroundImageUrl helper
The getBackgroundImageUrl function generates optimized CSS url() values for CMS background images. It extracts the raw URL, calculates the appropriate dimensions based on the media metadata, and applies image transformation parameters.
Usage
import { getBackgroundImageUrl } from "@shopware/helpers";
const optimizedUrl = getBackgroundImageUrl(
"url(https://cdn.shopware.store/.../image.jpg)",
cmsBlockOrSection, // object with backgroundMedia.metaData.width/height
{ format: "webp", quality: 85 }, // optional
);
// => 'url("https://cdn.shopware.store/.../image.jpg?width=1000&fit=crop,smart&format=webp&quality=85")'Parameters
| Parameter | Type | Description |
|---|---|---|
url | string | CSS url() string containing the background image URL |
element | { backgroundMedia?: { metaData?: { width?: number; height?: number } } } | CMS section or block object with media metadata |
options | BackgroundImageOptions (optional) | Format and quality settings |
BackgroundImageOptions
type BackgroundImageOptions = {
format?: string; // "webp" | "avif" | "jpg" | "png"
quality?: number; // 0-100
};When format or quality are provided, they are appended as query parameters to the image URL. If omitted, only the dimension and fit parameters are applied.
generateCdnSrcSet helper
Generates an HTML srcset string using CDN width-based resizing. Useful as a fallback when media has no pre-generated thumbnails — the CDN handles on-the-fly resizing via query parameters.
Usage
import { generateCdnSrcSet } from "@shopware/helpers";
const srcset = generateCdnSrcSet(
"https://cdn.shopware.store/.../image.jpg",
[400, 800, 1200, 1600], // optional, these are the defaults
{ format: "webp", quality: 85 }, // optional
);
// => "https://cdn.shopware.store/.../image.jpg?width=400&fit=crop,smart&format=webp&quality=85 400w, ...800w, ...1200w, ...1600w"Parameters
| Parameter | Type | Description |
|---|---|---|
src | string | undefined | Base image URL |
widths | number[] (optional) | Array of widths to generate (default: [400, 800, 1200, 1600]) |
options | { format?: string; quality?: number } (optional) | Format and quality settings |
Returns undefined if src is falsy or URL parsing fails.
buildCdnImageUrl helper
Builds an optimized CDN image URL with size parameters based on rendered element dimensions. Adds width or height (whichever is larger) rounded up to the nearest 100px, plus fit=crop,smart.
Usage
import { buildCdnImageUrl } from "@shopware/helpers";
const url = buildCdnImageUrl("https://cdn.shopware.store/.../image.jpg", {
width: 724,
height: 760,
});
// => "https://cdn.shopware.store/.../image.jpg?height=800&fit=crop,smart"Parameters
| Parameter | Type | Description |
|---|---|---|
src | string | undefined | Base image URL |
dimensions | { width: number; height: number } | Rendered element dimensions in pixels |
options | { format?: string; quality?: number } (optional) | Format and quality settings |
Returns an empty string if src is falsy. Returns the original src if URL parsing fails.
Changelog
Full changelog for stable version is available here
Latest changes: 1.9.0
Minor Changes
#2875
fa598c8Thanks @mateuszfl! - Resolve the technical URL of a standalone CMS layout,/page/cms/<id>(Shopware'sfrontend.cms.page.fullroute). Layouts that are not assigned to a category or landing page, like the legal pages from the basic information settings, have no SEO URL, and Shopware links them by this path, for example inllms.txtserved through/store-api/sales-channel-file/{fileName}.getRouteFromPathInfoandisTechnicalPathnow recognise the/page/cms/prefix, andvue-starter-templaterenders it with the new globalFrontendCmsPageFullcomponent, which loads the layout fromreadCms post /cms/{id}and marks the pagenoindex.#2668
2202e1cThanks @mateuszfl! - Support SEO URLs of headless (API type) sales channels. Since shopware/shopware#17991 headless sales channels persist their SEO URLs against thestore-api.*route family (store-api.product.detail,store-api.category.detail,store-api.landing-page.detail).useNavigationSearch().resolvePath()now maps those route names to theirfrontend.*equivalents, so page resolution works unchanged on a headless sales channel. The newgetFrontendRouteNamehelper in@shopware/helpersexposes the same mapping for custom resolvers.#2851
43a035fThanks @mdanilowicz! - Add three helpers that were previously only available inside composables:getListingFiltersQuery(filters)turns listing criteria into URL query params. Arrays are joined with|, and empty arrays and falsy values are left out. It is whatuseListing().filtersToQuerydoes, now usable outside a component.getCmsMeta(entity)returns the translatedtitle,metaTitle,metaDescriptionandkeywordsof a category, product or landing page, with an empty string for a missing field.getTotalPages(total, limit)returns the page count, or0whenlimitis not a positive number.
API
getTotalPages
Get the number of pages needed to show total items, limit per page. Returns 0 when limit is not a positive number.
export function getTotalPages(total: number, limit: number): numbergetFrontendRouteName
export function getFrontendRouteName(
routeName: string | undefined,
): string | undefinedgetTranslatedProperty
Get translated property from the given object.
export function getTranslatedProperty<T>(
element: T | undefined | null | never,
property: keyof T,
): stringdownloadFile
Download file
export function downloadFile<T>(file: T, name: string)getBiggestThumbnailUrl
Returns the biggest thumbnail url from the media object
export function getBiggestThumbnailUrl<
T extends {
thumbnails?: Array<{
width: number;
url: string;
}>;
},
>(media?: T): string | undefinednormalizePath
export function normalizePath(path: string): stringisTechnicalPath
export function isTechnicalPath(path: string): booleanisTechnicalUrl
Check whether an absolute or relative URL points to a technical Shopware route. Query parameters and fragments are ignored.
export function isTechnicalUrl(
url: string,
baseUrl = "http://localhost",
): booleangetRouteFromPathInfo
export function getRouteFromPathInfo(
path: string,
): RouteInfoFromPathInfo | nullgetCanonicalPathForTechnicalPath
Get the canonical path for a mapped technical Shopware URL.
Returns null for SEO URLs, synthetic technical fallbacks without an SEO mapping, and invalid mappings that would redirect to another technical URL.
export function getCanonicalPathForTechnicalPath(
path: string,
seoUrl?: object | null,
): string | nullgetSmallestThumbnailUrl
Returns the smallest thumbnail url from the media object or the media.url if no thumbnails are available
export function getSmallestThumbnailUrl<
T extends {
thumbnails?: Array<{
width: number;
url: string;
}>;
url?: string;
},
>(media?: T): string | undefinedrelativeUrlSlash
Add/remove slash from the relative path
export function relativeUrlSlash(relativeUrl: string, slash = true)canUseQuoteActions
export function canUseQuoteActions<
T extends {
stateMachineState?: {
technicalName: string;
};
},
>(quote: T)urlIsAbsolute
export function urlIsAbsolute(url: string)encodeUrlPath
Encodes URL pathname to handle special characters (spaces, commas, etc.)
export function encodeUrlPath(urlString: string): stringgenerateCdnSrcSet
Generates a srcset string using CDN width-based resizing. Useful as a fallback when media has no pre-generated thumbnails.
export function generateCdnSrcSet(
src: string | undefined,
widths: number[] = [400, 800, 1200, 1600],
options?: { format?: string; quality?: number },
): string | undefinedbuildCdnImageUrl
Builds an optimized CDN image URL with size parameters. Adds width or height (whichever is larger, width if equal) rounded up to the nearest 100px.
export function buildCdnImageUrl(
src: string | undefined,
dimensions: { width: number; height: number },
options?: { format?: string; quality?: number },
): stringgetSrcSetForMedia
Returns the srcset attribute for the image, for available breakpoints
export function getSrcSetForMedia<
T extends {
thumbnails?: Array<{
width: number;
url: string;
}>;
},
>(media?: T): string | undefinedgetMedia
Prepare media object
export function getMedia<
T extends {
downloads?: Array<{
id: string;
accessGranted: boolean;
media: {
fileName: string;
fileExtension: string;
};
}>;
},
>(lineItem: T)excludeRootCategory
Category filter entities without the sales channel entry point.
That root category is an ancestor of every product's category tree, so it matches the whole result set and filtering by it changes nothing. Opt in per listing by passing sessionContext.salesChannel.navigationCategoryId; without an id the entities are returned unchanged.
export function excludeRootCategory<T extends { id: string }>(
entities: T[] | undefined | null,
rootCategoryId: string | undefined | null,
): T[]getCategoryFilterAggregations
Category aggregations for a listing filter: an entity categories agg plus a flat categories-counts terms agg. Kept flat because the ES search route returns no buckets once a nested sub-agg is attached, so variants overcount.
export function getCategoryFilterAggregations(): Array<
CategoryEntityAggregation | CategoryCountsAggregation
>getCategoryFilterPostFilter
Criteria post-filter entry narrowing a product listing to the given category ids. Sent as a post-filter, it does not reduce the category aggregations from getCategoryFilterAggregations, so all category options stay visible while results are filtered (standard faceted behavior).
export function getCategoryFilterPostFilter(categoryIds: string[]): {
field: string;
type: "equalsAny";
value: string;
}getCmsLayoutConfiguration
Get layout configuration for CMS content
export function getCmsLayoutConfiguration<
T extends CmsBlock | CmsSection | CmsSlot,
>(content: T): LayoutConfigurationexpand LayoutConfiguration
export type LayoutConfiguration = {
layoutStyles: {
backgroundColor?: string | null;
backgroundImage?: string | null;
backgroundSize?: string | null;
sizingMode?: string | null;
marginBottom?: string | null | undefined;
marginLeft?: string | null | undefined;
marginRight?: string | null | undefined;
marginTop?: string | null | undefined;
};
cssClasses: {
[cssClass: string]: boolean;
} | null;
};LayoutConfiguration
export type LayoutConfiguration = {
layoutStyles: {
backgroundColor?: string | null;
backgroundImage?: string | null;
backgroundSize?: string | null;
sizingMode?: string | null;
marginBottom?: string | null | undefined;
marginLeft?: string | null | undefined;
marginRight?: string | null | undefined;
marginTop?: string | null | undefined;
};
cssClasses: {
[cssClass: string]: boolean;
} | null;
};getProductListingFromCmsPage
Extracts the product listing data from a CMS page structure. Useful for SSR to get listing data early before components render.
export function getProductListingFromCmsPage<T = unknown>(
cmsPage: CmsPageStructure,
): T | nullgetCmsEntityObject
Returns the main page object depending of the type of the CMS page.
export function getCmsEntityObject(
response: CmsPageResponse,
): Product | Category | LandingPageisProduct
Predicate function to check if the entity is a product.
export function isProduct<T extends { apiAlias: string }>(
entity: T | Product,
): entity is ProductisCategory
export function isCategory<T extends { apiAlias: string }>(
entity: T | Category,
): entity is CategoryisLandingPage
export function isLandingPage<T extends { apiAlias: string }>(
entity: T | LandingPage,
): entity is LandingPagegetProductFreeShipping
Get product free shipping property
export function getProductFreeShipping<
T extends {
shippingFree: boolean;
},
>(product?: T): booleangetMainImageUrl
gets the cover image
export function getMainImageUrl<
T extends
| {
cover: {
media?: {
url: string;
};
};
}
| {
media?: Array<{
media?: {
url?: string;
};
}>;
}
| {
cover: {
url: string;
};
}
| {
cover: null;
},
>(object: T): stringgetProductName
export function getProductName<
T extends {
name: string;
},
>({ product }: { product?: T } = {}): string | nullgetProductReviews
Format product reviews to ui-interfaces
export function getProductReviews<
T extends {
id: string;
productReviews?: Array<{
id: string;
externalUser?: string;
customerId?: string;
createdAt: string;
content: string;
points?: number;
}>;
},
>({ product }: { product?: T } = {}): UiProductReview[]getProductUrl
Get product url. The priority is SEO url and then technical url.
export function getProductUrl<
T extends {
id: string;
seoUrls?: Array<{
seoPathInfo?: string;
}>;
},
>(product?: T): stringgetProductTierPrices
Get the prices depending on quantity added to cart. Tier prices can be set in Advanced pricing tab in Product view (admin panel)
export function getProductTierPrices<
T extends {
calculatedPrices?: Array<{
unitPrice: number;
quantity: number;
}>;
},
>(product?: T): TierPrice[]getProductRatingAverage
Get product rating average property
export function getProductRatingAverage<T extends { ratingAverage: number }>(
product: T,
): number | nullgetProductCalculatedListingPrice
Get the calculated list price
export function getProductCalculatedListingPrice<
T extends {
calculatedPrice?: CalculatedPrice;
calculatedPrices?: CalculatedPrice[];
},
>(product?: T): number | undefinedgetProductFromPrice
export function getProductFromPrice<
T extends {
calculatedPrice?: CalculatedPrice;
calculatedPrices?: CalculatedPrice[];
},
>(product: T): number | undefinedgetProductRoute
Get product route information for Vue router.
Returns product URL and route informations for resolving SEO url. Use it with combination of <RouterLink> or <NuxtLink> in Vue.js or Nuxt.js projects.
export function getProductRoute<
T extends {
id: string;
seoUrls?: Array<{
seoPathInfo?: string;
}>;
},
>(product?: T)isProductOnSale
Checks if a product is on sale based on its price percentage
export function isProductOnSale(product: {
calculatedPrice: {
listPrice?: {
percentage?: number;
} | null;
};
}): booleanisProductTopSeller
Checks if a product is marked as a top seller
export function isProductTopSeller(product: {
markAsTopseller?: boolean;
}): booleangetCategoryImageUrl
gets the cover image
export function getCategoryImageUrl<
T extends {
media?: { url: string };
type: string;
},
>(category: T): stringgetCategoryUrl
Get URL for category. Some link
export function getCategoryUrl<
T extends {
type: string;
externalLink?: string;
seoUrls?: { seoPathInfo: string }[];
internalLink?: string;
id: string;
linkType?: string;
},
>(category: T): stringgetCategoryBreadcrumbs
Gather breadcrumbs from category
export function getCategoryBreadcrumbs<
T extends {
translated?: {
breadcrumb?: string[];
};
breadcrumb?: string[];
},
>(
category: T,
options?: {
/**
* Start at specific index if your navigation
* contains root names which should not be visible.
*/
startIndex?: number;
},
)getCategoryRoute
Get category/navigation route information for Vue Router.
Returns category or navigation URL and route informations for resolving SEO url. Use it with combination of <RouterLink> or <NuxtLink> in Vue.js or Nuxt.js projects.
Example:
<RouterLink :to="getCategoryRoute(navigationElement)">export function getCategoryRoute<
T extends {
type: string;
externalLink?: string;
seoUrls?: { seoPathInfo: string }[];
internalLink?: string;
id: string;
linkType?: string;
},
>(category: T)getProductManufacturerName
Gets the translated name of the product manufacturer
export function getProductManufacturerName(
product: ProductWithManufacturer,
): stringgetListingFiltersQuery
Turn listing criteria into URL query params. Arrays are joined with |, empty arrays and falsy values are left out.
export function getListingFiltersQuery<T extends object>(
filters: T,
): Record<string, unknown>getShippingMethodDeliveryTime
Get shipping delivery time
export function getShippingMethodDeliveryTime<
T extends {
deliveryTime?: {
translated: {
name: string;
};
};
},
>(shippingMethod: T)getShippingMethodIcon
Get shipping method icon
export function getShippingMethodIcon<
T extends {
media?: {
url: string;
};
},
>(shippingMethod: T)getPaymentMethodIcon
Get payment method icon
export function getPaymentMethodIcon<
T extends {
media?: {
url: string;
};
},
>(paymentMethod: T)getFormattedPrice
Get formatted price
export function getFormattedPrice(
value: string | number,
currency: string,
options: Options = {
direction: "ltr",
removeDecimals: false,
removeCurrency: false,
},
): stringbuildUrlPrefix
export function buildUrlPrefix(
url: string | UrlRoute,
prefix: string,
): UrlRouteOutputexpand UrlRouteOutput
export type UrlRouteOutput = Omit<UrlRoute, "path"> & { path: string };getBackgroundImageUrl
export function getBackgroundImageUrl<
T extends {
backgroundMedia?: {
metaData?: {
width?: number;
height?: number;
};
};
},
>(url: string, element: T, options?: BackgroundImageOptions): stringisMaintenanceMode
export function isMaintenanceMode<
T extends {
code?: string;
},
>(errors: T[]): booleangetCmsBreadcrumbs
Build the breadcrumbs for the CMS page
export function getCmsBreadcrumbs<
T extends {
translated: {
name: string;
};
},
>(page: T): { name: string }[]getCmsTranslate
Replace text placeholder with param value
export function getCmsTranslate(
key: string,
params?: { [key: string]: string | number | null | undefined } | null,
)getCmsMeta
Get the translated name and meta fields of a category, product or landing page. A missing field is returned as an empty string.
export function getCmsMeta(
entity: CmsMetaFields & { translated?: CmsMetaFields | null },
): {
title: string;
metaTitle: string;
metaDescription: string;
keywords: string;
}getLanguageName
Get translated language name
export function getLanguageName<
T extends {
translationCode?: { translated: { name: string } };
},
>(language: T): stringgetListingFilters
TODO: Listing filters need better schema-backed types.
export function getListingFilters<T extends Record<string, any>>(
aggregations: T | undefined | null,
): ListingFilter[]