Express proxy API calls with cookie Express proxy API calls with cookie express express

Express proxy API calls with cookie


If I understand you right, then your requirements list looks like:

  1. Simple integration with express.
  2. Proxy only one endpoint.
  3. Proxy only on local environment.
  4. Ability to set cookies for proxied request.

Code Example:

var express = require('express');var app = express();var path = require('path');var proxy = require('express-http-proxy');app.use(express.static(path.join(__dirname, 'public')));app.use(express.static(path.join(__dirname, 'dist')));if (process.env.NODE_ENV === 'production') {  app.get('/brand', function(req,res){    res.send({"brand":"Cadillac","origin":"USA"});  });} else {  app.use('/brand', proxy('http://www-dev.abc.com/brand', {    proxyReqOptDecorator: function(proxyReqOpts, srcReq) {      proxyReqOpts.headers['cookie'] = 'cookie-string';      return proxyReqOpts;    }  }));}app.listen(8000);

Comments:

  • For checking environment type I used construction process.env.NODE_ENV === 'production'
  • The best package for your requirements is express-http-proxy, but if you will need to proxy multiple endpoints, it will be painfully. Check http-proxy in this case.