How to forward http requests to https with webpack?

Member

by domenico , in category: Javascript , 4 months ago

How to forward http requests to https with webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , a month ago

@domenico 

To forward HTTP requests to HTTPS using Webpack, you can use the http-proxy-middleware package. Here's how to do it:

  1. Install http-proxy-middleware by running the following command:
1
npm install http-proxy-middleware --save-dev


  1. Create a new file (e.g. proxy.js) in the root directory of your project and add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'https://your-https-endpoint-here.com',
      changeOrigin: true,
    })
  );
};


Replace 'https://your-https-endpoint-here.com' with the URL of your HTTPS endpoint.

  1. Update your Webpack configuration (usually found in webpack.config.js) to use the proxy middleware. Add the following code to the configuration:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const proxy = require('./proxy');

module.exports = {
  // Other webpack configurations...

  devServer: {
    before: function(app) {
      proxy(app);
    },
  },
};


Now, when you run your Webpack development server, all HTTP requests to /api will be proxied to the specified HTTPS endpoint.