title: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:371:5)
body: <p>I am getting this error after a sign-in has occurred. The code works as it should but after the user is returned I get this error.</p>
  <pre><code>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
      at new NodeError (node:internal/errors:371:5)
      at ServerResponse.setHeader (node:_http_outgoing:576:11)
      at ServerResponse.header (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\express\lib\response.js:771:10)
      at ServerResponse.location (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\express\lib\response.js:888:15)
      at ServerResponse.redirect (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\express\lib\response.js:926:18)
      at allFailed (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\passport\lib\middleware\authenticate.js:139:20)
      at attempt (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\passport\lib\middleware\authenticate.js:174:28)
      at Strategy.strategy.fail (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\passport\lib\middleware\authenticate.js:296:9)
      at verified (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\passport-local\lib\strategy.js:82:30)
  
      at C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\src\config\passport.js:17:32
  </code></pre>
  <p>The code</p>
  <pre><code>const usersRepo = require('../repositories/usersRepo');
  const { Strategy } = require('passport-local');
  
  function initialize(passport) {
  
      passport.use('local.signIn', new Strategy({
          usernameField: 'username',
          passwordField: 'password'
      }, (username, password, done) =&gt; {
          (async function ValidateUser() {
              try {
                  const users = await usersRepo.getData({ username: username });
                  users.forEach((user) =&gt; {
                      if (user.username === username &amp;&amp; user.password === password) {
                          return done(null, user)
                      } else {
                          return done(null, false, { message: &quot;user not found&quot; })
                      }
                  })
  
              } catch (error) {
                  done(error, false)
              }
  
          }())
      }))
  
      passport.serializeUser((user, done) =&gt; {
          done(null, user);
      });
      passport.deserializeUser((user, done) =&gt; {
          done(null, user);
      });
  }
  module.exports = initialize
  </code></pre>