Collection

An easy way to access and use Shopify Collection data within the Superfans SDK.

Description

The collection variable provides details about the collection on a product listing (PLP) page. It includes the collection ID, title, handle, description, image, and an optional search keyword.

This object is only available on PLP pages. Outside of a PLP context, it is null.

When the PLP is driven by a search keyword instead of a Shopify collection, collection.keyword is a non-empty string. When it is a normal collection listing, keyword is missing or an empty string.

Properties of collection

PropertyTypeScopeDescriptionExample
collection.idStringPLPUnique id of the collection.123457
collection.titleStringPLPName of the collection.Sample collection
collection.handleStringPLPUser-friendly slug used in the collection URL.sample-collection
collection.descriptionStringPLPDescription of the collection. Can include HTML.<p>Collection description</p>
collection.imageStringPLPCollection image URL. Can be missing.https://cdn.shopify.com/image.jpg
collection.keywordStringPLPSearch keyword for this listing, when the PLP is a keyword search rather than a collection. Empty or absent on a normal collection PLP.summer dress

Sample collection object

Normal collection PLP:

{
  "id": "123457",
  "title": "Sample collection",
  "handle": "sample-collection",
  "description": "<p>Collection description</p>",
  "image": "https://cdn.shopify.com/image.jpg",
  "keyword": ""
}

Keyword search PLP:

{
  "id": "",
  "title": "",
  "handle": "",
  "description": "",
  "image": "",
  "keyword": "summer dress"
}

Example Usage

const collection = Superfans.variables.collection;

if (!collection) {
  console.log("Not on a listing page.");
} else {
  const keyword = collection.keyword || "";

  if (keyword) {
    console.log(`Keyword listing: ${keyword}`);
  } else {
    console.log(`Collection: ${collection.title}`);
    console.log(`Handle: ${collection.handle}`);
  }
}

Best Practices

  1. Check for null: collection is only defined on PLP pages.
  2. Treat keyword as a string: Use collection.keyword || "". A non-empty value means this listing is a search-keyword PLP.
  3. Do not assume id / handle exist in keyword mode: Use keyword to search products, and id / handle to load a collection.
  4. Read-only fields: Do not modify collection properties.
  5. Use the handle for navigation: When opening a collection, pass collection.handle or collection.id to Superfans.actions.openCollection.

Caveats

  1. Context-dependent: collection is null outside PLP pages.
  2. Keyword vs collection listings: collection.keyword is a string, not an array. Empty string or missing means a normal collection page.
  3. Optional image: Some collections have no image. Check before using collection.image.
  4. HTML content: collection.description can contain HTML. Sanitize before injecting it into the DOM.

Did this page help you?