Skip to content

Add a Proxy to browsersync

Drake Wilson edited this page Mar 8, 2016 · 12 revisions

If you have an API Server running on a different port, you may want to proxy requests from you application to your api.

You can do this by adding a middleware to browsersync. (Shortcut)

One way to do this is by installing the proxy-middleware.

npm install proxy-middleware --save-dev

Then open the file tools/utils/seed/code_change_tools.ts.

At the top of the file you include the proxy-middleware by

const proxy = require('proxy-middleware');

There is currently a block that looks like this:

browserSync({
  middleware: [require('connect-history-api-fallback')({index: `${APP_BASE}index.html`})],
  port: PORT,
  startPath: APP_BASE,
  server: {
    baseDir: baseDir,
    routes: routes
  }
});

We need to change a few things here:

  1. Move the top-level middleware property inside the server property.
  2. Then, add the proxy as first middleware before the connect-history-api-fallback.
browserSync({
  port: PORT,
  startPath: APP_BASE,
  server: {
    baseDir: baseDir,
    middleware: [
      proxy({
        protocol: 'http:',
        hostname: 'localhost',
        port: 8080,
        pathname: '/api',
        route: '/api'
      }),
      require('connect-history-api-fallback')({index: `${APP_BASE}index.html`})
    ],
    routes: routes
  }
});

This configuration will proxy all requests starting with /api (route-property) to another server on localhost:8080/api.

Shortcut

This is the shortcut version to add a proxy to localhost:8080 for any requests on /api

npm install proxy-middleware --save-dev

replace tools/utils/seed/code_change_tools.ts with the gist here

Clone this wiki locally