Blog » Mocking and proxying HTTP requests from localhost with Webpack Dev Server or Express

Mocking and proxying HTTP requests from localhost with Webpack Dev Server or Express

2018-06 |

This content is only available in english

Mocking and proxying HTTP requests from localhost with Webpack Dev Server or Express

Back in the day, my JS projects were small and self-contained. Nowadays, in my professional work, majority, if not all of front-end applications I am working on are connected to multiple back-end services for variety of reasons. It gives me a freedom of not caring of the back-end, as long as we have defined a contract, and proceeding happily with what actually matters, i.e. colors and animations. But it also gave ma some headache, when I wanted to have pleasant, convenient coding environment on my localhost, and not have all of these weird back-end stuff running on my local machine as well. Here's how I worked it out with both Webpack Dev Server and Express.

I've found two ways of dealing with HTTP requests coming out of my front-end, so that I can handle them freely, without major changes to development version of my application: mocking and proxying. Both are based on intercepting these requests on my localhost level, and handling them manually. However, they are handled differently, and they have their own pros, cons, and ideal case, in which you want to use them.

There is some code in this post, displaying how you can mock or proxy this problem out of your way. There is also some more code on this subject on my github, in code examples section of my blog repository. You'll find a small setup there, which showcases all ideas I'm bragging about in this post. There is an application with a button, that sends HTTP request with fetch; local server, that you can proxy your requests to; and four examples, each demonstrating different solution to this problem. Check it out!

Mocking

With mocked HTTP request response, you don't even call any back-end at all. Request is intercepted, and mocked - manually defined by you - response is served by your localhost. It's useful for most cases, because it gets the job done easily. It's particularly useful, when your back-end is just slow, or there is a lot of data to transfer, or a lot of calls - you just don't transfer any data over the wire, and there is no delay in your development. Downside of this solution is that you never see actual response that is coming from the service. You may end up surprised by totally different data model provided by back-end, or by any other difference between your assumption stated in your mock and actual response.

Webpack Dev Server

proxy is an option in configuration of Webpack Dev Server, which allows you to define proxy for any HTTP request that comes out of your localhost. You can also define specific bypass in it, with conditions as detailed as you want. In my example, I'm intercepting all calls to /api URL, and respond with mocked JS object instead.

devServer: {
  // ...
  proxy: {
    '/api': {
      bypass: (request, response) => {
        if (request.url.substr(-4) === '/api') {
          response.send({ data: 'mocked data from webpack.devserver.mock.config.js' })
        }
      },
    },
  },
},

(content of the whole script available here)

Express

Contrary to Webpeck Dev Server, mocking a response in Express doesn't feel like hacking. It's very straightforward, almost like this framework was created specifically to perform tasks like this (?!).

const app = express();

// ...

app.get('/api', (request, response) => {
  response.json({ data: 'mocked data from express.mock.js' });
});

(content of the whole script available here)

Proxying

With proxied HTTP request, you call actual back-end service. Request is only proxied - redirected to it's true destination, and potentially modified a bit. It's usually preferred for when you are fine with getting real data from real service, even at a cost of waiting some additional time with each visit to your localhost, but your back-end is on different host than your local, which is usually the case. Cons? If you can afford it time- and resources-wise, there are none, in my experience.

Webpack Dev Server

Proxy with Webpack Dev Server can be achieved using proxy configuration option, this time more like it was originally intended. target parameter describes destination to which certain call should be redirected. If pathRewrite parameter is not provided, /api will be concatenated with the target, which is not what I wanted to achieve here (hence I've defined this parameter), but you may find it useful.

devServer: {
  // ...
  proxy: {
    '/api': {
      target: 'http://localhost:3001/get-secret-data',
      pathRewrite: { '^/api': '' },
    },
  },
},

(content of the whole script available here)

Express

In Express, it's a little bit more effort, since it's required to incorporate http-proxy package for this operation. Similarly to Webpack Dev Server, target parameter defines destination of your redirection. The other parameter, ignorePath, is set to false by default. If you don't override it, /api will be added to the end of your request's URL. Again, it might be what you want in some cases.

const app = express();
const apiProxy = httpProxy.createProxyServer();

// ...

app.get('/api', (request, response) => {
  apiProxy.web(request, response, {
    target: 'http://localhost:3001/get-secret-data',
    ignorePath: true,
  });
});

(content of the whole script available here)

Other blog posts

How to set up tooling around your open source project

2019-11 |

This content is only available in english

How to set up tooling around your open source project

Lately in my project we had very particular need for specific validation of content of JavaScript bundle produced by Webpack. In the process of extensive research we have not found any existing tool to serve this purpose. Therefore, I've created Webpack Bundle Content Validator, which is a Webpack plugin and a CLI tool for Webpack bundle content validation. More importantly, I made it open source. Surprisingly, simply publishing it to NPM wasn't enough - I decided to set up continuous integration, automated unit tests code coverage calculation, automated check for vulnerabilities and a few other things, in order to make it legitimate and reliable package. In this post I'm describing those steps in details.

Continue reading

When building web applications in React, I usually choose Express to be my server, and more often than not I use React-Router to manage redirections and changes in history. Not without a reason - both are among the most popular choices in their respective fields nowadays; both are simple and elegant in every day work. However, I had some tough moments with both of them when it came up to setting all unrecognized routing to "Not Found" page, and this piece came as a result of them.

Continue reading

Hard to imagine, but it's over 1 year since I created this blog, and up until recently, it always had static head tags. Title always being the same, for example, wasn't that much of an issue to me, but social meta tags never related to the content of the post I'm sharing on Twitter, that was not cool (it's also not cool when it comes to SEO, but it's not that much of my concern right now). I finally had to tackle it. Here's a simple way to do it that I've found.

Continue reading

Syntax highlighting in React with highlight.js and Web Worker

2018-09 |

This content is only available in english

Syntax highlighting in React with highlight.js and Web Worker

One of the most common issues I heard people have with my blog was lack of syntax highlighting in posts, especially those, which contain a lot of code. Okay, it's almost 2019, I'm a software engineer, working mostly with front-end these times - I finally agreed, that it should be added. So I added it. And in the meantime, I also learned a little bit about Web Workers. Hence, this post, in which I describe this little adventure.

Continue reading

My first MobX store

2018-07 |

This content is only available in english

My first MobX store

My dad wants to read my blog. The only issue is that he doesn't speak English very well. It's communicative, but it's not quite enough to understand intricate, sophisticated Shakespearean language, I am decorating my posts with. Worry not, father, as I've found the solution: language versions. I am currently working on adaptations of my posts in Polish language. In the meantime, I'm also adapting my codebase to be able to recognize and properly handle language parameter. And for that purpose, for the first time, I decided to use MobX.

Continue reading