{"id":27012030,"url":"https://github.com/salesforcecommercecloud/commerce-sdk-isomorphic","last_synced_at":"2026-04-29T23:00:48.081Z","repository":{"id":38082620,"uuid":"283238555","full_name":"SalesforceCommerceCloud/commerce-sdk-isomorphic","owner":"SalesforceCommerceCloud","description":"Browser \u0026 Node.js JavaScript client for B2C Commerce API","archived":false,"fork":false,"pushed_at":"2024-10-30T05:17:56.000Z","size":4840,"stargazers_count":43,"open_issues_count":15,"forks_count":20,"subscribers_count":5,"default_branch":"main","last_synced_at":"2024-10-30T08:34:01.313Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://salesforcecommercecloud.github.io/commerce-sdk-isomorphic/","language":"RAML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/SalesforceCommerceCloud.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"Contributing.md","funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-07-28T14:35:03.000Z","updated_at":"2024-10-10T16:00:04.000Z","dependencies_parsed_at":"2023-12-08T16:28:39.627Z","dependency_job_id":"ebebadc0-5dcc-4f55-832f-0697cf4c05bc","html_url":"https://github.com/SalesforceCommerceCloud/commerce-sdk-isomorphic","commit_stats":{"total_commits":199,"total_committers":20,"mean_commits":9.95,"dds":0.7386934673366834,"last_synced_commit":"c6448d9a19e40fe2d7f27cdb72f4652a6322600a"},"previous_names":[],"tags_count":30,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SalesforceCommerceCloud%2Fcommerce-sdk-isomorphic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SalesforceCommerceCloud%2Fcommerce-sdk-isomorphic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SalesforceCommerceCloud%2Fcommerce-sdk-isomorphic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SalesforceCommerceCloud%2Fcommerce-sdk-isomorphic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SalesforceCommerceCloud","download_url":"https://codeload.github.com/SalesforceCommerceCloud/commerce-sdk-isomorphic/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247174402,"owners_count":20896074,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-04-04T11:47:35.494Z","updated_at":"2026-03-03T18:04:20.328Z","avatar_url":"https://github.com/SalesforceCommerceCloud.png","language":"RAML","funding_links":[],"categories":[],"sub_categories":[],"readme":"# commerce-sdk-isomorphic\n\nThis SDK provides a Browser \u0026 Node.js JavaScript client for calling [B2C Commerce Shopper APIs](https://developer.salesforce.com/docs/commerce/commerce-api/overview).\n\n_For a Node.js only SDK that can also access Admin APIs checkout [Commerce SDK](https://github.com/SalesforceCommerceCloud/commerce-sdk)._\n\n## Documentation\n\nAn auto-generated [documentation site](https://salesforcecommercecloud.github.io/commerce-sdk-isomorphic/) provides comprehensive reference for all available endpoints and types across API classes. Following the v4.0.0 release, the underlying SDK file structure has been reorganized, introducing additional layers of imports/exports that may affect navigation.\n\n### Navigating the Documentation\n\n**For API Classes:**\n\n1. **Accessing API Classes:** Click on the API class name (e.g., `shopperProducts`) on the right hand side\n2. **Viewing Endpoints:** Scroll to the `Classes` section and click the corresponding API class link (e.g., `ShopperProducts`) to see available endpoints and their parameters\n3. **Type Definitions:** Scroll to the `Type aliases` section for available types\n\n**Utility Classes:** Utility classes and methods such as `clientConfig` and `helpers` maintain the same structure as previous versions.\n\n**NOTES:** \n\n1. **Type Access**: API class types are accessible through the `\u003capi_class\u003eTypes` namespace (e.g., `ShopperProductsTypes`). Individual types can be accessed as `ShopperProductsTypes.Product`.\n\n2. **Type References**: The `References` section under API classes in the generated documentation may show duplicate entries. This occurs because types are exported both at their original definition and under the API class namespace. Both references point to the same underlying type definition.\n\n## :warning: Planned API Changes :warning:\n\n### Shopper Context\n\nStarting July 31st 2024, all endpoints in the Shopper context API will require the `siteId` parameter for new customers. This field is marked as optional for backward compatibility and will be changed to mandatory tentatively by January 2025. You can read more about the planned change [here](https://developer.salesforce.com/docs/commerce/commerce-api/references/shopper-context?meta=Summary) in the notes section.\n\n### Shopper Login (SLAS)\n\nSLAS will soon require new tenants to pass `channel_id` as an argument for retrieving guest access tokens. You can read more about the planned change [here](https://developer.salesforce.com/docs/commerce/commerce-api/guide/slas.html#guest-tokens).\n\nPlease be aware that existing tenants are on a temporary allow list and will see no immediate disruption to service.  We do ask that all users seek to adhere to the `channel_id` requirement before the end of August to enhance your security posture before the holiday peak season.\n\nIn practice, we recommend:\n\n- For customers using the SLAS helpers with a public client, it is recommended to upgrade to at least `v1.8.0` of the `commerce-sdk-isomorphic`.\n- For customers using the SLAS helpers with a private client, it is recommended to upgrade to `v3.0.0` of the `commerce-sdk-isomorphic`.\n\n## :warning: Planned SDK Changes :warning:\n\n### Encoding path parameters\n\nIn the next major version release, the SDK will encode special characters (UTF-8 based on SCAPI guidelines) in path parameters by default. Please see the [Encoding special characters](#encoding-special-characters) section for more details.\n\n## Getting Started\n\n### Requirements\n\n- Node `^20.x` or `^22.x`\n- The SDK requires B2C Commerce API (SCAPI) to be configured. For more info see [Getting started with SCAPI](https://developer.salesforce.com/docs/commerce/commerce-api/guide/get-started.html).\n\n### Installation\n\n```bash\n# This package uses yarn, if you don't have yarn:\n# npm install -g yarn\nyarn install commerce-sdk-isomorphic\n```\n\n### Usage\n\n```javascript\nimport {helpers, ShopperLogin, ShopperSearch} from 'commerce-sdk-isomorphic';\n\nconst config = {\n  // SCAPI does not support CORS, so client side requests must use a reverse proxy.\n  proxy: 'https://localhost:3000',\n  parameters: {\n    clientId: '\u003cyour-client-id\u003e',\n    organizationId: '\u003cyour-org-id\u003e',\n    shortCode: '\u003cyour-short-code\u003e',\n    siteId: '\u003cyour-site-id\u003e',\n  },\n};\n\nconst {access_token} = await helpers.loginGuestUser({\n  slasClient: new ShopperLogin(config),\n  parameters: {redirectURI: `${config.proxy}/callback`}\n});\n\nconst shopperSearch = new ShopperSearch({\n  ...config,\n  headers: {authorization: `Bearer ${access_token}`},\n});\n\nconst searchResult = await shopperSearch.productSearch({\n  parameters: {q: 'shirt'},\n});\n```\n\n#### Fetch Options\n\nYou can configure how the SDK makes requests using the `fetchOptions` parameter. It is passed to [node-fetch](https://github.com/node-fetch/node-fetch/1#api) on the server and [whatwg-fetch](https://github.github.io/fetch/) on browser.\n\n```javascript\nconst https = require(\"https\");\n\nconst config = {\n  fetchOptions: {\n    // By default, requests made using the SDK do not include cookies.\n    credentials: \"include\",\n    timeout: 2000,\n    agent: new https.agent({ keepAlive: true }),\n  },\n};\n```\n\nFor more info, refer to the [documentation site](https://salesforcecommercecloud.github.io/commerce-sdk-isomorphic/).\n\n#### `throwOnBadResponse`\n\nWhen `true`, the SDK throws an `Error` on responses whose status is not 2xx or 304. By default, the value of this flag is `false` for backwards compatibility. Below is an example for accessing the error object via `e.response.json()`.\n\n```js\nconst config = {\n  throwOnBadResponse: true\n  // rest of the config object...\n};\n\nconst shopperSearch = new ShopperSearch({\n  ...config\n});\n\n// in an async function\ntry {\n  const searchResult = await shopperSearch.productSearch({\n    parameters: { q: \"shirt\" },\n  });\n} catch (e) {\n  const error = await e.response.json();\n  console.log(error);\n  // error is the JSON object - {error: \",,,\"}\n}\n```\n\n#### Additional Config Settings\n\n* `headers`: Headers to include with API requests.\n\n#### Custom Query Parameters\n\nYou can pass custom query parameters through the SDK to be used in [B2C Commerce API Hooks](https://developer.salesforce.com/docs/commerce/commerce-api/guide/extensibility_via_hooks.html). Custom query parameters must begin with `c_`:\n\n```javascript\nconst searchResult = await shopperSearch.productSearch({\n  parameters: {\n    q: 'shirt',\n    c_paramkey: '\u003cparam-value\u003e'\n  },\n});\n```\n\nInvalid query parameters that are not a part of the API and do not follow the `c_` custom query parameter convention are filtered from the request with a warning.\n\n#### Custom APIs\n\nThe SDK supports calling [B2C Commerce Custom APIs](https://developer.salesforce.com/docs/commerce/commerce-api/guide/custom-apis.html) with a helper function, `callCustomEndpoint`:\n\n```javascript\nimport pkg from \"commerce-sdk-isomorphic\";\nconst { helpers } = pkg;\n\nconst clientConfig = {\n  parameters: {\n    clientId: \"\u003cyour-client-id\u003e\",\n    organizationId: \"\u003cyour-org-id\u003e\",\n    shortCode: \"\u003cyour-short-code\u003e\",\n    siteId: \"\u003cyour-site-id\u003e\",\n  },\n  // If not provided, it'll use the default production URI:\n  // 'https://{shortCode}.api.commercecloud.salesforce.com/custom/{apiName}/{apiVersion}'\n  // path parameters should be wrapped in curly braces like the default production URI\n  baseUri: \"\u003cyour-base-uri\u003e\",\n};\n\n// Required params: apiName, endpointPath, shortCode, organizaitonId\n// Required path params can be passed into:\n// options.customApiPathParameters or clientConfig.parameters\nconst customApiPathParameters = {\n  apiName: \"loyalty-info\",\n  apiVersion: \"v1\", // defaults to v1 if not provided\n  endpointPath: \"customers\",\n};\n\nconst accessToken = \"\u003cINSERT ACCESS TOKEN HERE\u003e\";\n\nawait helpers.callCustomEndpoint({\n  options: {\n    method: \"GET\",\n    parameters: {\n      queryParameter: \"queryParameter1\",\n    },\n    headers: {\n      // Content-Type is defaulted to application/json if not provided\n      \"Content-Type\": \"application/json\",\n      authorization: `Bearer ${accessToken}`,\n    },\n    customApiPathParameters,\n  },\n  clientConfig,\n});\n\nawait helpers.callCustomEndpoint({\n  options: {\n    method: \"POST\",\n    parameters: {\n      queryParameter: \"queryParameter1\",\n    },\n    headers: {\n      authorization: `Bearer ${accessToken}`,\n    },\n    customApiPathParameters,\n    body: JSON.stringify({ data: \"data\" }),\n  },\n  clientConfig,\n});\n```\n\nFor more documentation about this helper function, please refer to the [commerce-sdk-isomorphic docs](https://salesforcecommercecloud.github.io/commerce-sdk-isomorphic/modules/helpers.html).\n\n#### Custom Fetch function\n\nYou can provide your own custom fetch function to intercept, log, or modify all SDK requests. This is useful for:\n- **Request/Response Logging**: Track all API calls for debugging and monitoring\n- **Request Interception**: Add custom headers, modify request URLs, or implement custom retry logic\n- **Error Handling**: Add custom error processing or transformation before responses reach your application\n- **Performance Monitoring**: Measure request/response times and track API performance metrics\n\n**Example with Logging:**\n```javascript\n// Custom fetch function with detailed logging\nconst customFetch = async (url, options) =\u003e {\n  console.log(`[SDK Request] ${options?.method || 'GET'} ${url}`);\n  console.log('[SDK Request Headers]', options?.headers);\n  if (options?.body) {\n    console.log('[SDK Request Body]', options.body);\n  }\n  \n  const startTime = Date.now();\n  const response = await fetch(url, options);\n  const duration = Date.now() - startTime;\n  \n  console.log(`[SDK Response] ${response.status} ${response.statusText} (${duration}ms)`);\n  console.log('[SDK Response Headers]', Object.fromEntries(response.headers.entries()));\n  \n  return response;\n};\n\nconst config = {\n  parameters: {\n    clientId: '\u003cyour-client-id\u003e',\n    organizationId: '\u003cyour-org-id\u003e',\n    shortCode: '\u003cyour-short-code\u003e',\n    siteId: '\u003cyour-site-id\u003e',\n  },\n  fetch: customFetch,\n};\n```\n\n#### Encoding special characters\n\nThe SDK currently single encodes special characters for query parameters in UTF-8 format based on SCAPI guidelines. However, the SDK does NOT encode path parameters, and will require the developer to encode any path parameters with special characters.\n\nAdditionally, SCAPI has special characters that should be double encoded, specifically `%` and `,`:\n- `%` should always be double encoded\n- `,` should be double encoded when used as part of an ID/parameter string, and single encoded when used to differentiate items in a list \n\nThere is a helper function called `encodeSCAPISpecialCharacters` that can be utilized to single encode the SCAPI special characters and no other special characters.\n\nHere's an example where the `getCategory/getCategories` endpoints are called with a `categoryID` with special characters:\n```javascript\nimport pkg from \"commerce-sdk-isomorphic\";\nconst { helpers, ShopperProducts } = pkg;\n\nconst clientConfig = {\n  parameters: {\n    clientId: \"\u003cyour-client-id\u003e\",\n    organizationId: \"\u003cyour-org-id\u003e\",\n    shortCode: \"\u003cyour-short-code\u003e\",\n    siteId: \"\u003cyour-site-id\u003e\",\n  }\n};\n\nconst shopperProducts = new ShopperProducts({\n  ...clientConfig,\n  headers: {authorization: `Bearer \u003cinsert_access_token\u003e`}\n});\n\nconst categoryId = \"SpecialCharacter,%$^@\u0026$;()!123Category\";\n// \"SpecialCharacter%2C%25$^@\u0026$;()!123Category\"\nconst scapiSpecialEncodedId = helpers.encodeSCAPISpecialCharacters(categoryId);\n\n\n// id is a path parameter for API call:\n// \u003cbase-url\u003e/product/shopper-products/v1/organizations/{organizationId}/categories/{id}\nconst categoryResult = await shopperProducts.getCategory({\n  parameters: {\n    // No need to use `encodeURIComponent` as query parameters are single encoded by the SDK\n    // So the SCAPI special characters will end up double encoded as well\n    id: scapiSpecialEncodedId,\n  }\n});\n\nconsole.log(\"categoryResult: \", categoryResult);\n\n// `ids` are a query parameter and comma delimited to separate category IDs\nconst categoriesResult = await shopperProducts.getCategories({\n  parameters: {\n    // No need to use `encodeURIComponent` as query parameters are single encoded by the SDK\n    // So the SCAPI special characters will end up double encoded as well\n    // Commas that separate items in a list will end up single encoded\n    ids: `${scapiSpecialEncodedId},${scapiSpecialEncodedId}`,\n  }\n});\n\nconsole.log(\"categoriesResult: \", categoriesResult);\n```\n\n**NOTE: In the next major version release, path parameters will be single encoded by default**\n\n## License Information\n\nThe Commerce SDK Isomorphic is licensed under BSD-3-Clause license. See the [license](./LICENSE.txt) for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsalesforcecommercecloud%2Fcommerce-sdk-isomorphic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsalesforcecommercecloud%2Fcommerce-sdk-isomorphic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsalesforcecommercecloud%2Fcommerce-sdk-isomorphic/lists"}