Is there a way to proxy requests in Parcel as in Webpack?

Viewed 7931

In Webpack there is an ability to proxy backend requests through proxy setting in the config file. That allows me to develop a front-end part of my app with webpack-dev-server with HMR while webpack-dev-server and my app server run on different ports on my localhost. There is also a development server in Parcel which is run by default command parcel index.html on port 1234. Is there a way to run both Parcel dev server and proxy requests to my app server?

I found a solution that suggests using Express middleware for that. But that doesn't solve the problem completely and cleanly. What if my backend runs Django? How should I use Parcel dev server then?

2 Answers

This is currently not supported directly, see the open pull-request https://github.com/parcel-bundler/parcel/pull/2477

However, https://github.com/parcel-bundler/parcel/issues/55 and lists various solutions involving a simple wrapper, such as:

for http-proxy-middleware >= 1.0.0 (Published 2/2020):

const Bundler = require('parcel-bundler');
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');


const app = express();

app.use(createProxyMiddleware('/api', {
  target: 'http://localhost:3000'
}));

const bundler = new Bundler('src/index.html');
app.use(bundler.middleware());

app.listen(Number(process.env.PORT || 1234));

For older http-proxy-middleware (versions 0.x):

const Bundler = require('parcel-bundler');
const express = require('express');
const proxy = require('http-proxy-middleware');

const app = express();

app.use('/api', proxy({
  target: 'http://localhost:3000/api'
}));

const bundler = new Bundler('src/index.html');
app.use(bundler.middleware());

app.listen(Number(process.env.PORT || 1234));

There is an npm module called parcel-proxy-server that might help. I have tried it myself, and it works quite well for my project.

From the documentation: Create a file, e.g. server.js

const ParcelProxyServer = require('parcel-proxy-server');

// configure the proxy server
const server = new ParcelProxyServer({
  entryPoint: './path/to/my/entry/point',
  parcelOptions: {
    // provide parcel options here
    // these are directly passed into the
    // parcel bundler
    //
    // More info on supported options are documented at
    // https://parceljs.org/api
    https: true
  },
  proxies: {
    // add proxies here
    '/api': {
      target: 'https://example.com/api'
    }
  }
});

// the underlying parcel bundler is exposed on the server
// and can be used if needed
server.bundler.on('buildEnd', () => {
  console.log('Build completed!');
});

// start up the server
server.listen(8080, () => {
  console.log('Parcel proxy server has started');
});

then call node server.js to run your proxy, and the default parcel command.

Related