Skip to content

Instantly share code, notes, and snippets.

@edm00se

edm00se/About.md Secret

Last active September 1, 2021 18:34
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
custom dev server for parcel with http proxy

Parcel + http-proxy

For more, check out my blog post on the subject, which goes into deeper detail.

Loosely follows: https://github.com/nodejitsu/node-http-proxy/blob/master/test/lib-http-proxy-passes-web-incoming-test.js#L412

This is for creating a proxying dev server, making use of parcel's built-in dev server, and forwarding back-end calls (such as /api/). This does this all without using express or express middleware, but rather using http-proxy directly.

Why is this a concern? There is a great example, for those using express, on how to use parcel as middleware, but this requires use of express. My example uses Node's built-in http and the published http-proxy packages directly.

*note: I really like express, but I didn't feel like needing a third dev server installed was really needed

This is best invoked through an npm script, decalred in package.json such as:

"scripts": {
  "dev": "node dev-server.js",
const { createServer } = require('http');
const { createProxyServer } = require('http-proxy');
const Path = require('path');
const Bundler = require('parcel-bundler');
const backEnd = {
protocol: 'http',
host: 'localhost',
port: 8080
};
const parcelEnd = {
protocol: 'http',
host: 'localhost',
port: 1234
};
// parcel options, such as publicUrl, watch, sourceMaps... none of which are needed for this proxy server configuration
const options = {};
// point parcel at its "input"
const entryFiles = Path.join(__dirname, 'src', 'index.html');
// init the bundler
const bundler = new Bundler(entryFiles, options);
bundler.serve();
// create a proxy server instance
const proxy = createProxyServer();
// serve
const server = createServer((req, res) => {
if (req.url.includes('/api/')) {
proxy.web(req, res, {
// back-end server, local tomcat or otherwise
target: backEnd,
changeOrigin: true,
autoRewrite: true
});
} else {
// parcel's dev server
proxy.web(req, res, {
target: parcelEnd,
ws: true
});
}
});
console.log('dev proxy server operating at: http://localhost:5050/');
server.listen(5050);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment