Skip to content

Latest commit

 

History

History
419 lines (323 loc) · 10.9 KB

File metadata and controls

419 lines (323 loc) · 10.9 KB

Servers

Overview of http-proxy-middleware implementation in different servers.

Missing a server? Feel free to extend this list of examples.

http.createServer

Vanilla http server implementation with http.createServer

import * as http from 'node:http';

import { createProxyMiddleware } from 'http-proxy-middleware';

/**
 * Configure proxy middleware
 */
const apiProxy = createProxyMiddleware({
  target: 'http://www.example.com',
  changeOrigin: true, // for vhosted sites, changes host header to match to target's host
});

const server = http.createServer(apiProxy);

server.listen(3000);

Express

https://github.com/expressjs/express GitHub stars express downloads

import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';

const apiProxy = createProxyMiddleware({
  target: 'http://www.example.org/api',
  changeOrigin: true, // for vhosted sites
});

const app = express();

app.use('/api', apiProxy);
app.listen(3000);

Connect

https://github.com/senchalabs/connect GitHub stars connect downloads

import * as http from 'node:http';

import connect from 'connect';
import { createProxyMiddleware } from 'http-proxy-middleware';

const apiProxy = createProxyMiddleware({
  target: 'http://www.example.org/api',
  changeOrigin: true, // for vhosted sites
});

const app = connect();
app.use('/api', apiProxy);

http.createServer(app).listen(3000);

Next.js

https://github.com/vercel/next.js GitHub stars next.js downloads

See working Next.js example in /examples/next-app/pages/api/users.ts

// Next project: `/pages/api/users.proxy.ts`
import { createProxyMiddleware } from 'http-proxy-middleware';

// singleton
export const proxyMiddleware = createProxyMiddleware<NextApiRequest, NextApiResponse>({
  target: 'http://jsonplaceholder.typicode.com',
  changeOrigin: true,
  pathRewrite: {
    '^/api/users': '/users',
  },
});
// Next project: `/pages/api/users.ts`
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';

import { proxyMiddleware } from './users.proxy';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  proxyMiddleware(req, res, (result: unknown) => {
    if (result instanceof Error) {
      throw result;
    }
  });
}

export const config = {
  api: {
    externalResolver: true,
    // Uncomment to fix stalled POST requests
    // https://github.com/chimurai/http-proxy-middleware/issues/795#issuecomment-1314464432
    // bodyParser: false,
  },
};

// curl http://localhost:3000/api/users

Hono

https://github.com/honojs/hono GitHub stars hono downloads

import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import { createHonoProxyMiddleware } from 'http-proxy-middleware';

const app = new Hono();

app.use(
  '/users',
  createHonoProxyMiddleware({
    target: 'http://jsonplaceholder.typicode.com',
    changeOrigin: true, // for vhosted sites, changes host header to match to target's host
    logger: console,
  }),
);

const server = serve(app);

// curl http://localhost:3000/users

fastify

https://github.com/fastify/fastify GitHub stars fastify downloads

See working example in /examples/fastify/index.js

import fastifyExpress from '@fastify/express';
import fastifyFactory from 'fastify';
import { createProxyMiddleware } from 'http-proxy-middleware';

const fastify = fastifyFactory({ logger: true });

(async () => {
  await fastify.register(fastifyExpress);

  const proxy = createProxyMiddleware({
    target: 'http://jsonplaceholder.typicode.com',
    changeOrigin: true,
  });

  fastify.use(proxy);

  fastify.listen({ port: 3000 }, (err, address) => {
    if (err) throw err;
    fastify.log.info(`server listening on ${address}`);
  });
})();

// curl http://localhost:3000/users

Browser-Sync

https://github.com/BrowserSync/browser-sync GitHub stars browser-sync downloads

import BrowserSync from 'browser-sync';
import { createProxyMiddleware } from 'http-proxy-middleware';

const browserSync = BrowserSync.create();

const apiProxy = createProxyMiddleware({
  target: 'http://www.example.org',
  changeOrigin: true, // for vhosted sites
  pathFilter: '/api',
});

