Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Ecommerce Frontend

The package provides a set of React utilities to help you manage your ecommerce frontend. These include context providers, hooks, and components to handle carts, products, and payments.

The following hooks and components are available:

Hook / Component

Description

EcommerceProvider

A context provider to wrap your application and provide the ecommerce context.

useCart

A hook to manage the cart state and actions.

useAddresses

A hook to fetch and manage products.

usePayments

A hook to manage the checkout process.

useCurrency

A hook to format prices based on the selected currency.

useEcommerce

A hook that encompasses all of the above in one.

EcommerceProvider

The EcommerceProvider component is used to wrap your application and provide the ecommerce context. It takes the following props:

Prop

Type

Description

addressesSlug

string

The slug of the addresses collection. Defaults to addresses.

api

object

API configuration for the internal fetches of the provider. More

cartsSlug

string

The slug of the carts collection. Defaults to carts.

children

ReactNode

The child components that will have access to the ecommerce context.

currenciesConfig

CurrenciesConfig

Configuration for supported currencies. See Currencies.

customersSlug

string

The slug of the customers collection. Defaults to users.

debug

boolean

Enable or disable debug mode. This will send more information to the console.

enableVariants

boolean

Enable or disable product variants support. Defaults to true.

paymentMethods

PaymentMethod[]

An array of payment method adapters for the client side. See Payment adapters.

syncLocalStorage

boolean object

Whether to sync the cart ID to local storage. Defaults to true. Takes an object for configuration

Example usage:

1
import { EcommerceProvider } from '@payloadcms/plugin-ecommerce/react'
2
// Import any payment adapters you want to use on the client side
3
import { stripeAdapterClient } from '@payloadcms/plugin-ecommerce/payments/stripe'
4
import { USD, EUR } from '@payloadcms/plugin-ecommerce/currencies'
5
6
export const Providers = () => (
7
<EcommerceProvider
8
enableVariants={true}
9
currenciesConfig={{
10
supportedCurrencies: [USD, EUR],
11
defaultCurrency: 'USD',
12
}}
13
>
14
{children}
15
</EcommerceProvider>
16
)

api

The api prop is used to configure the API settings for the internal fetches of the provider. It takes an object with the following properties:

Property

Type

Description

apiRoute

string

The base route for accessing the Payload API. Defaults to /api.

serverURL

string

The full URL of your Payload server.

cartsFetchQuery

object

Additional query parameters to include when fetching the cart.

cartsFetchQuery

The cartsFetchQuery property allows you to specify additional query parameters to include when fetching the cart. This can be useful for including related data or customizing the response. This accepts:

Property

Type

Description

depth

string

Defaults to 0. See Depth

select

SelectType

Select parameters. See Select

populate

PopulateType

Populate parameters. See Populate

Example usage:

1
<EcommerceProvider
2
api={{
3
cartsFetchQuery: {
4
depth: 2, // Include related data up to 2 levels deep
5
},
6
}}
7
>
8
{children}
9
</EcommerceProvider>

syncLocalStorage

The syncLocalStorage prop is used to enable or disable syncing the cart ID to local storage. This allows the cart to persist across page reloads and sessions. It defaults to true.

You can also provide an object with the following properties for more configuration:

Property

Type

Description

key

string

The key to use for storing the cart ID in local storage. Defaults to cart.

useCart

The useCart hook is used to manage the cart state and actions. It provides methods to add, remove, and update items in the cart, as well as to fetch the current cart state. It has the following properties:

Property

Type

Description

addItem

(item: CartItemInput, quantity?: number) => void

Method to add an item to the cart, optionally accepts a quantity to add multiple at once.

cart

Cart null

The current cart state. Null or undefined if it doesn't exist.

clearCart

() => void

Method to clear the cart.

decrementItem

(item: IDType) => void

Method to decrement the quantity of an item. Will remove it entirely if it reaches 0.

incrementItem

(item: IDType) => void

Method to increment the quantity of an item.

removeItem

(item: IDType) => void

Method to remove an item from the cart.

Example usage:

1
import { useCart } from '@payloadcms/plugin-ecommerce/react'
2
3
const CartComponent = () => {
4
const { addItem, cart, clearCart, decrementItem, incrementItem, removeItem } =
5
useCart()
6
7
// Your component logic here
8
}

