React Storefront |

Calling eCommerce Platform APIs

In order to provide a secure, scalable environment to host your app, the Moovweb XDN limits your access to the network. In order to make http requests from route handlers, you must use the fetch module provided by Moovweb XDN.

Route Handlers

We recommend that all calls to upstream eCommerce APIs be made from route handlers running on the server. This keeps your bundle size small and your API keys secure. To call an API, use the fetch module provided by react-storefront, which implements the standard fetch API found in browsers. Here's an example:

// src/product/product-handler.js

import fetch from 'fetch'
import { withGlobalState } from 'react-storefront/router'
import globalState from '../globalState'

export default async function productHandler({ id }) {
  const { hostname, port, apiKey } = Config.get('upstreamApi')

  const productInfo = await fetch(`https://${hostname}:${port}/getProductInfo`, {
    headers: {
      'Authorization': `ApiKey ${apiKey}`
    }
  })
  .then(res => res.json())

  return withGlobalState(request, globalState, {
    product: productInfo // Note: you'll most likely need to alter this object before returning so that it matches the ProductModel class.
  })
}

In Browser

When accessing the fetch module in the browser, React Storefront uses the unfetch polyfill.

Following Redirects

The fetch function provides a redirect option whose value can be:

  • manual - Redirects are not followed, an object like { redirect: url } is returned when the server returns a redirect status (301 or 302)
  • follow - Redirects are followed up to options.maxRedirects, which defaults to 20.
  • error - An error is thrown if the server returns a redirect status.

You can configure fetch to follow redirects by setting the redirect option to follow. For example:

  const productData = await fetch(`https://${hostname}/getProductInfo`, {
    redirect: 'follow'
  }).then(res => res.json())