browserSync.init({
  server: {
    baseDir: './',
    port: 3000,
    middleware: [apiProxy],
  },
  startPath: '/api',
});

Polka

https://github.com/lukeed/polka GitHub stars polka downloads

import { createProxyMiddleware } from 'http-proxy-middleware';
import polka from 'polka';

const app = polka();

app.use(
  createProxyMiddleware({
    target: 'http://www.example.org',
    changeOrigin: true,
  }),
);

app.listen(3000);

lite-server

https://github.com/johnpapa/lite-server GitHub stars lite-server downloads

File: bs-config.mjs

import { createProxyMiddleware } from 'http-proxy-middleware';

const apiProxy = createProxyMiddleware({
  target: 'http://www.example.org',
  changeOrigin: true, // for vhosted sites
  pathFilter: '/api',
});

export default {
  server: {
    // Start from key `10` in order to NOT overwrite the default 2 middleware provided
    // by `lite-server` or any future ones that might be added.
    // Reference: https://github.com/johnpapa/lite-server/blob/master/lib/config-defaults.js#L16
    middleware: {
      10: apiProxy,
    },
  },
};

grunt-contrib-connect

https://github.com/gruntjs/grunt-contrib-connect GitHub stars grunt-contrib-connect downloads

As an Array:

import { createProxyMiddleware } from 'http-proxy-middleware';

const apiProxy = createProxyMiddleware({
  target: 'http://www.example.org',
  changeOrigin: true, // for vhosted sites
  pathFilter: '/api',
});

grunt.initConfig({
  connect: {
    server: {
      options: {
        middleware: [apiProxy],
      },
    },
  },
});

As a function:

import { createProxyMiddleware } from 'http-proxy-middleware';

const apiProxy = createProxyMiddleware({
  target: 'http://www.example.org',
  changeOrigin: true, // for vhosted sites
  pathFilter: '/api',
});

grunt.initConfig({
  connect: {
    server: {
      options: {
        middleware: function (connect, options, middlewares) {
          // inject a custom middleware into the array of default middlewares
          middlewares.unshift(apiProxy);

          return middlewares;
        },
      },
    },
  },
});

gulp-connect

https://github.com/avevlad/gulp-connect GitHub stars gulp-connect downloads

import gulp from 'gulp';
import connect from 'gulp-connect';
import { createProxyMiddleware } from 'http-proxy-middleware';

gulp.task('connect', function () {
  connect.server({
    root: ['./app'],
    middleware: function (connect, opt) {
      const apiProxy = createProxyMiddleware({
        target: 'http://www.example.org',
        changeOrigin: true, // for vhosted sites
        pathFilter: '/api',
      });

      return [apiProxy];
    },
  });
});

gulp.task('default', ['connect']);

grunt-browser-sync

https://github.com/BrowserSync/grunt-browser-sync GitHub stars grunt-browser-sync downloads

import { createProxyMiddleware } from 'http-proxy-middleware';

const apiProxy = createProxyMiddleware({
  target: 'http://www.example.org',
  changeOrigin: true, // for vhosted sites
  pathFilter: '/api',
});

grunt.initConfig({
  // BrowserSync Task
  browserSync: {
    default_options: {
      options: {
        files: ['css/*.css', '*.html'],
        port: 9000,
        server: {
          baseDir: ['app'],
          middleware: apiProxy,
        },
      },
    },
  },
});

gulp-webserver

https://github.com/schickling/gulp-webserver GitHub stars gulp-webserver downloads

import gulp from 'gulp';
import webserver from 'gulp-webserver';
import { createProxyMiddleware } from 'http-proxy-middleware';

gulp.task('webserver', function () {
  const apiProxy = createProxyMiddleware({
    target: 'http://www.example.org',
    changeOrigin: true, // for vhosted sites
    pathFilter: '/api',
  });

  gulp.src('app').pipe(
    webserver({
      livereload: true,
      directoryListing: true,
      open: true,
      middleware: [apiProxy],
    }),
  );
});

gulp.task('default', ['webserver']);