http-proxy-middleware icon indicating copy to clipboard operation
http-proxy-middleware copied to clipboard

add custom query param

Open nikksan opened this issue 7 years ago • 3 comments

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))

nikksan avatar Aug 29 '18 12:08 nikksan

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 avatar Aug 29 '18 12:08 nikksan

@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));

rizalibnu avatar Dec 22 '18 06:12 rizalibnu

#184

christiaanwesterbeek avatar Nov 12 '19 10:11 christiaanwesterbeek