0

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));
Phil
  • 157,677
  • 23
  • 242
  • 245
KAT
  • 125
  • 3

1 Answers1

0

changeOrigin doesn't do anything to cookies or any other request header besides Host

option.changeOrigin: true/false, Default: false - changes the origin of the host header to the target URL

So if your request looks like this...

GET /api/admin/user
Host: your.frontend.domain
Cookie: connect.sid=whatever

the only thing the changeOrigin changes is Host

GET /api/admin/user
Host: your.gateway.domain
Cookie: connect.sid=whatever
Authorization: Bearer <your JWT token>

This is so the upstream service can route the request to appropriate name-based virtual host.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • So the cookie will always come along then? Because before I made this change the cookie was being set but the api server never saw it. req.cookie was always undefined. – KAT Feb 16 '23 at 02:54
  • Are you using name-based virtual hosts on the API side? – Phil Feb 16 '23 at 02:56
  • I will need to look that up. I'm new to a lot of this so I'm not sure. – KAT Feb 16 '23 at 03:01