Express and Firebase Function: Headers cannot be set once they have already been sent

My experience has been mainly with the Hapi framework for developing RESTful APIs. However, for my current project, I decided to use Express and I'm encountering some confusion regarding the issues that are arising.

While testing the POST endpoint using Postman, everything seems to work fine with the first request, but I encounter an error when attempting a second request.

Error: Can't set headers after they are sent.

The route handler code is as follows:

const login = (req, res) => {
  const validation = authScema.loginPayload.validate(req.body)
  if (validation.error) {
    return res.status(400).send(validation.error.details[0].message)
  }

  const { email, password } = req.body

  firebase
    .auth()
    .signInWithEmailAndPassword(email, password)
    .catch(error => {
      // Handle Errors here.
      if (error) {
        return res.status(400).send('Invalid login details.')
      }
    })

  firebase.auth().onAuthStateChanged(user => {
    if (user) {
      const userObject = {
        email: user.email,
        uid: user.uid
      }
      const token = jwt.sign(userObject, secret)
      return res.status(200).send(token)
    }
  })
}

I am perplexed by the fact that the headers seem to be resent even though I have returns in every branch. The function should exit at that point, shouldn't it?

Answer №1

It turns out that the signInWithEmailAndPassword function is a promise that will return the user in the happy path.

Therefore, here is the final code snippet:

firebase
    .auth()
    .signInWithEmailAndPassword(email, password)
    .then(user => {
      const userObject = {
        email: user.email,
        uid: user.uid
      }

      const token = jwt.sign(userObject, secret)
      res.status(200).json({ token })
    })
    .catch(error => {
      if (error) {
        res.status(400).json({ message: 'Invalid login details.' })
      }
    })

The onOnAuthStateChanged function is not needed in this specific case.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the differences between app.set and app.value in Express

In my app.js file, I typically utilize app.set(valName, value) to transmit various configuration values to my routes. After which, I connect the app to my routes by executing: app.use('/', require('./routes/index')(app)); This allow ...

Dynamic sidebar that adheres to the content and is placed alongside it using JavaScript

I am in need of creating a sticky sidebar that will float beside my content column. The purpose of this sidebar is to contain jump links on the page, similar to what can be seen on this page, but with the navigation buttons positioned directly next to the ...

Guide for Uploading, presenting, and storing images in a database column with the help of jQuery scripting language

What is the best method for uploading, displaying, and saving an image in a database using jQuery JavaScript with API calls? I am working with four fields in my database: 1. File ID 2. Filename 3. Filesize 4. Filepath ...

What is the best way to send a query in a jQuery AJAX call?

I am a beginner in working with AJAX requests and server programming. This project is part of my school assignment. I need to include the SID that was generated as a parameter for this request. Additionally, I am trying to pass in an object of colors, a st ...

Looking to develop a dynamic password verification form control?

I am in the process of developing a material password confirmation component that can be seamlessly integrated with Angular Reactive Forms. This will allow the same component to be utilized in both Registration and Password Reset forms. If you would like ...

Default close x button not functioning to close modal dialog

When I click the [X] button in my modal dialog box, it doesn't close. Here is an example of my code: $('#apply_Compensation_Leave').show(); This is the modal code: <div class="modal" id="apply_Compensation_Leave" tabindex="-1" role="di ...

Activate the date-picker view when the custom button is clicked

Utilizing this library for date-picker functionality has been quite beneficial. I am currently working on a feature that involves opening the date-picker upon clicking a custom button. The default input is functioning properly. <input name="pickerFromD ...

Could converting a 47-byte JSON string into 340 MB be possible through JSON stringification?

var keys = [7925181,"68113227"]; var vals = {"7925181":["68113227"],"68113227":["7925181"]}; var temp = []; for (var i = 0; i < keys.length; i++) { temp[keys[i]] = vals[keys[i]]; } //alert(JSON.stringify(vals).length); alert(JSON.stringify(temp).le ...

Updating the list in React upon form submission without requiring a full page refresh

Currently, I have a list of data being displayed with a specific sort order in the textbox. Users are able to modify the order and upon clicking submit, the changes are saved in the database. The updated list will then be displayed in the new order upon pa ...

Which JavaScript framework tackles the challenges of managing asynchronous flow, callbacks, and closures?

I have a strong aversion to JavaScript. I find it to be quite messy and disorganized as a language. However, I recognize that my lack of proficiency in coding with it may contribute to this perception. These past few days have been incredibly frustrating ...

Steps for generating a div, link, and image that links to another image using Javascript

Hey there, I have a cool picture to share with you! <img src="cards.png" id="img"> <!--CARD PICTURE--> Check out what I want to do with it: <div class="container_img"> <img src="cards.png" id="img"> <!--CARD PICTURE--> ...

Exploring ways to personalize the parsing of url query parameters in express.js

When using req.query, the hash of query parameters is returned. Additionally, if a parameter consists of a JSON object, it is automatically parsed into JSON format, which is quite impressive. However, I am curious about customizing this parsing process. I ...

Leaflet Alert: The number of child elements is not the same as the total number of markers

Encountering a problem with Leaflet clustering using v-marker-cluster. Within the icon createFunction of the cluster, the className of children is used to determine the cluster style. Here is a snippet of this function : const childCount = marker_cluster._ ...

React DataGrid fails to refresh when state changes

Currently, I am in the process of developing a link tree using the Datagrid Component provided by MaterialUI. While data can be successfully displayed, I encounter an issue when attempting to add a new entry. The problem lies in the fact that despite cha ...

Apply a specific CSS class to a division depending on the currently active cookie

I have implemented cookies on specific pages using https://github.com/carhartl/jquery-cookie. Could someone guide me on how to apply a CSS class to an ID (e.g., adding class .red to #mouse if the cookie named "socks" is active)? For example: If there is ...

The Vue v-on:click event listener seems to be unresponsive when applied to a

I've been attempting to utilize the on-click directive within a component, but for some reason, it doesn't seem to be functioning. Whenever I click on the component, nothing happens, even though I should see 'test clicked' in the consol ...

Exploring the bind() method in the latest version of jQuery,

After upgrading my JQuery version, one of the plugins I was using stopped working. Despite trying to use the migrate plugin and changing all instances of bind() to on(), I still couldn't get it to work properly. The plugin in question is jQuery Paral ...

Identifying a specific item within an array

Can someone guide me on how to manipulate a specific object within an array of objects? For example: var myArray = [ {id: 1}, {id: 2}, {id: 3}, {id: 4} ] // Initial state with the 'number' set as an array state = { number: [] } // A functio ...

Implementing Entity addition to a Data Source post initialization in TypeORM

The original entity is defined as shown below: import { Entity, PrimaryGeneratedColumn} from "typeorm" @Entity() export class Product { @PrimaryGeneratedColumn() id: number The DataSource is initialized with the following code: import ...

What is causing this issue that is preventing me from async rendering Vue components?

I am new to working with Vue and I am attempting to lazy load a Component. However, I encountered an error that seems to be related to a syntax issue. Below is the code snippet: <template> <div class="container"> <h1>Asy ...