How to proxy requests to a websocket API?

872 Views Asked by At

I am trying to setup a dev env using webpack-serve to serve the generated frontend files (a react app), and proxy websocket requests to the path /api to a separate process.

The other process listens at port 5000, webpack-serve listens at port 5001.

However the connection to the other process is broken shortly (possibly immediately) after being established (the other process logs a connect/disconnect but the browser never shows a successful connection in the network tab of the dev tools), and I get a code 1006 from the WebSocket connection in the browser (but no error message).

I added the basic auth layer to webpack-serve so that the request for / would trigger the browser to request credentials and then the credentials would be sent to the /api requests too, as the other process requires basic auth.

I need to know what I'm doing wrong.

my webpack.config.js:

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");

const convert = require('koa-connect');
const history = require('connect-history-api-fallback');
const proxy = require('http-proxy-middleware');
const auth = require('koa-basic-auth');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    mode: 'development',
    devtool: 'source-map',
    resolve: {
        modules: [
            path.resolve(__dirname, 'node_modules'),
            path.resolve(__dirname, 'src')
        ],
        extensions: ['.jsx','.scss','.js']
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "bundle.css"
        })
    ],
    optimization: {
        minimizer: [
            new UglifyJsPlugin({
                cache: true,
                parallel: true,
                sourceMap: true
            }),
            new OptimizeCSSAssetsPlugin({
                cssProcessorOptions: { discardComments: { removeAll: true } },
            })
        ]
    },
    module: {
        rules: [
            {
                test: /\.(jsx?)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                }
            },
            {
                test: /\.(s?[ca]ss)$/,
                use: [{ loader: MiniCssExtractPlugin.loader, },
                      { loader: 'css-loader', },
                      { loader: 'postcss-loader', options: {
                          plugins: function () {
                              return [
                                  require('precss'),
                                  require('autoprefixer')
                              ];
                          }
                      } },
                      { loader: 'sass-loader', options: {
                          sourceMap: true
                      } }]
            }
        ]
    },
    serve: {
        content: 'dist',
        add: (app, middleware, options) => {
            app.use(convert(proxy('/api', { target: 'ws://localhost:5000' })));
            app.use(convert(history()));
            app.use(async (ctx, next) => {
                try {
                    await next();
                } catch (err) {
                    if (401 == err.status) {
                        ctx.status = 401;
                        ctx.set('WWW-Authenticate', 'Basic');
                        ctx.body = "can't haz that";
                    } else {
                        throw err;
                    }
                }
            });
            app.use(auth({ name: 'admin', pass: 'password' }));
            middleware.webpack();
            middleware.content();
        },
        clipboard: false,
        open: true,
        port: 5001,
        host: 'rrw.myhost.com'
    }
};
1

There are 1 best solutions below

0
On

Turns out I had to add the following to my proxy() arg-object:

auth: 'admin:password', ws: true