Proxying requests to server

People often serve the front-end ScandiPWA app from the same host and port as their backend implementation (i.e. Magento theme).

For example, a production setup might look like this after the app is deployed:

/* - static server returns index.html with ScandiPWA app
/graphql - Magento 2 server handles any GraphQL reuqests
/media - Magento 2 server handles any media asset requets

Such setup is not required. However, if you do have a setup like this, it is convenient to write requests like fetch('/graphql') without worrying about redirecting them to another host or port during development.

To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json, for example:

"proxy": "http://localhost:4000",

This way, when you fetch('/graphql') in development, the development server will recognize that it’s not a static asset and will proxy your request to http://localhost:4000/graphql as a fallback. The development server will only attempt to send requests without text/html in its Accept header to the proxy.

Configuring proxy manually

If the proxy option is not flexible enough for you, you can get direct access to the Express app instance and hook up your own proxy middleware.

You can use this feature in conjunction with the proxy property in package.json, but it is recommended you consolidate all of your logic into src/setupProxy.js.

First, install http-proxy-middleware using npm or Yarn:

npm install http-proxy-middleware --save # for NPM
yarn add http-proxy-middleware # for Yarn

Next, create src/setupProxy.js and place the following contents in it:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  // ...
};

You can now register proxies as you wish! Here's an example using the above http-proxy-middleware:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/graphql',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
    })
  );
};

Heads up!

You do not need to import this file anywhere. It is automatically registered when you start the development server.

Configuring the Magento 2 server

To proxy requests to the Magento 2 server, you are required to make sure that it is using the correct Composer dependencies. The list of your application Composer dependencies can be found in your application composer.json file.

You can copy the requirements defined in require field of your application's composer.json to your server's root composer.json and execute the composer update command.

In case you plan on deploying ScandiPWA as a Magento theme, you might simply require the ScandiPWA's composer package and it will be registered in Magento as the valid theme. Read more about this process in the Magento theme deployment guide.

Last updated