useAddresses

The useAddresses hook is used to fetch and manage addresses. It provides methods to create, update, and delete addresses, as well as to fetch the list of addresses. It has the following properties:

Property

Type

Description

addresses

Address[]

The list of addresses, if any are available for the current user.

createAddress

(data: Address) => Promise<Address>

Method to create a new address.

updateAddress

(addressID: IDType, data: Partial<Address>) => Promise<Address>

Method to update an existing address by ID.

Example usage:

1
import { useAddresses } from '@payloadcms/plugin-ecommerce/react'
2
3
const AddressesComponent = () => {
4
const { addresses, createAddress, updateAddress } = useAddresses()
5
6
// Your component logic here
7
}

usePayments

The usePayments hook is used to manage the checkout process. It provides methods to initiate payments, confirm orders, and handle payment status. It has the following properties:

Property

Type

Description

confirmOrder

(args) => Promise<Order>

Method to confirm an order by ID. More

initiatePayment

(args) => Promise<void>

Method to initiate a payment for an order. More

paymentMethods

PaymentMethod[]

The list of available payment methods.

selectedPaymentMethod

PaymentMethod

The currently selected payment method, if any.

Example usage:

1
import { usePayments } from '@payloadcms/plugin-ecommerce/react'
2
3
const CheckoutComponent = () => {
4
const {
5
confirmOrder,
6
initiatePayment,
7
paymentMethods,
8
selectedPaymentMethod,
9
} = usePayments()
10
11
// Your component logic here
12
}

confirmOrder

Use this method to confirm an order by its ID. It requires the payment method ID and will return the order ID.

1
try {
2
const data = await confirmOrder('stripe', {
3
additionalData: {
4
paymentIntentID: paymentIntent.id,
5
customerEmail,
6
},
7
})
8
// Return type will contain `orderID`
9
// use data to redirect to your order page
10
} catch (error) {
11
// handle error
12
}

If the payment gateway requires additional confirmations offsite then you will need another landing page to handle that. For example with Stripe you may need to use a callback URL, just make sure the relevant information is routed back.

initiatePayment

Use this method to initiate a payment for an order. It requires the cart ID and the payment method ID. Depending on the payment method, additional data may be required. Depending on the payment method used you may need to provide additional data, for example with Stripe:

1
try {
2
const data = await initiatePayment('stripe', {
3
additionalData: {
4
customerEmail,
5
billingAddress,
6
shippingAddress,
7
},
8
})
9
} catch (error) {
10
// handle error
11
}

This function will hit the Payload API endpoint for /stripe/initiate and return the payment data required to complete the payment on the client side, which by default will include a client_secret to complete the payment with Stripe.js. The next step is to call the confirmOrder once payment is confirmed on the client side by Stripe.

useCurrency

The useCurrency hook is used to format prices based on the selected currency. It provides methods to format prices and to get the current currency. It has the following properties:

Property

Type

Description

currenciesConfig

CurrenciesConfig

The configuration for supported currencies. Directly matching the config provided to the Context Provider. More

currency

Currency

The currently selected currency.

formatPrice

(amount: number) => string

Method to format a price based on the selected currency.

setCurrency

(currencyCode: string) => void

Method to set the current currency by code. It will update all price formats when used in conjunction with the formatPrice utility.

formatPrice in particular is very helpful as all prices are stored as integers to avoid any potential issues with decimal calculations, therefore on the frontend you can use this utility to format your price accounting for the currency and decimals. Example usage:

1
import { useCurrency } from '@payloadcms/plugin-ecommerce/react'
2
3
const PriceComponent = ({ amount }) => {
4
const { currenciesConfig, currency, setCurrency } = useCurrency()
5
6
return <div>{formatPrice(amount)}</div>
7
}

useEcommerce

The useEcommerce hook encompasses all of the above hooks in one. It provides access to the cart, addresses, and payments hooks.

Example usage:

1
import { useEcommerce } from '@payloadcms/plugin-ecommerce/react'
2
3
const EcommerceComponent = () => {
4
const { cart, addresses, selectedPaymentMethod } = useEcommerce()
5
6
// Your component logic here
7
}
Next

Payment Adapters