http-proxy-middleware
http-proxy-middleware copied to clipboard
add custom query param
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))
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