Skip to content

shopware/frontends - helpers

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.

ts
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

ts
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 ​

ts
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 ​

ParameterTypeDescription
urlstringCSS url() string containing the background image URL
element{ backgroundMedia?: { metaData?: { width?: number; height?: number } } }CMS section or block object with media metadata
optionsBackgroundImageOptions (optional)Format and quality settings

BackgroundImageOptions ​

ts
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 ​

ts
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 ​

ParameterTypeDescription
srcstring | undefinedBase image URL
widthsnumber[] (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 ​

ts
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 ​

ParameterTypeDescription
srcstring | undefinedBase 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.8.0 ​

Minor Changes ​

  • #2574 2ddf156 Thanks @mkucmus! - Add getCategoryFilterAggregations() and getCategoryFilterPostFilter() to request category aggregations for product listings and filter by category without reducing the aggregations. excludeRootCategory() drops the sales channel entry point from the category entities, and the CATEGORY_AGGREGATION_NAME / CATEGORY_COUNTS_AGGREGATION_NAME / CATEGORY_PARENTS_AGGREGATION_NAME constants are exported for consumers that build the aggregations themselves.

    getListingFilters (@beta) merges the categories and categories-counts response aggregations into a single categories filter with a product count per category. This changes the shape of that filter for listings that already requested a categories aggregation: the entities are sorted by count (highest first) instead of keeping the response order, each entity gains a count, the filter no longer carries the aggregation's apiAlias, and categories-counts is no longer returned as a filter of its own.

Patch Changes ​

  • #2598 204c8f4 Thanks @dependabot! - Fix Nuxt plugin injection typing for Nuxt 4.5 and maintenance mode error handling.

API ​

normalizePath ​

ts
export function normalizePath(path: string): string

source code

isTechnicalPath ​

ts
export function isTechnicalPath(path: string): boolean

source code

isTechnicalUrl ​

Check whether an absolute or relative URL points to a technical Shopware route. Query parameters and fragments are ignored.

ts
export function isTechnicalUrl(
  url: string,
  baseUrl = "http://localhost",
): boolean

source code

getRouteFromPathInfo ​

ts
export function getRouteFromPathInfo(
  path: string,
): RouteInfoFromPathInfo | null

source code

getCanonicalPathForTechnicalPath ​

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.

ts
export function getCanonicalPathForTechnicalPath(
  path: string,
  seoUrl?: object | null,
): string | null

source code

getMedia ​

Prepare media object

ts
export function getMedia<
  T extends {
    downloads?: Array<{
      id: string;
      accessGranted: boolean;
      media: {
        fileName: string;
        fileExtension: string;
      };
    }>;
  },
>(lineItem: T)

source code

getSmallestThumbnailUrl ​

Returns the smallest thumbnail url from the media object or the media.url if no thumbnails are available

ts
export function getSmallestThumbnailUrl<
  T extends {
    thumbnails?: Array<{
      width: number;
      url: string;
    }>;
    url?: string;
  },
>(media?: T): string | undefined

source code

encodeUrlPath ​

Encodes URL pathname to handle special characters (spaces, commas, etc.)

ts
export function encodeUrlPath(urlString: string): string

source code

generateCdnSrcSet ​

Generates a srcset string using CDN width-based resizing. Useful as a fallback when media has no pre-generated thumbnails.

ts
export function generateCdnSrcSet(
  src: string | undefined,
  widths: number[] = [400, 800, 1200, 1600],
  options?: { format?: string; quality?: number },
): string | undefined

source code

buildCdnImageUrl ​

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.

ts
export function buildCdnImageUrl(
  src: string | undefined,
  dimensions: { width: number; height: number },
  options?: { format?: string; quality?: number },
): string

source code

getSrcSetForMedia ​

Returns the srcset attribute for the image, for available breakpoints

ts
export function getSrcSetForMedia<
  T extends {
    thumbnails?: Array<{
      width: number;
      url: string;
    }>;
  },
>(media?: T): string | undefined

source code

downloadFile ​

Download file

ts
export function downloadFile<T>(file: T, name: string)

source code

canUseQuoteActions ​

ts
export function canUseQuoteActions<
  T extends {
    stateMachineState?: {
      technicalName: string;
    };
  },
>(quote: T)

source code

urlIsAbsolute ​

ts
export function urlIsAbsolute(url: string)

source code

relativeUrlSlash ​

Add/remove slash from the relative path

ts
export function relativeUrlSlash(relativeUrl: string, slash = true)

source code

getTranslatedProperty ​

Get translated property from the given object.

ts
export function getTranslatedProperty<T>(
  element: T | undefined | null | never,
  property: keyof T,
): string

source code

getBiggestThumbnailUrl ​

Returns the biggest thumbnail url from the media object

ts
export function getBiggestThumbnailUrl<
  T extends {
    thumbnails?: Array<{
      width: number;
      url: string;
    }>;
  },
>(media?: T): string | undefined

source code

getCmsLayoutConfiguration ​

Get layout configuration for CMS content

ts
export function getCmsLayoutConfiguration<
  T extends CmsBlock | CmsSection | CmsSlot,
>(content: T): LayoutConfiguration

source code

expand LayoutConfiguration
ts
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 ​

ts
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;
};

