Skip to content

Instantly share code, notes, and snippets.

@phusick
Created November 18, 2016 11:38
Show Gist options
  • Save phusick/c47b3c518fb5a265b5bd00e1ee1e5b3c to your computer and use it in GitHub Desktop.
Save phusick/c47b3c518fb5a265b5bd00e1ee1e5b3c to your computer and use it in GitHub Desktop.
Webpack Dev Server with Proxy
/* eslint-disable no-console */
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const cookieParser = require('cookie-parser');
const config = require('./webpack.config')();
const PORT = require('../../package.json').config.port;
function relayRequestHeaders(proxyReq, req) {
console.log('πŸ’₯πŸ’₯πŸ’₯ request πŸ’₯πŸ’₯πŸ’₯');
Object.keys(req.headers).forEach((key) => {
// console.log(`${key}: ${req.headers[key]}`);
proxyReq.setHeader(key, req.headers[key]);
});
}
function relayResponseHeaders(proxyRes, req, res) {
console.log('πŸ’₯πŸ’₯πŸ’₯ response πŸ’₯πŸ’₯πŸ’₯');
Object.keys(proxyRes.headers).forEach((key) => {
// console.log(`${key}: ${proxyRes.headers[key]}`);
res.append(key, proxyRes.headers[key]);
});
}
const server = new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
contentBase: 'config/development',
https: false,
hot: true,
historyApiFallback: true,
setup: function (app) {
app.use(cookieParser());
app.use(function (req, res, next) {
const USER_TOKEN = req.headers['x-user-token'];
const CSRF_TOKEN = req.headers['x-csrf-token'];
if (USER_TOKEN && CSRF_TOKEN) {
res.cookie('USER_TOKEN', USER_TOKEN, {
httpOnly: false,
});
res.cookie('CSRF_TOKEN', CSRF_TOKEN);
}
next();
});
},
proxy: {
'/httpbin/**': {
target: 'https://httpbin.org',
pathRewrite: { '^/httpbin': '' },
changeOrigin: true,
secure: true,
// onProxyReq: relayRequestHeaders,
// onProxyRes: relayResponseHeaders,
logLevel: 'debug',
},
'/requestbin/**': {
target: 'https://requestb.in/1690g9x1',
ignorePath: true,
changeOrigin: true,
secure: true,
logLevel: 'debug',
},
'/rest/**': {
target: 'https://secreturl.endomondo.com',
changeOrigin: true,
secure: true,
// onProxyReq: relayRequestHeaders,
// onProxyRes: relayResponseHeaders,
logLevel: 'debug',
},
},
});
server.listen(PORT, 'localhost', (err) => {
if (err) { return console.error(err); }
console.info('🌎 Listening on port %s.', PORT);
return undefined;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment