4

I'm having some issues trying to send an axios requests with custom headers from my app so I can use them for authentication on my server.

I have a react native app that uses firebase authentication and a node/express backend server.

When a user signs in, I will grab their firebase idtoken and store it.

I will then send that idtoken as a header whenever I make an axios request to the server.

 const { currentUser } = firebase.auth();

  const url = ${serverUrl}/api/users/${user.uid`;

  const idtoken = await currentUser.getToken(true);

    var config = {
      headers: { idtoken },
    };

const response = await axios(url, config);

In the server code, there will be an express middleware that checks whether the idtoken sent in the request header is valid or not. If it is, it will call next() and proceed to execute the logic. If not, then it'll fail and send a 401 status.

This is in my app.js:

const app = express();


  app.use(bodyParser.json());

  app.use(firebaseAuthentication);
  router(app);

This is the firebaseAuthentication middleware:

const firebaseAuthentication = async (req, res, next) => {
  console.log(req);
  try {
    const { idtoken } = req.headers;

    await admin.auth().verifyIdToken(idtoken);
    next();
  } catch (e) {
    res.status(401).send({ error: 'Unauthorized request. Must be signed in via firebase' });
  }
};

This is the router:

module.exports = app => {

    app.get('/api/users/:firebaseUID', UserController.getUser);
}

The issue is that everything seems to go through until it tries to send the good data back to the user...but I get a 404 and a Error: Can't set headers after they are sent

This is the specific request that is failing:

  async getUser(req, res, next) {
    const firebaseUID = req.params.firebaseUID;
    try {
      const user = await User.findOne({ firebaseUID });

      res.send(user);
    } catch (e) {
      next(e);
    }
  },

What is happening here and how can I fix it? Thanks!

judgejab
  • 519
  • 1
  • 3
  • 14

0 Answers0