### Install Dependencies and Start Server
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-express-minimal/README.md
Installs project dependencies and starts the Express server. Use this for local development setup.
```bash
npm ci
npm start
```
--------------------------------
### Project Setup Commands
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-typescript-minimal/README.md
Run these commands to install dependencies, start the development server, and push your bundle.
```bash
npm ci
npm start
npm run push
```
--------------------------------
### Install and Start MCP Server
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/README.md
Navigate to the MCP directory and run the start command to launch the server. This is necessary for manually testing with AI agent enabled IDEs that communicate via stdio.
```bash
cd {{dir-to-mcp}}
npm run start
```
--------------------------------
### Install and Start Test Project
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/test-commerce-sdk-react/README.md
Run these commands at the root of the monorepo to install dependencies and start the test project.
```bash
# run this at the root of the monorepo
npm ci
cd ./packages/test-commerce-sdk-react
npm start
```
--------------------------------
### Install All Dependencies
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/CONTRIBUTING.md
Use this command to install all project dependencies and link packages in the monorepo. Run this frequently during development.
```bash
npm ci
```
--------------------------------
### Start PWA Kit Project Locally
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-create-app/assets/bootstrap/js/README.MD
Use this command to start your PWA Kit project locally. It will automatically open your storefront in a browser.
```bash
npm start
```
--------------------------------
### Install Commerce SDK React
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md
Install the Commerce SDK React library and its peer dependency, @tanstack/react-query, using npm.
```bash
npm install @salesforce/commerce-sdk-react @tanstack/react-query
```
--------------------------------
### Install Dependencies
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-react-sdk/README.md
Installs all necessary dependencies for the PWA Kit React SDK. Ensure you have Node.js 16.11 or later and npm 8 or later.
```bash
npm i
```
--------------------------------
### Get Help with PWA Kit Create App
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-create-app/README.md
Use this command to view all available options and usage instructions for the create app tool.
```bash
npx @salesforce/pwa-kit-create-app --help
```
--------------------------------
### Create a New PWA Kit Project
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-create-app/README.md
Run this command in your terminal to start the project generation process.
```bash
npx @salesforce/pwa-kit-create-app
```
--------------------------------
### Core OpenTelemetry Module Setup
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/docs/distributed-tracing.md
This snippet outlines the core OpenTelemetry setup including the provider, propagator, and context manager. It emphasizes non-global instances and lazy initialization.
```javascript
import { NodeTracerProvider } from '@opentelemetry/node';
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { W3CTraceContextPropagator } from '@opentelemetry/core';
import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks';
import { MrtConsoleSpanExporter } from './mrt-console-span-exporter';
// Provider: NodeTracerProvider + SimpleSpanProcessor(MrtConsoleSpanExporter)
const provider = new NodeTracerProvider();
provider.addSpanProcessor(new SimpleSpanProcessor(new MrtConsoleSpanExporter()));
// Propagator: a module-level W3CTraceContextPropagator instance
const propagator = new W3CTraceContextPropagator();
// Context manager: a global AsyncHooksContextManager installed once, lazily
let contextManager = null;
export const isDistributedTracingEnabled = () => {
// Assume getOTELConfig() is defined elsewhere and returns config object
const config = getOTELConfig();
return config && config.enabled;
};
export const extractContext = (headers) => {
if (!isDistributedTracingEnabled()) {
return context.active(); // Fallback to active context
}
try {
return propagator.extract(context.active(), headers);
} catch (e) {
console.error('Failed to extract context:', e);
return context.active(); // Fallback on failure
}
};
export const withServerSpan = async (req, res, parentCtx, fn) => {
if (!isDistributedTracingEnabled()) {
return fn();
}
// Lazy initialization of context manager
if (!contextManager) {
contextManager = new AsyncHooksContextManager();
contextManager.enable();
// Assuming register() is available and used for context manager setup
// propagation.setGlobalPropagator(propagator); // This is NOT done globally
// contextManager.register(); // This is NOT done globally
}
const tracer = provider.getTracer('ssr.render');
const activeSpan = tracer.startSpan('ssr.render', { parent: parentCtx });
return contextManager.with(activeSpan, async () => {
try {
res.locals.__withChildSpan = withChildSpan; // For universal components
const result = await fn();
// Set attributes on the active span
setActiveSpanAttribute('http.route', res.locals.route.path);
return result;
} catch (error) {
activeSpan.recordException(error);
throw error;
} finally {
activeSpan.end();
}
});
};
export const withChildSpan = (name, fn) => {
if (!isDistributedTracingEnabled()) {
return fn();
}
// Ensure context manager is initialized if not already
if (!contextManager) {
contextManager = new AsyncHooksContextManager();
contextManager.enable();
}
const tracer = provider.getTracer('ssr.render'); // Or a more specific tracer name
const activeSpan = tracer.startSpan(name);
return contextManager.with(activeSpan, async () => {
try {
return await fn();
} catch (error) {
activeSpan.recordException(error);
throw error;
} finally {
activeSpan.end();
}
});
};
export const setActiveSpanAttribute = (key, value) => {
if (!isDistributedTracingEnabled()) {
return;
}
const span = context.active();
if (span) {
span.setAttribute(key, value);
}
};
export const getCurrentTraceparent = () => {
if (!isDistributedTracingEnabled()) {
return null;
}
const span = context.active();
if (span && span.spanContext && span.spanContext().traceId) {
// Constructing a traceparent string is more involved and depends on propagator details
// This is a simplified representation.
return `00-${span.spanContext().traceId}-00-01`;
}
return null;
};
// Placeholder for getOTELConfig and context/propagation modules
const getOTELConfig = () => ({ enabled: true }); // Mock implementation
const context = { active: () => ({ setAttribute: () => {} }) }; // Mock implementation
const propagation = { setGlobalPropagator: () => {} }; // Mock implementation
```
--------------------------------
### CommerceApiProvider Setup in React App
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md
Wrap your React application with CommerceApiProvider and QueryClientProvider for basic setup. Ensure you provide your client ID, organization ID, and other necessary configuration details.
```jsx
import {CommerceApiProvider} from '@salesforce/commerce-sdk-react'
import {QueryClient, QueryClientProvider} from '@tanstack/react-query'
const App = ({children}) => {
const queryClient = new QueryClient()
return (
{children}
)
}
export default App
```
--------------------------------
### View PWA Kit Dev Help
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-dev/README.md
Run this command to see all available commands for the PWA Kit developer tool. Ensure Node.js and npm are installed and meet the minimum version requirements.
```bash
npx @salesforce/pwa-kit-dev --help
```
--------------------------------
### Implementing a Layout Component
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/PAGE_DESIGNER_ARCHITECTURE.md
Provides an example of how to implement a layout component that renders child components within specified regions using the `Region` component.
```jsx
function TwoColumnLayout({component}) {
return (
)
}
```
--------------------------------
### Test Translations with Pseudo Locale
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-retail-react-app/translations/README.md
Run this script to start the local development server with the locale forced to a pseudo locale. This helps verify that all hardcoded strings are wrapped with formatting functions.
```bash
npm run start:pseudolocale
```
--------------------------------
### PageDesignerProvider Setup
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/PAGE_DESIGNER_ARCHITECTURE.md
Wraps the application to enable Page Designer's visual editing features. Requires client ID and target origin.
```jsx
{children}
```
--------------------------------
### Error Message for Missing SDK Client
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md
This is an example of the error message displayed when a required SDK client is not initialized or provided to the CommerceApiProvider. It helps in debugging configuration issues.
```text
Missing required client: shopperProducts. Please initialize shopperProducts class and provide it in CommerceApiProvider's apiClients prop.
```
--------------------------------
### Site Localization Configuration
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-retail-react-app/translations/README.md
Example of defining supported currencies, locales, and default settings for a site in `config/sites.js`. Ensure these settings align with your B2C Commerce instance.
```javascript
// config/sites.js
modules.exports = [
{
id: 'site-id',
l10n: {
supportedCurrencies: ['GBP', 'EUR', 'CNY', 'JPY'],
defaultCurrency: 'GBP',
supportedLocales: [
{
id: 'de-DE',
preferredCurrency: 'EUR'
},
{
id: 'en-GB',
preferredCurrency: 'GBP'
},
{
id: 'es-MX',
preferredCurrency: 'MXN'
},
// other locales
],
defaultLocale: 'en-GB'
}
}
]
```
--------------------------------
### Add PageDesignerInit to App Provider
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/PAGE_DESIGNER.md
This example demonstrates how to render the PageDesignerInit component within the PageDesignerProvider in the main application file (e.g., app/components/_app/index.jsx) to initialize Page Designer.
```jsx
{children}
```
--------------------------------
### Example Custom API JSON Configuration
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/README.md
Define custom API metadata in an api.json file for the scapi_custom_api_discovery tool. This includes API name, version, and endpoint details.
```json
{
"apiName": "reviews",
"apiVersion": "v1",
"cartridgeName": "plugin_custom_api_intro",
"endpointPath": "reviews",
"httpMethod": "GET",
"securityScheme": "bearer",
"baseUrl": "https://your-shortcode.api.commercecloud.salesforce.com/custom/reviews/v1"
}
```
--------------------------------
### Extend Recommended ESLint Config
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-dev/src/configs/eslint/README.md
To extend the recommended PWA Kit ESLint configuration, use `require.resolve()` with the full path to the config file. This is necessary because the config is not part of a package starting with 'eslint-config-'.
```javascript
module.exports = {
extends: [require.resolve('@salesforce/pwa-kit-dev/configs/eslint/recommended')]
}
```
--------------------------------
### Integrate CommerceApiProvider with PWA Kit
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md
Integrate the CommerceApiProvider into your PWA Kit application's AppConfig component. This setup is necessary for server-side data fetching and state management using React Query.
```jsx
// app/components/_app-config/index.jsx
import {CommerceApiProvider} from '@salesforce/commerce-sdk-react'
import {withReactQuery} from '@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-react-query'
const AppConfig = ({children}) => {
const headers = {
'correlation-id': correlationId
}
return (
{children}
)
}
// Set configuration options for react query.
// NOTE: This configuration will be used both on the server-side and client-side.
// retry is always disabled on server side regardless of the value from the options
const options = {
queryClientConfig: {
defaultOptions: {
queries: {
retry: false
},
mutations: {
retry: false
}
}
}
}
export default withReactQuery(AppConfig, options)
```
--------------------------------
### List Available Commands
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/internal-lib-build/README.md
Navigate to the internal-lib-build directory and execute the --help flag to view all available commands.
```bash
cd packages/internal-lib-build
./bin/internal-lib-build --help
```
--------------------------------
### Using useCommerceApi and useAccessToken
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md
Demonstrates how to fetch products using SCAPI clients initialized by `useCommerceApi` and an access token obtained via `useAccessToken`. Ensure you have the necessary imports and that the provider is configured.
```jsx
import {useCommerceApi, useAccessToken} from '@salesforce/commerce-sdk-react'
const Example = () => {
const api = useCommerceApi()
const {getTokenWhenReady} = useAccessToken()
const fetchProducts = async () => {
const token = await getTokenWhenReady()
const products = await api.shopperProducts.getProducts({
parameters: {ids: ids.join(',')},
headers: {
Authorization: `Bearer ${token}`
}
})
return products
}
}
```
--------------------------------
### Get Browser Geolocation Coordinates
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/src/data/hook-catalog.md
Use this hook to get the user's current geolocation coordinates. It provides loading and error states, and a refresh function.
```javascript
import React from 'react'
import {useGeolocation} from '@salesforce/retail-react-app/app/hooks/use-geo-location'
export default function GeolocationExample() {
const {coordinates, loading, error, refresh} = useGeolocation()
// Example:
// if (loading) return
Detecting location…
// if (error) return
Error: {String(error)}
// return (
//
//
{JSON.stringify(coordinates, null, 2)}
//
//
// )
}
```
--------------------------------
### New API Application Initialization
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/PAGE_DESIGNER.md
Demonstrates how to initialize the component registry at the application level in the new API.
```jsx
// _app/index.jsx
import {initializeRegistry} from './page-designer/registry'
initializeRegistry() // At module level, not in useEffect
```
--------------------------------
### Use Product Query Hook
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md
Demonstrates how to use the `useProduct` hook to fetch product data. Pass product ID and locale as parameters. Displays loading state and product name.
```jsx
import {useProduct} from '@salesforce/commerce-sdk-react'
const Example = () => {
const query = useProduct({
parameters: {
id: '25592770M',
locale: 'en-US'
}
})
return (
<>
isLoading: {query.isLoading}
name: {query.data?.name}
>
)
}
```
--------------------------------
### Run MCP Demo Commands
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/docs/cursor-integration-guide.md
Execute these commands to run the MCP server demo and observe its capabilities in code analysis and generation.
```bash
npm run demo # or: node demo.js
```
--------------------------------
### Deploy Project to Managed Runtime
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-express-minimal/README.md
Builds and pushes the project bundle to the Managed Runtime environment. Use this for deployment.
```bash
npm run push
```
--------------------------------
### Registering Component Importers with Fallbacks
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/PAGE_DESIGNER_ARCHITECTURE.md
Demonstrates how to register component importers using `registry.registerImporter`, including an optional fallback for skeleton loading states to improve user experience during initial load.
```javascript
registry.registerImporter(
'commerce_assets.banner',
() => import('./banner'),
() => import('./banner-skeleton') // Optional fallback
)
```
--------------------------------
### Send JSON-RPC Requests to MCP Server
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/README.md
Send JSON-RPC requests to the MCP server to interact with its tools. Examples include listing available tools and calling a specific tool with arguments.
```json
{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}
```
```json
{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "pwakit_get_dev_guidelines", "arguments": {}}}
```
--------------------------------
### Natural Language Commands for Code Generation
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/docs/cursor-integration-guide.md
Use natural language to instruct Cursor to insert or modify components. Examples include inserting a ProductCard or adding a modal with specific styling.
```plaintext
"Insert a ProductCard component after the imports in App.js"
"Add a modal component with Tailwind styling to this file"
"Create a new button component with these specifications: primary variant, medium size"
```
--------------------------------
### PWA Kit Loading Screen Logic
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-dev/src/ssr/server/loading-screen/index.html
This script handles the loading screen behavior. It checks for a 'loading' query parameter and waits for the application to be ready before redirecting to the specified path. It also includes functionality to animate fun facts displayed on the loading screen.
```javascript
(function() {
const url = new URL(window.location)
const loading = url.searchParams.get('loading')
if (loading === '1') {
const interval = 1000
const waitForReady = () => {
return new Promise((resolve) => {
const checkReady = () => {
fetch('/__mrt/status')
.then((res) => res.json())
.then((data) => {
if (data.ready) {
resolve()
} else {
setTimeout(checkReady, interval)
}
})
}
checkReady()
})
}
waitForReady().then(() => {
// Redirect to homepage if path is not defined
const path = url.searchParams.get('path') ?? ''
window.location = new URL(path, url.origin)
})
}
const animateFacts = () => {
const holdMs = 7000;
const transitionMs = 433;
const facts = document.querySelectorAll('.fun-fact');
facts.forEach((fact) => {
fact.style.transitionDuration = transitionMs + 'ms';
fact.classList.add('fun-fact--hidden');
});
let counter = 0;
const modulo = (x, y) => ((x % y) + y) % y
const update = () => {
const previous = modulo(counter - 1, facts.length)
const current = modulo(counter, facts.length)
facts[previous].classList.remove('fun-fact--show')
setTimeout(() => facts[previous].classList.add('fun-fact--hidden'), transitionMs)
facts[current].classList.remove('fun-fact--hidden')
setTimeout(() => facts[current].classList.add('fun-fact--show'), 50)
}
update();
setInterval(() => {
counter += 1;
update()
}, holdMs)
}
animateFacts()
})()
```
--------------------------------
### Run Linting
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/CONTRIBUTING.md
Execute the linting process to check code quality and style consistency across the project.
```bash
npm run lint
```
--------------------------------
### Dynamic Body and Parameters with useCustomMutation
Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md
Shows how to use `useCustomMutation` to dynamically set the request body and parameters, suitable for scenarios with changing inputs.
```jsx
import {useCustomMutation} from '@salesforce/commerce-sdk-react'
const clientConfig = {
parameters: {
clientId: 'CLIENT_ID',
siteId: 'SITE_ID',
organizationId: 'ORG_ID',
shortCode: 'SHORT_CODE'
},
proxy: 'http://localhost:8888/mobify/proxy/api'
};
const mutation = useCustomMutation({
options: {
method: 'POST',
customApiPathParameters: {
endpointPath: 'path/to/resource',
apiName: 'hello-world'
}
},
clientConfig,
rawResponse: false
});
// use it in a react component
const ExampleDynamicMutation = () => {
const [colors, setColors] = useState(['blue', 'green', 'white'])
const [selectedColor, setSelectedColor] = useState(colors[0])
return (
<>