Webpack 5 devServer proxy config and pathRewrite for context matching, CORS policy


In web front-end development, with the devServer proxy in Webpack, we have some useful configs.

CORS policy devServer.proxy

We can use this config devServer proxy for the SPA calling the API without CORS policy

"The browser console will present an error like "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite" indicating that the request was blocked due to violating the CORS security rules." – said MDN web docs.

We have many work-around solutions:

  • Config the server to accept the SPA’s request
  • Launch browser to bypass the CORS policy with arg --disable-web-security
  • Config via the devServer.proxy

Proxying some URLs can be useful when you have a separate API backend development server and you want to send API requests on the same domain.

We can use config below to enable proxying, in short:

module.exports = {
  ...
  devServer: {
    proxy: {
      '/api': 'http://localhost:51743',
    }
  }
};

or more options:

module.exports = {
  ...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:51743',
        // pathRewrite: { '^/api': '' },
      }
    }
  }
}

Another way of the config above:

module.exports = {
  devServer: {
    ...
    proxy: [{
      context: ['/api'],
      target: 'http://localhost:51743',
      // pathRewrite: { '^/api': '' },
    }]
  }
}
  • target: A request to /api/users will now proxy the request to http://localhost:51743/api/users.

  • pathRewrite: If we don’t want /api to be passed along.
    Eg: /api/users => http://localhost:51743/users

  • context: Only proxy /api and /auth addresses, the rest are allowed.
    Eg: context: ['/auth', '/api'].

SPA get 404 error when refreshing the page or access directly?

The navigation between pages works perfectly by clicking through several routes and everything seemed fine until we refreshed the page or tried to access a route directly. We got a 404 error as my previous post, but for the production. What’s about the development?

This config is very useful for SPAs development environment. We can re-write all the request by telling web server to redirect all requests to our index.html, with pathRewrite.

module.exports = {
  ...
  devServer: {
    proxy: [
      {
        context: ['/auth', '/api'],
        target: 'http://localhost:51743',
        pathRewrite: {'.*' : '/'}
      },
    ],
  },
};

Note that, we have to define and take care the context carefully as /images, /js may be failed to load.

Reference:

Original written from my blog: https://nready.net/?p=1344
@Le Quoc Nam, Saigon, 02 Nov 2022


Leave a Reply