The Swell JS library is a wrapper around the Storefront API, which provides restricted access to store data for client-side applications.
Important: This library implements a subset of the operations available using the Swell API and uses a public key, making it safe to use anywhere. As secret keys provide full access to your store's data, you should only use them server-side via environment variables to prevent them from being exposed in your source code.
To better understand how this library works, read the Swell API docs.
Use cases
- List product and category data
- Create, recover, and update shopping carts
- Create a checkout flow to convert a shopping cart to an order
- Create a subscription signup and billing flow
- Authenticate customers and allow them to edit account information, orders and subscriptions
With npm
npm install swell-js --save
With Yarn
yarn add swell-js
The client is authenticated using your Store ID and public key. You can find these details in your dashboard under Settings > API.
Basic
await swell.init('<store-id>', '<public_key>');
Note: swell.auth()
was renamed to swell.init()
in v1.3.0.
With options
If your application uses camelCase, you can set an flag to transform the API's snake_case responses. This works on request data you provide as well.
const options = {
useCamelCase: // true | false (default is false)
};
swell.init('<store-id>', '<public_key>', options)
The examples here use ES6 async/await syntax. For ES5, all methods return a promise.
import swell from 'swell-js';
swell.init('my-store', 'pk_...');
await swell.get('/products', {
category: 't-shirts',
limit: 25,
page: 1,
});
Return a list of products, up to limit
results. Max 100 per page.
await swell.get('/products', {
limit: 25,
page: 1,
});
Return a list of products with variants expanded, up to limit
results. Max 100 per page.
await swell.get('/products', {
limit: 25,
page: 1,
expand: ['variants'],
});
Return a list of products category slug, up to limit
results. Max 100 per page.
await swell.get('/products', {
category: 't-shirts',
limit: 25,
page: 1,
});
Return a list of products by search, up to limit
results. Max 100 per page. Search is performed using "and" syntax, where all words must be present in one or more fields of the product.
await swell.get('/products', {
search: 'blue jeans',
limit: 25,
page: 1,
});
Return a single product by slug.
await swell.get('/products/{slug}', {
slug: 'pink-shoes',
});
Return a single product by ID.
await swell.get('/products/{id}', {
id: '5c15505200c7d14d851e510f',
});
Return a list of product categories, up to limit
results. Max 100 per page.
await swell.get('/categories', { limit: 25, page: 1 });
Retrieve the current cart, if one has been created with at least one item. Returns a cart object or null
if no items have been added to the cart.
await swell.cart.get();
Add a single item to the cart. Returns the updated cart object.
await swell.cart.addItem({
product_id: '5c15505200c7d14d851e510f',
quantity: 1,
options: [
{
id: 'color',
value: 'Blue',
},
],
});
Update a single cart item by ID. Returns the updated cart object.
await swell.cart.updateItem('5c15505200c7d14d851e510f', {
quantity: 2,
});
Update all items in the cart by replacing existing items. Returns the updated cart object.
await swell.cart.setItems([
{
id: '5c15505200c7d14d851e510f',
quantity: 2,
options: [
{
id: 'color',
value: 'Blue',
},
],
},
{
id: '5c15505200c7d14d851e510g',
quantity: 3,
options: [
{
id: 'color',
value: 'Red',
},
],
},
{
id: '5c15505200c7d14d851e510h',
quantity: 4,
options: [
{
id: 'color',
value: 'White',
},
],
},
]);
Removes a single item from the cart. Returns the updated cart object.
await swell.cart.removeItem('5c15505200c7d14d851e510f');
Removes all items from the cart. Returns the updated cart object.
await swell.cart.setItems([]);
Normally used with an abandoned cart recovery email. Your email may have a link to your store with a checkout_id
identifying the cart that was abandoned. Making this request will add the cart to the current session and mark it as recovered
. Returns the recovered cart object.
await swell.cart.recover('878663b2fb4175b128e40de428cd7b0c');
Update the cart with customer account information. Returns the updated cart object.
An account is assigned to a cart by its email address. If the account has no password saved, then it's considered a guest checkout and the cart will have the property guest=true
. On the other hand, if the account has a password saved, the cart will have the property account_logged_in=false
which you can use to prompt the user to log in to continue. Once the account is logged in, then account_logged_in
will be updated to true
.
await swell.cart.update({
account: {
email: '[email protected]',
email_optin: true, // optional, indicates the customer wants to receive marketing emails
password: 'example', // optional, will save the customer's password if one doesn't exist yet
},
});
Update the cart with customer shipping information. Returns the updated cart object.
await swell.cart.update({
shipping: {
name: 'Ship to name',
address1: '...',
address2: '...',
city: '...',
state: '...',
zip: '...',
country: '...',
phone: '...',
},
});
Update the cart with customer billing information. This method can update both shipping and billing at once if desired. Returns the updated cart object.
await swell.cart.update({
billing: {
name: 'Bill to name',
address1: '...',
address2: '...',
city: '...',
state: '...',
zip: '...',
country: '...',
phone: '...',
// Using credit card
card: {
// Token from swell.card.createToken() or Stripe.js
token: 'tok_...',
},
// Using PayPal
paypal: {
payer_id: '...',
payment_id: '...',
},
// Using Amazon
amazon: {
access_token: '...',
order_reference_id: '...',
},
},
});
Apply either a coupon or gift card code, allowing you to have a single input for a code value. Coupon and gift card codes are not case sensitive. If successful, returns the updated cart object. Otherwise, returns a validation error.
await swell.cart.applyCouponCode('FREESHIPPING');
Remove a coupon code if one was applied.
await swell.cart.removeCouponCode();
Use this method to apply a gift card code only. You can apply any number of gift cards to a cart at once. Gift card codes are not case sensitive. If successful, returns the updated cart object. Otherwise, returns a validation error.
await swell.cart.applyGiftcard('BUYS SFX4 BMZH YY7N');
Remove a gift card using the ID that was assigned to cart.giftcards.id
.
await swell.cart.removeGiftcard('5c15505200c7d14d851e51af');
A shipment rating is contains all the available shipping services given the cart contents and shipping info. The cart must have at least shipping.country
set before it will return a rating. Returns an object with shipping services and rates.
await swell.cart.getShippingRates();
When a customer is finished checking out, call this method to convert a cart to an order. Returns the newly created order.
await swell.cart.submitOrder();
You can retrieve order details after a cart is submitted. By default, this method will return the last order created by the current session. You can also retrieve an order using checkout_id
, allowing you to display order details from an email containing an appropriate link, for example https://example.com/order/{checkout_id}
.
// Get the last order placed by the current session
await swell.cart.getOrder();
// Get an order by checkout_id
await swell.cart.getOrder('878663b2fb4175b128e40de428cd7b0c');
Returns an object with settings that can affect checkout behavior.
name
- Name of the storecurrency
- Store base currencysupport_email
- Email address for customer supportfields
- Set of checkout fields to render as optional or requiredscripts
- Custom scripts including script tagsaccounts
- Indicates whether account login isoptional
,disabled
orrequired
email_optin
- Indicates whether email newsletter opt-in should be presented as optionalterms_policy
- Store terms and conditionsrefund_policy
- Store refund policyprivacy_policy
- Store privacy policytheme
- Checkout theme settingscountries
- List of country codes that have shipping zones configuredpayment_methods
- List of active payment methodscoupons
- Indicates whether the store has couponsgiftcards
- Indicates whether the store has gift cards
await swell.cart.getSettings();
If the email/password is correct, the account will be added to the session and make other related endpoints available to the client.
await swell.account.login('[email protected]', 'password');
This will remove the account from the current session and shopping cart.
await swell.account.logout();
Returns the logged in account object, or null
if the customer is not logged in.
await swell.account.get();
Create a new customer account and log into the current session. Returns the newly created account object.
await swell.account.create({
email: '[email protected]',
first_name: 'John', // optional
last_name: 'Doe', // optional
email_optin: true, // optional
password: 'example', // optional
});
Update the current logged in account, if possible. If successful, returns the updated account object. Otherwise, returns a validation error.
await swell.account.update({
email: '[email protected]',
first_name: 'Jane', // optional
last_name: 'Doe', // optional
email_optin: false, // optional
password: 'example', // optional
});
Send a email to an existing customer account with a link to reset their password. If the email is not found, then no email will be sent. The call returns a value indicating success in either case.
await swell.account.recover({
email: '[email protected]',
});
This requires a reset_key
that is automatically generated when a recovery email is sent (see above). Your password recovery email should link to your web site with reset_key
as a parameter for use in this call.
await swell.account.recover({
reset_key: '...',
password: 'new password',
});
Return a list of addresses on file for an account. These are stored automatically when a non-guest user checks out and chooses to save their information for later.
await swell.account.getAddresses();
Create a new address entry for an account. Returns the newly created address object.
await swell.account.createAddress({
name: 'Ship to name',
address1: '...',
address2: '...',
city: '...',
state: '...',
zip: '...',
country: '...',
phone: '...',
});
Remove an existing address entry from an account. Returns the deleted address object.
await swell.account.deleteAddress('5c15505200c7d14d851e510f');
Return a list of saved credit cards an account. These are stored automatically when a non-guest user checks out and chooses to save their information for later.
await swell.account.getCards();
Credit card tokens can be created using swell.card.createToken
or Stripe.js.
await swell.account.createCard({
token: 't_...',
});
Remove an existing saved credit card from an account.
await swell.account.deleteCard('5c15505200c7d14d851e510f');
Return a list of orders placed by a customer.
await swell.account.getOrders({ limit: 10, page: 2 });
Fetch and manage subscriptions associated with the logged in customer's account.
Return a list of active and canceled subscriptions for an account.
await swell.subscriptions.get();
Return a single subscription by ID.
await swell.subscriptions.get(id);
Subscribe the customer to a new product for recurring billing.
await swell.subscriptions.create({
product_id: '5c15505200c7d14d851e510f',
// the following parameters are optional
variant_id: '5c15505200c7d14d851e510g',
quantity: 1,
coupon_code: '10PERCENTOFF',
items: [
{
product_id: '5c15505200c7d14d851e510h',
quantity: 1,
},
],
});
await swell.subscriptions.update('5c15505200c7d14d851e510f', {
// the following parameters are optional
quantity: 2,
coupon_code: '10PERCENTOFF',
items: [
{
product_id: '5c15505200c7d14d851e510h',
quantity: 1,
},
],
});
await swell.subscriptions.update('5c15505200c7d14d851e510f', {
product_id: '5c15505200c7d14d851e510g',
variant_id: '5c15505200c7d14d851e510h', // optional
quantity: 2,
});
await swell.subscriptions.update('5c15505200c7d14d851e510f', {
canceled: true,
});
await swell.subscriptions.addItem('5c15505200c7d14d851e510f', {
product_id: '5c15505200c7d14d851e510f',
quantity: 1,
options: [
{
id: 'color',
value: 'Blue',
},
],
});
await swell.subscriptions.updateItem('5c15505200c7d14d851e510f', '<item_id>', {
quantity: 2,
});
await swell.subscriptions.setItems('5c15505200c7d14d851e510e', [
{
id: '5c15505200c7d14d851e510f',
quantity: 2,
options: [
{
id: 'color',
value: 'Blue',
},
],
},
{
id: '5c15505200c7d14d851e510g',
quantity: 3,
options: [
{
id: 'color',
value: 'Red',
},
],
},
{
id: '5c15505200c7d14d851e510h',
quantity: 4,
options: [
{
id: 'color',
value: 'White',
},
],
},
]);
await swell.subscriptions.removeItem('5c15505200c7d14d851e510f', '<item_id>');
await swell.subscriptions.setItems([]);
In order to avoid PCI requirements.
Returns an object representing the card token. Pass the token ID to a cart's billing.card.token
field to designate this card as the payment method.
await swell.card.createToken({
number: '4242 4242 4242 4242',
exp_month: 1,
exp_year: 2099,
cvc: 321,
});
Returns true
if the card number is valid, otherwise false
.
swell.card.validateNumber('4242 4242 4242 4242'); // => true
swell.card.validateNumber('1111'); // => false
Returns true
if the card expiration date is valid, otherwise false
.
swell.card.validateExpry('1/29'); // => true
swell.card.validateExpry('1/2099'); // => true
swell.card.validateExpry('9/99'); // => false
Returns true
if the card CVC code is valid, otherwise false
.
swell.card.validateCVC('321'); // => true
swell.card.validateCVC('1'); // => false