Piyush Dankhra

moon indicating dark mode
sun indicating light mode

Last updated: January 11, 2021

How the PWA Studio communicate with the Magento?

There are two ways PWA Studio communicates with the Magento 2.

  1. GraphQL
  2. RestAPI

To connect with the Magento 2, it uses the MAGENTO_BACKEND_URL parameter of the .env file. It uses this specified Magento instance to fetch data.

#### Connecting to a Magento store #############################################
#
# Connect to an instance of Magento 2.3 by specifying its public domain name.
MAGENTO_BACKEND_URL=https://magento.local/
#
################################################################################

Note: It is the base url, not the Magento admin url.

GraphQL

GraphQL is the main endpoint to manipulate the data. It is using Apollo Client to fetch data via GraphQL. Using the Apollo Client, we can cache the query for faster communication. If we look under the src/index.js file

ReactDOM.render(
<Adapter apiBase={apiBase} apollo={{ link: apolloLink }} store={store}>
<AppContextProvider>
<App />
</AppContextProvider>
</Adapter>,
document.getElementById('root')
);

file source: packages/venia-concept/src/index.js

Inside the component, we can use GraphQL query to fetch and render the data and GraphQL mutation to write data in the Magento.

RestAPI

The second option we have available is the RestAPI. Most of all operations use GraphQL, but if there is no endpoint available of GraphQL for such extension or functionality then we can utilize RestAPI.

For example, it uses the RestAPI peregrine library to POST the shipping and payment information on the submitOrder call.

If we look inside the packages/peregrine/lib/store/actions/checkout/asyncActions.js file.

import { Magento2 } from '../../../RestApi';
const { request } = Magento2;

It uses request to POST the data under the submitOrder function using the RestAPI.

// POST to shipping-information to submit the shipping address and shipping method.
const guestShippingEndpoint = `/rest/V1/guest-carts/${cartId}/shipping-information`;
const authedShippingEndpoint =
'/rest/V1/carts/mine/shipping-information';
const shippingEndpoint = user.isSignedIn
? authedShippingEndpoint
: guestShippingEndpoint;
await request(shippingEndpoint, {
method: 'POST',
body: JSON.stringify({
addressInformation: {
billing_address,
shipping_address,
shipping_carrier_code: shipping_method.carrier_code,
shipping_method_code: shipping_method.method_code
}
})
});

I'm Piyush Dankhra
Adobe Certified Expert - Adobe Commerce Developer / Front-End Developer / Business Practitioner
Adobe Subject Matter Expert - Adobe Commerce Front End Developer / Business Practitioner
Working on Magento 2 / Hyva