source code

getProductListingFromCmsPage ​

Extracts the product listing data from a CMS page structure. Useful for SSR to get listing data early before components render.

ts
export function getProductListingFromCmsPage<T = unknown>(
  cmsPage: CmsPageStructure,
): T | null

source code

getCmsEntityObject ​

Returns the main page object depending of the type of the CMS page.

ts
export function getCmsEntityObject(
  response: CmsPageResponse,
): Product | Category | LandingPage

source code

isProduct ​

Predicate function to check if the entity is a product.

ts
export function isProduct<T extends { apiAlias: string }>(
  entity: T | Product,
): entity is Product

source code

isCategory ​

ts
export function isCategory<T extends { apiAlias: string }>(
  entity: T | Category,
): entity is Category

source code

isLandingPage ​

ts
export function isLandingPage<T extends { apiAlias: string }>(
  entity: T | LandingPage,
): entity is LandingPage

source code

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.

ts
export function excludeRootCategory<T extends { id: string }>(
  entities: T[] | undefined | null,
  rootCategoryId: string | undefined | null,
): T[]

source code

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.

ts
export function getCategoryFilterAggregations(): Array<
  CategoryEntityAggregation | CategoryCountsAggregation
>

source code

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).

ts
export function getCategoryFilterPostFilter(categoryIds: string[]): {
  field: string;
  type: "equalsAny";
  value: string;
}

source code

getCategoryUrl ​

Get URL for category. Some link

ts
export function getCategoryUrl<
  T extends {
    type: string;
    externalLink?: string;
    seoUrls?: { seoPathInfo: string }[];
    internalLink?: string;
    id: string;
    linkType?: string;
  },
>(category: T): string

source code

getProductFreeShipping ​

Get product free shipping property

ts
export function getProductFreeShipping<
  T extends {
    shippingFree: boolean;
  },
>(product?: T): boolean

source code

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:

html
<RouterLink :to="getCategoryRoute(navigationElement)">
ts
export function getCategoryRoute<
  T extends {
    type: string;
    externalLink?: string;
    seoUrls?: { seoPathInfo: string }[];
    internalLink?: string;
    id: string;
    linkType?: string;
  },
>(category: T)

source code

getCategoryBreadcrumbs ​

Gather breadcrumbs from category

ts
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;
  },
)

source code

getProductName ​

ts
export function getProductName<
  T extends {
    name: string;
  },
>({ product }: { product?: T } = {}): string | null

source code

getProductUrl ​

Get product url. The priority is SEO url and then technical url.

ts
export function getProductUrl<
  T extends {
    id: string;
    seoUrls?: Array<{
      seoPathInfo?: string;
    }>;
  },
>(product?: T): string

source code

getMainImageUrl ​

gets the cover image

ts
export function getMainImageUrl<
  T extends
    | {
        cover: {
          media?: {
            url: string;
          };
        };
      }
    | {
        media?: Array<{
          media?: {
            url?: string;
          };
        }>;
      }
    | {
        cover: {
          url: string;
        };
      }
    | {
        cover: null;
      },
>(object: T): string

source code

getProductTierPrices ​

Get the prices depending on quantity added to cart. Tier prices can be set in Advanced pricing tab in Product view (admin panel)

ts
export function getProductTierPrices<
  T extends {
    calculatedPrices?: Array<{
      unitPrice: number;
      quantity: number;
    }>;
  },
