In a node.js + express application, use a proxy route as middleware for another proxy

23 Views Asked by At

I have a node.js app with an api-gateway that routes to several microservices. One of the microservices is the authentication microservice. I want to use the route auth/verifySession to check if the session is still valid, and attaching the session.userId to be able to access any of the other routes from the gateway. But I can't seem to find how to properly set it up.

This is the the code for the router used by the gateway:

type import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware';

const router = express.Router();

const authProxy = createProxyMiddleware({
  target: 'http://auth-ms:3013',
  changeOrigin: true,
  onProxyReq: fixRequestBody,
})
const serviceProxy = createProxyMiddleware({
  target: 'http://service-ms:3010',
  changeOrigin: true,
  onProxyReq: fixRequestBody,
});

router.get('/', (req, res) => {
  res.send('Hello World!')
})

router.use(cors());

const sessionCheck = async (req, res, next) => {
  try {
    const sessionResponse = await axios.get('http://auth-ms:3013/verifySession');

    if (sessionResponse.data && sessionResponse.data.userId) {
      req.userId = sessionResponse.data.userId;
      next();
    } else {
      res.status(401).send('Unauthorized');
    }
  } catch (error) {
    console.error('Error verifying session:', error);
    res.status(500).send('Internal Server Error');
  }
};

router.use('/auth', cors(), authProxy);
router.use('/service', cors(), sessionCheck, serviceProxy);

export default router;
here

And this is the route in auth for verifying the session:

router.get('/verifySession', async (req, res) => {
  try {
    const hashedSessionData = req.cookies.sessionId;

    const isSessionValid = await bcrypt.compare(JSON.stringify(req.session), hashedSessionData);

    if (!isSessionValid) {
      throw new Error('Invalid session');
    }

    res.json({ message: 'Session is valid', userId: req.session.userId });
  } catch (error) {
    console.error('Error verifying session:', error.message);
    res.status(401).json({ error: 'Invalid session' });
  }
});

After the session verification I am getting ERR_CON_REFUSED when trying to access any of the auth routes, when it worked during previous attempts.

0

There are 0 best solutions below