Home > Net >  Express get request code: 'ERR_HTTP_HEADERS_SENT' when sending response
Express get request code: 'ERR_HTTP_HEADERS_SENT' when sending response

Time:07-03

So this is a common problem in Express, this question is asked a lot but none of them worked for me,
I have a get request with axios to my express server to check the auth status of the user with firebase, everything works fine, but this error shows in my console, here's the code:

Server.js

const firebaseDb=require("firebase/database");
const firebaseAuth=require("firebase/auth");
const path = require('path');
const express= require("express");
var cors = require('cors');
const bodyParser = require("body-parser");

const app=express();

app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));

const db=firebaseDb.getDatabase();
const auth=firebaseAuth.getAuth();
app.get('/checkAuth',(req, res)=>{  

firebaseAuth.onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in.      
    return res.status(200).send("auth ok");

  } else {
    // User is signed out
    return res.status(404).send("auth error");
  }
});
});

So the error is exactly where my return res.status(200).send("auth ok");
I tried return res.sendStatus(200); still same problem,
some solutions suggested to add the returnbefore the res.send but again it didn't work, ANY IDEA ABOUT THIS ERROR?

CodePudding user response:

Disclaimer: I have no experience with the Firebase library, but I can read documentation.

onAuthStateChanged is an event emitter that can fire events for multiple situations: the current user signed in, or they signed out. Because it's an event emitter, it can emit multiple events, and that's your problem: for each event, you're calling either res.status(200).send() or res.status(404).send(). This works for the first event that is emitted, but the second event will trigger a ERR_HTTP_HEADERS_SENT error because you already sent back a response.

Besides that, you're creating a new event handler for every request to /checkAuth, which will eventually cause your app to run out of memory, because these event emitters remain active. 1000 requests to /checkAuth means you create 1000 event handlers.

If I understand the documentation correctly, it looks like you can use auth.currentUser instead, as documented here:

app.get('/checkAuth', (req, res) => {  
  const user = auth.currentUser;

  if (user) {
    // User is signed in.      
    return res.status(200).send("auth ok");
  } else {
    // User is signed out
    return res.status(404).send("auth error");
  }
});
  • Related