>(product?: T): TierPrice[]

source code

getProductRatingAverage ​

Get product rating average property

ts
export function getProductRatingAverage<T extends { ratingAverage: number }>(
  product: T,
): number | null

source code

getProductReviews ​

Format product reviews to ui-interfaces

ts
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[]

source code

getProductCalculatedListingPrice ​

Get the calculated list price

ts
export function getProductCalculatedListingPrice<
  T extends {
    calculatedPrice?: CalculatedPrice;
    calculatedPrices?: CalculatedPrice[];
  },
>(product?: T): number | undefined

source code

getCategoryImageUrl ​

gets the cover image

ts
export function getCategoryImageUrl<
  T extends {
    media?: { url: string };
    type: string;
  },
>(category: T): string

source code

getProductRoute ​

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.

ts
export function getProductRoute<
  T extends {
    id: string;
    seoUrls?: Array<{
      seoPathInfo?: string;
    }>;
  },
>(product?: T)

source code

isProductOnSale ​

Checks if a product is on sale based on its price percentage

ts
export function isProductOnSale(product: {
  calculatedPrice: {
    listPrice?: {
      percentage?: number;
    } | null;
  };
}): boolean

source code

isProductTopSeller ​

Checks if a product is marked as a top seller

ts
export function isProductTopSeller(product: {
  markAsTopseller?: boolean;
}): boolean

source code

getProductManufacturerName ​

Gets the translated name of the product manufacturer

ts
export function getProductManufacturerName(
  product: ProductWithManufacturer,
): string

source code

getProductFromPrice ​

ts
export function getProductFromPrice<
  T extends {
    calculatedPrice?: CalculatedPrice;
    calculatedPrices?: CalculatedPrice[];
  },
>(product: T): number | undefined

source code

isMaintenanceMode ​

ts
export function isMaintenanceMode<
  T extends {
    code?: string;
  },
>(errors: T[]): boolean

source code

getFormattedPrice ​

Get formatted price

ts
export function getFormattedPrice(
  value: string | number,
  currency: string,
  options: Options = {
    direction: "ltr",
    removeDecimals: false,
    removeCurrency: false,
  },
): string

source code

getCmsBreadcrumbs ​

Build the breadcrumbs for the CMS page

ts
export function getCmsBreadcrumbs<
  T extends {
    translated: {
      name: string;
    };
  },
>(page: T): { name: string }[]

source code

getCmsTranslate ​

Replace text placeholder with param value

ts
export function getCmsTranslate(
  key: string,
  params?: { [key: string]: string | number | null | undefined } | null,
)

source code

getListingFilters ​

TODO: Listing filters need better schema-backed types.

ts
export function getListingFilters<T extends Record<string, any>>(
  aggregations: T | undefined | null,
): ListingFilter[]

source code

getPaymentMethodIcon ​

Get payment method icon

ts
export function getPaymentMethodIcon<
  T extends {
    media?: {
      url: string;
    };
  },
>(paymentMethod: T)

source code

getShippingMethodIcon ​

Get shipping method icon

ts
export function getShippingMethodIcon<
  T extends {
    media?: {
      url: string;
    };
  },
>(shippingMethod: T)

source code

getShippingMethodDeliveryTime ​

Get shipping delivery time

ts
export function getShippingMethodDeliveryTime<
  T extends {
    deliveryTime?: {
      translated: {
        name: string;
      };
    };
  },
>(shippingMethod: T)

source code

getBackgroundImageUrl ​

ts
export function getBackgroundImageUrl<
  T extends {
    backgroundMedia?: {
      metaData?: {
        width?: number;
        height?: number;
      };
    };
  },
>(url: string, element: T, options?: BackgroundImageOptions): string

source code

buildUrlPrefix ​

ts
export function buildUrlPrefix(
  url: string | UrlRoute,
  prefix: string,
): UrlRouteOutput

source code

expand UrlRouteOutput
ts
export type UrlRouteOutput = Omit<UrlRoute, "path"> & { path: string };

getLanguageName ​

Get translated language name

ts
export function getLanguageName<
  T extends {
    translationCode?: { translated: { name: string } };
  },
>(language: T): string

source code

Was this page helpful?
UnsatisfiedSatisfied
Be the first to vote!
0.0 / 5  (0 votes)