### Install Axios Fetcher for Node.js Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/packages/sdk-fetcher-axios/README.md Install the Axios fetcher and Axios using NPM for Node.js projects. ```bash npm install @spree/axios-fetcher axios ``` -------------------------------- ### Install Spree Storefront SDK with Axios Fetcher Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Install the storefront SDK and Axios fetcher for Node.js or browser environments. ```bash npm install @spree/storefront-api-v2-sdk @spree/axios-fetcher axios ``` -------------------------------- ### Install Node Fetcher for Node.js Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/packages/sdk-fetcher-node/README.md Install the necessary packages for using Spree SDK with fetch in Node.js. ```bash npm install @spree/node-fetcher node-fetch ``` -------------------------------- ### Install Spree Storefront SDK with Native Fetch Fetcher Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Install the storefront SDK and native fetch fetcher for Node.js 18+ or browser environments. ```bash npm install @spree/storefront-api-v2-sdk @spree/node-fetcher node-fetch ``` -------------------------------- ### Install Spree Platform SDK with Axios Fetcher Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Install the platform SDK and Axios fetcher for Node.js or browser environments. ```bash npm install @spree/platform-api-v2-sdk @spree/axios-fetcher axios ``` -------------------------------- ### Install Node Fetcher for Storefront SDK Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/quick-start.md Install the Node Fetch HTTP client and its corresponding fetcher for use with the Spree Storefront SDK in a Node.js environment. This enables network requests to the Spree API. ```bash npm install --save @spree/node-fetcher node-fetch ``` -------------------------------- ### Install Spree Storefront API v2 SDK Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/quick-start.md Install the NPM package for the Spree Storefront API v2 SDK. This is the first step to integrate Spree's storefront functionalities into your JavaScript application. ```bash npm install --save @spree/storefront-api-v2-sdk ``` -------------------------------- ### Install Spree Platform API v2 SDK Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/quick-start.md Install the NPM package for the Spree Platform API v2 SDK. This package provides access to Spree's administrative and platform-level functionalities. ```bash npm install --save @spree/platform-api-v2-sdk ``` -------------------------------- ### Create Cart and Get Order Token Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/tokens.md Use this to create a new guest cart and retrieve its associated order token. The order token identifies a guest user's cart and order. ```typescript const response = await client.cart.create() const orderToken: string = response.success().data.attributes.token ``` -------------------------------- ### Storefront: Authentication - Get Token Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Obtains an OAuth Bearer access token using email and password credentials. ```APIDOC ## Get Token ### Description Obtains an OAuth Bearer access token using email and password credentials. ### Method `client.authentication.getToken` ### Parameters #### Request Body - **username** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```json { "username": "spree@example.com", "password": "spree123" } ``` ### Response #### Success Response (200) - **access_token** (string) - The obtained access token. - **refresh_token** (string) - The refresh token. - **expires_in** (number) - The token's expiration time in seconds. #### Response Example ```json { "access_token": "...", "token_type": "Bearer", "expires_in": 86400, "refresh_token": "...", "created_at": 1234567890 } ``` ``` -------------------------------- ### Get Payment Methods Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/checkout-flow.md Retrieves available payment methods for the order. ```APIDOC ## GET /checkout/payment_methods ### Description Fetches the available payment methods for the current order. ### Method GET ### Endpoint /checkout/payment_methods ### Parameters #### Query Parameters - **order_token** (string) - Required - The token of the order. ``` -------------------------------- ### Include Spree Platform SDK via CDN Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/alternative-setups.md Include the Spree Platform SDK and its dependencies using script tags for direct use in HTML. This setup is for backend or administrative applications. Verify that the correct SDK and fetcher are referenced. ```html ``` -------------------------------- ### Checkout Process with Spree JS SDK Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Guides through the checkout flow, including updating order details with email and addresses, advancing through checkout steps, selecting shipping, adding payment methods (credit card or saved card), applying store credit, and completing the order. ```typescript const token = { order_token: 'ORDER_TOKEN' } ``` ```typescript // Update order with email and addresses const updated = await client.checkout.orderUpdate({ ...token, order: { email: 'john@snow.org', bill_address_attributes: { firstname: 'John', lastname: 'Snow', address1: '7735 Old Georgetown Road', city: 'Bethesda', phone: '3014445002', zipcode: '20814', state_name: 'MD', country_iso: 'US' }, ship_address_attributes: { firstname: 'John', lastname: 'Snow', address1: '7735 Old Georgetown Road', city: 'Bethesda', phone: '3014445002', zipcode: '20814', state_name: 'MD', country_iso: 'US' } } }) ``` ```typescript // Advance to next checkout step await client.checkout.orderNext({ order_token: 'ORDER_TOKEN' }) ``` ```typescript // Or auto-advance to the furthest valid step await client.checkout.advance({ order_token: 'ORDER_TOKEN' }) ``` ```typescript // List available shipping rates const shippingRates = await client.checkout.shippingRates({ order_token: 'ORDER_TOKEN', include: 'shipping_rates,stock_location' }) ``` ```typescript // Select a shipping method for a shipment await client.checkout.selectShippingMethod({ order_token: 'ORDER_TOKEN', shipping_method_id: '42', shipment_id: '1' }) ``` ```typescript // List available payment methods const paymentMethods = await client.checkout.paymentMethods({ order_token: 'ORDER_TOKEN' }) ``` ```typescript // Add a new credit card payment await client.checkout.addPayment({ order_token: 'ORDER_TOKEN', payment_method_id: '1', source_attributes: { gateway_payment_profile_id: 'card_1JqvNB2eZvKYlo2C5OlqLV7S', cc_type: 'visa', last_digits: '4242', month: '12', year: '2028', name: 'John Snow' } }) ``` ```typescript // Use an existing saved credit card await client.checkout.addPayment({ bearer_token: 'TOKEN', payment_method_id: '1', source_id: '3' }) ``` ```typescript // Apply store credit to checkout await client.checkout.addStoreCredits({ order_token: 'ORDER_TOKEN', amount: 50 }) ``` ```typescript // Remove store credit await client.checkout.removeStoreCredits({ order_token: 'ORDER_TOKEN' }) ``` ```typescript // Complete the order const completed = await client.checkout.complete({ order_token: 'ORDER_TOKEN' }) if (completed.isSuccess()) { console.log('Order placed:', completed.success().data.attributes.number) } ``` -------------------------------- ### Get Shipping Rates Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/checkout-flow.md Retrieves available shipping methods for the order. ```APIDOC ## GET /checkout/shipping_rates ### Description Fetches the available shipping rates for the current order. ### Method GET ### Endpoint /checkout/shipping_rates ### Parameters #### Query Parameters - **order_token** (string) - Required - The token of the order. ``` -------------------------------- ### Storefront Authentication: Get Access Token Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Obtain an OAuth Bearer access token using email and password credentials. The result object indicates success or failure. ```typescript // Get an access token using email/password const tokenResult = await client.authentication.getToken({ username: 'spree@example.com', password: 'spree123' }) if (tokenResult.isSuccess()) { const { access_token, refresh_token, expires_in } = tokenResult.success() console.log('Access token:', access_token) // { access_token: '...', token_type: 'Bearer', expires_in: 86400, refresh_token: '...', created_at: 1234567890 } } ``` -------------------------------- ### Get Bearer Token for Logged-in User Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/tokens.md Obtain a bearer token for a logged-in user by providing their username and password. This token identifies an authenticated user. ```typescript const response = await client.authentication.getToken({ username: 'spree@example.com', password: 'spree123' }) const bearerToken: string = response.success().access_token ``` -------------------------------- ### Get Order Status with Spree JS SDK Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Retrieves the status of a placed order using its order number and order token. Logs the order's state, payment state, and shipment state if successful. ```typescript const orderStatus = await client.order.status({ order_token: '7381273269536713689562374856', order_number: 'R653163382' }) if (orderStatus.isSuccess()) { const { state, payment_state, shipment_state } = orderStatus.success().data.attributes console.log(`Order state: ${state}, Payment: ${payment_state}, Shipment: ${shipment_state}`) } ``` -------------------------------- ### Obtain Platform API Bearer Tokens Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Get OAuth Bearer tokens for Platform API calls using either application credentials (client_credentials grant) for server-to-server or user credentials (password grant) for admin sessions. Refreshing user tokens is also supported. ```typescript import createAxiosFetcher from '@spree/axios-fetcher/dist/server/index' import { makeClient } from '@spree/platform-api-v2-sdk' const client = makeClient({ host: 'http://localhost:3000', createFetcher: createAxiosFetcher }) ``` ```typescript // Application token (client_credentials grant) — for server-to-server const appToken = await client.authentication.getApplicationToken({ client_id: '7ZY15L7crVZul8i3PZPrnpOkEURK7xnXEWRZdE6K39M', client_secret: 'cxMZ0tbe604qj_13hibNmc3GDsXUQfpzHt9PvweihFc' }) ``` ```typescript const bearerToken = appToken.success().access_token ``` ```typescript // User token (password grant) — for admin user sessions const userToken = await client.authentication.getUserToken({ client_id: '7ZY15L7crVZul8i3PZPrnpOkEURK7xnXEWRZdE6K39M', client_secret: 'cxMZ0tbe604qj_13hibNmc3GDsXUQfpzHt9PvweihFc', username: 'admin@example.com', password: 'admin123' }) ``` ```typescript // Refresh user token const refreshed = await client.authentication.refreshUserToken({ refresh_token: 'aebe2886d7dbba6f769e20043e40cfa3447e23ad9d8e82c632f60ed63a2f0df1' }) ``` -------------------------------- ### Create Storefront Client with Axios Fetcher (Browser) Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Instantiate the storefront SDK client using an Axios fetcher for browser environments via UMD. ```javascript const client = SpreeSDK.makeClient({ host: 'http://localhost:3000', createFetcher: SpreeSDK.createAxiosFetcher.default }) ``` -------------------------------- ### Create Storefront Client with Native Fetch Fetcher (Node.js) Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Instantiate the storefront SDK client using a native fetch fetcher for Node.js environments. ```typescript import createFetchFetcher from '@spree/node-fetcher/dist/server/index' import { makeClient } from '@spree/storefront-api-v2-sdk' const client = makeClient({ host: 'http://localhost:3000', createFetcher: createFetchFetcher }) ``` -------------------------------- ### Create Storefront Client with Axios Fetcher (Node.js) Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Instantiate the storefront SDK client using an Axios fetcher for Node.js environments. ```typescript import createAxiosFetcher from '@spree/axios-fetcher/dist/server/index' import { makeClient } from '@spree/storefront-api-v2-sdk' const client = makeClient({ host: 'http://localhost:3000', createFetcher: createAxiosFetcher }) ``` -------------------------------- ### Fetch Product Safely with Error Handling Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Demonstrates how to safely fetch a product using the SDK and handle potential errors. Imports are required for the fetcher and client. ```typescript import createAxiosFetcher from '@spree/axios-fetcher/dist/server/index' import { makeClient } from '@spree/storefront-api-v2-sdk' const client = makeClient({ host: 'http://localhost:3000', createFetcher: createAxiosFetcher }) async function fetchProductSafely(productId: string) { const result = await client.products.show({ id: productId, include: 'variants,images' }) if (result.isSuccess()) { const product = result.success() console.log('Product name:', product.data.attributes.name) console.log('Variants:', product.included?.filter(r => r.type === 'variant').length) return product } if (result.isFail()) { const error = result.fail() console.error('Error fetching product:', error.message) // error object contains server error details } return null } ``` -------------------------------- ### Create Platform Client with Axios Fetcher Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Instantiate the platform SDK client using an Axios fetcher. ```typescript import createAxiosFetcher from '@spree/axios-fetcher/dist/server/index' import { makeClient } from '@spree/platform-api-v2-sdk' const client = makeClient({ host: 'http://localhost:3000', createFetcher: createAxiosFetcher }) ``` -------------------------------- ### Initialize Storefront SDK Client Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/quick-start.md Create an instance of the Spree Storefront API client. Configure it with your Spree host and the fetcher implementation. This client is used to interact with the Spree API. ```javascript const createFetchFetcher = require('@spree/node-fetcher/dist/server/index').default const { makeClient } = require('@spree/storefront-api-v2-sdk') const client = makeClient({ host: 'http://localhost:3000', createFetcher: createFetchFetcher }) client.products.list({ include: 'default_variant', page: 1 }) .then((spreeResponse) => { console.log(spreeResponse.success()) }) ``` -------------------------------- ### Create Cart Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/checkout-flow.md Initiates a new shopping cart and returns cart details, including a token. ```APIDOC ## POST /cart ### Description Creates a new shopping cart. ### Method POST ### Endpoint /cart ### Response #### Success Response (201) - **token** (string) - The unique token for the created cart. - **data** (object) - Cart details. - **attributes** (object) - Cart attributes. - **token** (string) - The unique token for the created cart. ``` -------------------------------- ### Configure Spree SDK Client with Fetcher in Node.js Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/packages/sdk-fetcher-node/README.md Set up the Spree SDK client to use the Node.js fetcher. Ensure the host and createFetcher are correctly configured. ```javascript const createFetchFetcher = require('@spree/node-fetcher/dist/server/index').default const { makeClient } = require('@spree/storefront-api-v2-sdk') const client = makeClient({ host: 'http://localhost:3000', createFetcher: createFetchFetcher }) ``` -------------------------------- ### Create and Manage Carts with Spree JS SDK Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Demonstrates creating carts for guests and logged-in users, viewing contents, adding/updating/removing items, applying/removing coupons, estimating shipping, changing currency, associating guest carts, emptying, and deleting carts. ```typescript // Create a new cart (guest) const cart = await client.cart.create() const orderToken = cart.success().data.attributes.token ``` ```typescript // Create a cart (logged-in user) const authCart = await client.cart.create({ bearer_token: 'TOKEN' }) ``` ```typescript // View cart contents const cartContents = await client.cart.show({ order_token: orderToken }) ``` ```typescript // Add an item to cart const addedItem = await client.cart.addItem({ order_token: orderToken, variant_id: '1', quantity: 2 }) ``` ```typescript // Update item quantity const updated = await client.cart.setQuantity({ order_token: orderToken, line_item_id: '9', quantity: 5 }) ``` ```typescript // Remove an item const removed = await client.cart.removeItem({ order_token: orderToken, id: '1' }) ``` ```typescript // Apply a coupon code const withCoupon = await client.cart.applyCouponCode({ order_token: orderToken, coupon_code: 'SAVE10' }) ``` ```typescript // Remove a specific coupon await client.cart.removeCouponCode({ order_token: orderToken, code: 'SAVE10' }) ``` ```typescript // Remove all coupons await client.cart.removeAllCoupons({ order_token: orderToken }) ``` ```typescript // Estimate shipping rates before checkout const rates = await client.cart.estimateShippingRates({ order_token: orderToken, country_iso: 'US' }) ``` ```typescript // Change cart currency await client.cart.changeCurrency({ order_token: orderToken, new_currency: 'EUR' }) ``` ```typescript // Associate a guest cart with a logged-in user after login await client.cart.associateGuestCart({ bearer_token: 'TOKEN', guest_order_token: orderToken }) ``` ```typescript // Empty the cart await client.cart.emptyCart({ order_token: orderToken }) ``` ```typescript // Delete the cart entirely await client.cart.remove({ order_token: orderToken }) ``` -------------------------------- ### Storefront: Cart Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Create and manage shopping carts for both guest and authenticated users. This includes creating carts, adding/updating/removing items, applying coupons, estimating shipping, changing currency, associating guest carts, emptying, and deleting carts. ```APIDOC ## Storefront: Cart Create and manage shopping carts for both guest and authenticated users. ```ts // Create a new cart (guest) const cart = await client.cart.create() const orderToken = cart.success().data.attributes.token // Create a cart (logged-in user) const authCart = await client.cart.create({ bearer_token: 'TOKEN' }) // View cart contents const cartContents = await client.cart.show({ order_token: orderToken }) // Add an item to cart const addedItem = await client.cart.addItem({ order_token: orderToken, variant_id: '1', quantity: 2 }) // Update item quantity const updated = await client.cart.setQuantity({ order_token: orderToken, line_item_id: '9', quantity: 5 }) // Remove an item const removed = await client.cart.removeItem({ order_token: orderToken, id: '1' }) // Apply a coupon code const withCoupon = await client.cart.applyCouponCode({ order_token: orderToken, coupon_code: 'SAVE10' }) // Remove a specific coupon await client.cart.removeCouponCode({ order_token: orderToken, code: 'SAVE10' }) // Remove all coupons await client.cart.removeAllCoupons({ order_token: orderToken }) // Estimate shipping rates before checkout const rates = await client.cart.estimateShippingRates({ order_token: orderToken, country_iso: 'US' }) // Change cart currency await client.cart.changeCurrency({ order_token: orderToken, new_currency: 'EUR' }) // Associate a guest cart with a logged-in user after login await client.cart.associateGuestCart({ bearer_token: 'TOKEN', guest_order_token: orderToken }) // Empty the cart await client.cart.emptyCart({ order_token: orderToken }) // Delete the cart entirely await client.cart.remove({ order_token: orderToken }) ``` ``` -------------------------------- ### Products Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Browse and retrieve product listings with options for filtering, pagination, and image transformations. ```APIDOC ## Product Operations ### List Products Retrieves a list of products, with support for pagination and filtering. ```ts // List products with pagination await client.products.list({ page: 1, per_page: 10 }) // List products filtered by taxon with variant includes await client.products.list({ filter: { taxons: '1' }, include: 'default_variant,images', page: 1, per_page: 20 }) ``` ### Show Product Retrieves details for a single product, including variants and images, with optional image transformations. ```ts // Show a single product with variants await client.products.show({ id: '123', include: 'variants,images,option_types' }) // Show product with image transformation await client.products.show({ id: '123', image_transformation: { size: '200x200', quality: 80 } }) ``` ``` -------------------------------- ### Configure Spree SDK Client with Native Fetch in Browser Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/packages/sdk-fetcher-node/README.md Set up the Spree SDK client to use the native fetch API available in modern web browsers. Include the necessary SDK scripts. ```html ``` -------------------------------- ### Storefront: Checkout Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Step through the checkout flow, including setting addresses, selecting shipping methods, adding payment information, and completing the order. Supports both guest and logged-in users. ```APIDOC ## Storefront: Checkout Step through the checkout flow — set addresses, select shipping, add payment, and complete the order. ```ts const token = { order_token: 'ORDER_TOKEN' } // Update order with email and addresses const updated = await client.checkout.orderUpdate({ ...token, order: { email: 'john@snow.org', bill_address_attributes: { firstname: 'John', lastname: 'Snow', address1: '7735 Old Georgetown Road', city: 'Bethesda', phone: '3014445002', zipcode: '20814', state_name: 'MD', country_iso: 'US' }, ship_address_attributes: { firstname: 'John', lastname: 'Snow', address1: '7735 Old Georgetown Road', city: 'Bethesda', phone: '3014445002', zipcode: '20814', state_name: 'MD', country_iso: 'US' } } }) // Advance to next checkout step await client.checkout.orderNext({ order_token: 'ORDER_TOKEN' }) // Or auto-advance to the furthest valid step await client.checkout.advance({ order_token: 'ORDER_TOKEN' }) // List available shipping rates const shippingRates = await client.checkout.shippingRates({ order_token: 'ORDER_TOKEN', include: 'shipping_rates,stock_location' }) // Select a shipping method for a shipment await client.checkout.selectShippingMethod({ order_token: 'ORDER_TOKEN', shipping_method_id: '42', shipment_id: '1' }) // List available payment methods const paymentMethods = await client.checkout.paymentMethods({ order_token: 'ORDER_TOKEN' }) // Add a new credit card payment await client.checkout.addPayment({ order_token: 'ORDER_TOKEN', payment_method_id: '1', source_attributes: { gateway_payment_profile_id: 'card_1JqvNB2eZvKYlo2C5OlqLV7S', cc_type: 'visa', last_digits: '4242', month: '12', year: '2028', name: 'John Snow' } }) // Use an existing saved credit card await client.checkout.addPayment({ bearer_token: 'TOKEN', payment_method_id: '1', source_id: '3' }) // Apply store credit to checkout await client.checkout.addStoreCredits({ order_token: 'ORDER_TOKEN', amount: 50 }) // Remove store credit await client.checkout.removeStoreCredits({ order_token: 'ORDER_TOKEN' }) // Complete the order const completed = await client.checkout.complete({ order_token: 'ORDER_TOKEN' }) if (completed.isSuccess()) { console.log('Order placed:', completed.success().data.attributes.number) } ``` ``` -------------------------------- ### Initialize Platform SDK Client Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/quick-start.md Instantiate the Spree Platform API client, specifying the Spree host and the fetcher. This client is used for operations requiring platform-level access, such as managing users. ```javascript const createFetchFetcher = require('@spree/node-fetcher/dist/server/index').default const { makeClient } = require('@spree/platform-api-v2-sdk') const client = makeClient({ host: 'http://localhost:3000', createFetcher: createFetchFetcher }) client.users.list({ bearer_token: '...' }) .then((spreeResponse) => { console.log(spreeResponse.success()) }) ``` -------------------------------- ### Platform: Orders (Admin) Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Full lifecycle management for orders including creation, state transitions, approval, and cancellation. ```APIDOC ## Platform: Orders (Admin) Full lifecycle management for orders including creation, state transitions, approval, and cancellation. ### List all orders ```ts // List all orders const orders = await client.orders.list({ bearer_token: bearerToken }) ``` ### Get a single order ```ts // Get a single order const order = await client.orders.show({ bearer_token: bearerToken, id: '1' }) ``` ### Advance order to furthest valid state ```ts // Advance order to furthest valid state await client.orders.advance({ bearer_token: bearerToken, id: '1' }) ``` ### Move to next state ```ts // Move to next state await client.orders.next({ bearer_token: bearerToken, id: '1' }) ``` ### Mark order as complete ```ts // Mark order as complete await client.orders.complete({ bearer_token: bearerToken, id: '1' }) ``` ### Approve an order ```ts // Approve an order await client.orders.approve({ bearer_token: bearerToken, id: '1' }) ``` ### Cancel an order ```ts // Cancel an order await client.orders.cancel({ bearer_token: bearerToken, id: '1' }) ``` ### Empty an order ```ts // Empty an order (remove all line items, shipments, payments) await client.orders.empty({ bearer_token: bearerToken, id: '1' }) ``` ### Apply store credit to an order ```ts // Apply store credit to an order await client.orders.useStoreCredit({ bearer_token: bearerToken, id: '1', amount: 25 }) ``` ### Apply a coupon code to an order ```ts // Apply a coupon code to an order await client.orders.applyCouponCode({ bearer_token: bearerToken, id: '1', coupon_code: 'ADMIN20' }) ``` ### Delete an order ```ts // Delete an order await client.orders.remove({ bearer_token: bearerToken, id: '1' }) ``` ``` -------------------------------- ### Complete Checkout Flow with Spree API v2 JS SDK Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/checkout-flow.md This snippet demonstrates the complete checkout process, from cart creation to order placement. Ensure you have a valid client instance and necessary data like email and address details. ```typescript const cartCreateResponse = await client.cart.create() const orderToken = cartCreateResponse.success().data.attributes.token await client.cart.addItem({ order_token: orderToken, variant_id: '1' }) // Step one - save email, billing and shipping addresses await client.checkout.orderUpdate({ order_token: orderToken, order: { email, bill_address_attributes: {...}, ship_address_attributes: {...} } }) await client.checkout.orderNext({ order_token: orderToken }) // Step two - pick a shipping method const shipping = (await client.checkout.shippingRates({ order_token: orderToken })).success() await client.checkout.orderUpdate({ order_token: orderToken, order: { shipments_attributes: [{ id: shipping.data[0].id, selected_shipping_rate_id: shipping.data[0].relationships.shipping_rates.data[0].id }] } }) await client.checkout.orderNext({ order_token: orderToken }) // Step three - pick a payment method const payment = (await client.checkout.paymentMethods({ order_token: orderToken })).success() await client.checkout.addPayment({ order_token: orderToken, payment_method_id: payment.data[0].id, source_attributes: { gateway_payment_profile_id: "card_1JqvNB2eZvKYlo2C5OlqLV7S", cc_type: "visa", last_digits: "1111", month: "10", year: "2026", name: "John Snow" } }) await client.checkout.orderNext({ order_token: orderToken }) // Place the order await client.checkout.complete({ order_token: orderToken }) ``` -------------------------------- ### Complete Checkout Flow with Error Handling Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Illustrates a full checkout process with step-by-step error handling. Ensure the order token is valid before initiating. ```typescript // Full checkout flow with error handling async function completeCheckout(orderToken: string) { const steps = [ () => client.checkout.orderUpdate({ order_token: orderToken, order: { email: 'customer@example.com' } }), () => client.checkout.advance({ order_token: orderToken }), () => client.checkout.complete({ order_token: orderToken }) ] for (const step of steps) { const result = await step() if (result.isFail()) { throw new Error(`Checkout step failed: ${result.fail().message}`) } } console.log('Checkout complete!') } ``` -------------------------------- ### Platform: Products (Admin) Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Full CRUD operations for managing products via the Platform API. ```APIDOC ## Platform: Products (Admin) Full CRUD operations for managing products via the Platform API. ### List all products ```ts // List all products const products = await client.products.list({ bearer_token: bearerToken }) ``` ### Show a specific product ```ts // Show a specific product const product = await client.products.show({ bearer_token: bearerToken, id: '1' }) ``` ### Create a new product ```ts // Create a new product const created = await client.products.create({ bearer_token: bearerToken, product: { name: 'Winter Jacket', price: '99.99', sku: 'WJ-001', shipping_category_id: '1', description: 'A warm winter jacket', available_on: '2024-01-01T00:00:00Z', weight: '1.5', taxon_ids: '1,2' } }) ``` ### Update a product ```ts // Update a product const updated = await client.products.update({ bearer_token: bearerToken, id: '1', product: { name: 'Winter Jacket (Updated)', price: '89.99', meta_keywords: 'jacket, winter, clothing' } }) ``` ### Delete a product ```ts // Delete a product await client.products.remove({ bearer_token: bearerToken, id: '1' }) ``` ``` -------------------------------- ### Storefront: Wishlists Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Create and manage product wishlists for authenticated users, including adding/updating/removing wished items. ```APIDOC ## Storefront: Wishlists Create and manage product wishlists for authenticated users, including adding/updating/removing wished items. ### List all user wishlists ```ts // List all user wishlists const wishlists = await client.wishlists.list({ bearer_token: 'TOKEN' }) ``` ### Get the default wishlist ```ts // Get the default wishlist (creates one if none exists) const defaultWishlist = await client.wishlists.default({ bearer_token: 'TOKEN', is_variant_included: '123' }) ``` ### Show a specific wishlist ```ts // Show a specific wishlist const wishlist = await client.wishlists.show({ bearer_token: 'TOKEN', wishlist_token: 'WyZxWS2w3BdDRHcGgtN1LKiY' }) ``` ### Create a new wishlist ```ts // Create a new wishlist const newWishlist = await client.wishlists.create({ bearer_token: 'TOKEN', name: 'Holiday Gifts', is_private: false, is_default: false }) ``` ### Update a wishlist ```ts // Update a wishlist await client.wishlists.update({ bearer_token: 'TOKEN', wishlist_token: 'WyZxWS2w3BdDRHcGgtN1LKiY', name: 'Winter Wishlist', is_private: true }) ``` ### Add an item to a wishlist ```ts // Add an item to a wishlist await client.wishlists.addWishedItem({ bearer_token: 'TOKEN', wishlist_token: 'WyZxWS2w3BdDRHcGgtN1LKiY', variant_id: '5', quantity: 2 }) ``` ### Update quantity of a wished item ```ts // Update quantity of a wished item await client.wishlists.updateWishedItem({ bearer_token: 'TOKEN', wishlist_token: 'WyZxWS2w3BdDRHcGgtN1LKiY', id: '3', quantity: 5 }) ``` ### Remove a wished item ```ts // Remove a wished item await client.wishlists.removeWishedItem({ bearer_token: 'TOKEN', wishlist_token: 'WyZxWS2w3BdDRHcGgtN1LKiY', id: '3' }) ``` ### Delete a wishlist ```ts // Delete a wishlist await client.wishlists.remove({ bearer_token: 'TOKEN', wishlist_token: 'WyZxWS2w3BdDRHcGgtN1LKiY' }) ``` ``` -------------------------------- ### Create Spree SDK Client with Axios Fetcher in Node.js Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/packages/sdk-fetcher-axios/README.md Configure the Spree SDK client to use the Axios fetcher in a Node.js environment. Ensure the fetcher is correctly imported and passed to the `createFetcher` option. ```javascript const createAxiosFetcher = require('@spree/axios-fetcher/dist/server/index').default const { makeClient } = require('@spree/storefront-api-v2-sdk') const client = makeClient({ host: 'http://localhost:3000', createFetcher: createAxiosFetcher }) ``` -------------------------------- ### Manage Platform Products (Admin) Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Perform full CRUD operations on products using the Platform API. Requires a bearer token. ```typescript // List all products const products = await client.products.list({ bearer_token: bearerToken }) ``` ```typescript // Show a specific product const product = await client.products.show({ bearer_token: bearerToken, id: '1' }) ``` ```typescript // Create a new product const created = await client.products.create({ bearer_token: bearerToken, product: { name: 'Winter Jacket', price: '99.99', sku: 'WJ-001', shipping_category_id: '1', description: 'A warm winter jacket', available_on: '2024-01-01T00:00:00Z', weight: '1.5', taxon_ids: '1,2' } }) ``` ```typescript // Update a product const updated = await client.products.update({ bearer_token: bearerToken, id: '1', product: { name: 'Winter Jacket (Updated)', price: '89.99', meta_keywords: 'jacket, winter, clothing' } }) ``` ```typescript // Delete a product await client.products.remove({ bearer_token: bearerToken, id: '1' }) ``` -------------------------------- ### Include Spree Storefront SDK via CDN Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/alternative-setups.md Include the Spree Storefront SDK and its dependencies using script tags for direct use in HTML. This method is suitable for front-end applications where a build process is not used. Ensure Axios and the fetcher are included before the SDK initialization. ```html ``` -------------------------------- ### List Products with Spree API v2 JS SDK Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Retrieve product listings with options for pagination and filtering. Use 'include' to fetch related data like variants and images. ```typescript // List products with pagination const products = await client.products.list({ page: 1, per_page: 10 }) ``` ```typescript // List products filtered by taxon with variant includes const filteredProducts = await client.products.list({ filter: { taxons: '1' }, include: 'default_variant,images', page: 1, per_page: 20 }) ``` -------------------------------- ### Create Spree SDK Client with Custom Fetcher Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/switching-the-fetcher.md Supply a custom fetcher function during client creation for full control over requests and responses. Use `createCustomizedFetchFetcher` for fetch-compatible interfaces. ```javascript makeClient({ createFetcher: ... }) ``` -------------------------------- ### Manage Platform Orders (Admin) Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Handle the full lifecycle of orders, including state transitions, approval, and cancellation, via the Platform API. Requires a bearer token. ```typescript // List all orders const orders = await client.orders.list({ bearer_token: bearerToken }) ``` ```typescript // Get a single order const order = await client.orders.show({ bearer_token: bearerToken, id: '1' }) ``` ```typescript // Advance order to furthest valid state await client.orders.advance({ bearer_token: bearerToken, id: '1' }) ``` ```typescript // Move to next state await client.orders.next({ bearer_token: bearerToken, id: '1' }) ``` ```typescript // Mark order as complete await client.orders.complete({ bearer_token: bearerToken, id: '1' }) ``` ```typescript // Approve an order await client.orders.approve({ bearer_token: bearerToken, id: '1' }) ``` ```typescript // Cancel an order await client.orders.cancel({ bearer_token: bearerToken, id: '1' }) ``` ```typescript // Empty an order (remove all line items, shipments, payments) await client.orders.empty({ bearer_token: bearerToken, id: '1' }) ``` ```typescript // Apply store credit to an order await client.orders.useStoreCredit({ bearer_token: bearerToken, id: '1', amount: 25 }) ``` ```typescript // Apply a coupon code to an order await client.orders.applyCouponCode({ bearer_token: bearerToken, id: '1', coupon_code: 'ADMIN20' }) ``` ```typescript // Delete an order await client.orders.remove({ bearer_token: bearerToken, id: '1' }) ``` -------------------------------- ### Show Product Details with Spree API v2 JS SDK Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Fetch details for a single product, including its variants, images, and option types. Image transformations can also be applied. ```typescript // Show a single product with variants const product = await client.products.show({ id: '123', include: 'variants,images,option_types' }) ``` ```typescript // Show product with image transformation const productWithImage = await client.products.show({ id: '123', image_transformation: { size: '200x200', quality: 80 } }) ``` ```typescript if (product.isSuccess()) { console.log(product.success().data.attributes.name) } ``` -------------------------------- ### Storefront: Countries Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Retrieve the list of available countries and the store's default country. Allows fetching all countries or a specific country by its ISO code. ```APIDOC ## Storefront: Countries Retrieve the list of available countries and the store default country. ```ts // List all countries const countries = await client.countries.list() // Get a specific country by ISO code const usa = await client.countries.show({ iso: 'US' }) // Get the default country for the store const defaultCountry = await client.countries.default() ``` ``` -------------------------------- ### Complete Order Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/checkout-flow.md Finalizes the checkout process and places the order. ```APIDOC ## POST /checkout/complete ### Description Completes the checkout process and places the order. ### Method POST ### Endpoint /checkout/complete ### Parameters #### Request Body - **order_token** (string) - Required - The token of the order to complete. ``` -------------------------------- ### Select Shipping Method Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/checkout-flow.md Updates the order to include the selected shipping method. ```APIDOC ## PUT /checkout ### Description Updates the order to specify the selected shipping method. ### Method PUT ### Endpoint /checkout ### Parameters #### Request Body - **order_token** (string) - Required - The token of the order to update. - **order** (object) - Required - Order details to update. - **shipments_attributes** (array) - An array containing shipment details. - **id** (string) - Required - The ID of the shipment. - **selected_shipping_rate_id** (string) - Required - The ID of the selected shipping rate. ``` -------------------------------- ### Include Axios Fetcher for Browser Usage Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/packages/sdk-fetcher-axios/README.md Include the necessary script tags for the Spree SDK, Axios, and the Axios fetcher in your HTML file for browser-based applications. The SDK will automatically detect and use Axios. ```html ``` -------------------------------- ### List and Show Countries with Spree JS SDK Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Fetches a list of all available countries or details for a specific country using its ISO code. Also retrieves the store's default country. ```typescript // List all countries const countries = await client.countries.list() ``` ```typescript // Get a specific country by ISO code const usa = await client.countries.show({ iso: 'US' }) ``` ```typescript // Get the default country for the store const defaultCountry = await client.countries.default() ``` -------------------------------- ### Manage User Accounts with Spree API v2 JS SDK Source: https://context7.com/spree/spree-api-v2-js-sdk/llms.txt Use these methods to create, confirm, and manage user accounts. Ensure you have a valid bearer token for most operations. ```typescript // Create a new user account const createResult = await client.account.create({ user: { email: 'john@snow.org', password: 'spree123', password_confirmation: 'spree123' } }) ``` ```typescript // Confirm account email const confirmed = await client.account.confirm({ confirmation_token: '2xssfC9Hzf8DJXyRZGmB' }) ``` ```typescript // Forgot password (sends reset email) await client.account.forgotPassword({ user: { email: 'spree@example.com' } }) ``` ```typescript // Reset password using a token await client.account.resetPassword({ reset_password_token: '7381273269536713689562374856', user: { password: '123!@#asdASD', password_confirmation: '123!@#asdASD' } }) ``` ```typescript // Get current account info const info = await client.account.accountInfo({ bearer_token: 'TOKEN' }) ``` ```typescript // Update account const updated = await client.account.update({ bearer_token: 'TOKEN', user: { email: 'john@snow.org', password: 'new_spree123', password_confirmation: 'new_spree123' } }) ``` -------------------------------- ### Advance Checkout Stage Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/checkout-flow.md Moves the checkout process to the next stage. ```APIDOC ## POST /checkout/order_next ### Description Advances the checkout process to the next available step. ### Method POST ### Endpoint /checkout/order_next ### Parameters #### Request Body - **order_token** (string) - Required - The token of the order. ``` -------------------------------- ### Add Item to Cart Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/checkout-flow.md Adds a product variant to the shopping cart using the cart's order token. ```APIDOC ## POST /cart/items ### Description Adds a specified variant to the shopping cart. ### Method POST ### Endpoint /cart/items ### Parameters #### Request Body - **order_token** (string) - Required - The token of the cart to which the item will be added. - **variant_id** (string) - Required - The ID of the product variant to add. ``` -------------------------------- ### Import Spree SDK in TypeScript Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/alternative-setups.md Use this import statement in TypeScript projects when `esModuleInterop` is enabled in `tsconfig.json`. Ensure the correct paths for the fetcher and SDK are used. ```javascript // Set \"esModuleInterop\": true in tsconfig.json import createAxiosFetcher from '@spree/axios-fetcher/dist/server' import { makeClient } from '@spree/storefront-api-v2-sdk' ``` -------------------------------- ### Confirmation Token Source: https://github.com/spree/spree-api-v2-js-sdk/blob/main/pages/tokens.md A Confirmation Token is used for single operations, such as password resets. These tokens are single-use and may expire. ```APIDOC ## Confirmation Token Identifies a user for a single operation. For example, to reset their account's password. Confirmation Tokens are single-use and may have an expiration date. ```