I was setting up a nodejs api with 2 different react front ends and found that I kept running into CORS issues.
To get around this I created 3 servers. 2 for each of the front ends and 1 for the actual api server. My thoughts were that I would authenticate on the 2 proxy servers that have the react apps on them and then forward all other requests to the api server with the cookie's info set in a json web token.
However, upon setting up http-proxy-middleware and setting changeOrigin to true I've noticed that the cookie also gets sent along with the request which is awesome. Is this what changeOrigin is meant to do and will it work for all types of requests?
This is how I'd setup my proxy options:
// routes
app.use('/api/auth', require('./routes/openRoutes/authRoutes'));
// api routes
const proxyOptions = {
target: gateway.url, // target host
changeOrigin: true,
onProxyReq: function onProxyReq(proxyReq, req, res) {
// add custom header to request
const id = req.user ? req.user.id : null;
const token = jwt.sign({
data: id
}, sessionSecret, { expiresIn: '1h' });
if (token) {
proxyReq.setHeader('authorization', `Bearer ${token}`);
}
},
logLevel: 'debug',
};
app.use('/api/admin/user', createProxyMiddleware(proxyOptions));