Http-proxy-middleware: add custom query param

Created on 29 Aug 2018  路  3Comments  路  Source: chimurai/http-proxy-middleware

I searched the docs but I couldnt find anything close to that.
How can I add custom query param to the request ?
I tried by setting up different middleware just to add them to the query, but I guess they are not taken in account.

const addQueryCredentials = (req, res, next) => {
  req.query.client_id = clientId;
  req.query.client_secret = clientSecret
  next();
}
app.use(addQueryCredentials)
app.use('/', proxy(proxyFilter, proxyOpts))

Most helpful comment

@nikksan you can use pathRewrite to add custom query param to the request, try this:

const updateQueryStringParameter = (path, key, value) => {
  const re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i');
  const separator = path.indexOf('?') !== -1 ? '&' : '?';
  if (path.match(re)) {
    return path.replace(re, '$1' + key + '=' + value + '$2');
  } else {
    return path + separator + key + '=' + value;
  }
};

const options = {
  target: `https://www.example.com`,
  pathRewrite: function(path, req) {
    let newPath = path;
    newPath = updateQueryStringParameter(newPath, 'client_id',  clientId);
    newPath = updateQueryStringParameter(newPath, 'client_secret',  clientSecret);
    return newPath;
  },
};

app.use('/api', proxy(options));

All 3 comments

Ok, I actually found I way to achieve it by looking at the source code.

const addQueryParams = (req, res, next) => {
  req.originalUrl = modifyOriginalUrl()
  next()
}

Is there any classier solution ?
I relly dont want this logic to reside inside express middleware.

@nikksan you can use pathRewrite to add custom query param to the request, try this:

const updateQueryStringParameter = (path, key, value) => {
  const re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i');
  const separator = path.indexOf('?') !== -1 ? '&' : '?';
  if (path.match(re)) {
    return path.replace(re, '$1' + key + '=' + value + '$2');
  } else {
    return path + separator + key + '=' + value;
  }
};

const options = {
  target: `https://www.example.com`,
  pathRewrite: function(path, req) {
    let newPath = path;
    newPath = updateQueryStringParameter(newPath, 'client_id',  clientId);
    newPath = updateQueryStringParameter(newPath, 'client_secret',  clientSecret);
    return newPath;
  },
};

app.use('/api', proxy(options));

184

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pwlerke picture pwlerke  路  6Comments

minhduchcm picture minhduchcm  路  7Comments

dzz9143 picture dzz9143  路  3Comments

mshindal picture mshindal  路  4Comments

SidneyNemzer picture SidneyNemzer  路  5Comments