title: I want to execute a function upon the start of my node.js express server and execute an auth module, is this the correct way?
body: <p>I am currently building my server to execute an authentication function on startup using server/app listener. I am trying to use an external function in my controller file to do this, my server code below:</p>
  
  <pre><code>//Start listener on the port
  app.listen(port, () =&gt; {
      console.log(`Server is listening to port ${port}... (http\://localhost\:3000)`);
  });
  
  //Start Authentication when server starts
  app.on('listening', () =&gt; {
      console.log('Running Authentication...')
      auth.main()
  });
  </code></pre>
  
  <p>And am using these async modules in my auth, is this the correct way of executing a start up function? For the data I want to send back, should I store them in global variables and then use 'res.send' at the end of my function? and is there any way I could improve my code?</p>
  
  <pre><code>const main = (req, res) =&gt; {
  //Asynchronous Waterfall Call of 'Getting Access Tokens' (Stages 1-3)
  async.waterfall([
      getCookieData,
      getAuthCode,
      getAccessToken
  ], (err, result) =&gt; {
      if (err) {
          alert('Something is wrong!');
      }
      return alert('Done!');
  });
  
  //STAGE 1 - USE CUSTOMER DETAILS TO RETRIEVE COOKIE AND CSRF SESSION DATA
  getCookieData = async (callback) =&gt; {
          //If the paramter test passes then proceed
          var options = {
              //Type of HTTP request
              method: 'POST',
              //URI String
              uri: authURL,
              //HTTP Query Strings
              qs: {
                  'client_id': clientID
              },
              //HTTP Headers
              headers: {
                  'cache-control': 'no-cache',
                  'Accept': 'application/json',
                  'Host': host,
                  'Content-Type': 'application/json'
              },
              //HTTP Body
              body: {
                  'username': username,
                  'password': password
              },
              json: true // Automatically stringifies the body to JSON
              //resolveWithFullResponse: true // Get the full response instead of just the body
              //simple: false // Get a rejection only if the request failed for technical reasons
          };
          console.log(`Beginning HTTP POST Request to ${authURL}...`);
  
          //await literally makes JavaScript wait until the promise settles, and then go on with the result.
          await rp(options)
          .then((parsedBody) =&gt; {
              //POST Succeeded...
              Console.log('Successful HTTP POST!');
              try {
                  let csrf = response.body('csrftoken'),
                      ses = response.body('session'),
                      sesk = `session=${ses}`;
              } catch (e) {
                  console.log(`STAGE 1 - Error occurred when assigning url variables. Error: ${e}`);
                  console.error('STAGE 1 - Error occurred when assigning url variables. Error:', e);
                  callback(`STAGE 1 - Error occurred when assigning url variables. Error: ${e}`)
              }
              console.log(`Successful grab of the cookie: ${ses} and csrf token: ${csrf}. Getting authorisation code now!`);
              //Asynchronous callback for the next function - return = defensive architecture 
              return callback(null, authCodeURL, customerID, clientID, csrf, sesk);
          })
          .catch((err) =&gt; {
              if (res.statusCode == 400) {
                  console.log(`Error Message: ${res.body.message}. Status: ${res.body.status}`);
                  console.error('Error Message:', res.body.message, 'Status:', res.body.status);
                  callback(`Error Message: ${res.body.message}. Status: ${res.body.status}`);
              } else if (res.statusCode == 401) {
                  console.log(`Error Message: ${res.body.message}. Status: ${res.body.status}`);
                  console.error('Error Message:', res.body.message, 'Status:', res.body.status);
                  callback(`Error Message: ${res.body.message}. Status: ${res.body.status}`);
              } else {
                  console.log(`Failed to retrieve the cookie data! Error: ${error}`);
                  console.error('Failed to retrieve the cookie data! Error:', error);
                  callback(`Failed to retrieve the cookie data! Error: ${error}`);
              }
          });
      },
  
      //STAGE 2 - USE COOKIES AND CSRF TOKEN TO GET AUTH CODE
      //Is the word async needed? it is not asyncchronous but sequential
      getAuthCode = async (authCodeURL, customerID, clientID, csrf, sesk, callback) =&gt; {
              //If successful, proceed:
              var options = {
                  method: 'POST',
                  uri: authCodeURL,
                  qs: {
                      'client_id': clientID,
                      'response_type': 'code',
                      'scope': 'all'
                  },
                  headers: {
                      'X-CSRF-TOKEN': csrf,
                      'Accept': 'application/json',
                      'Cookie': sesk,
                      'Content-Type': 'application/json'
                  },
                  body: {
                      'customer_id': customerID
                  },
                  json: true // Automatically stringifies the body to JSON
              };
              console.log(`Beginning HTTP POST Request to ${authCodeURL}...`);
  
              //await literally makes JavaScript wait until the promise settles, and then go on with the result.
              await rp(options)
                  .then((parsedBody) =&gt; {
                      //POST Succeeded...
                      Console.log('Successful HTTP POST!');
                      try {
                          let authCode = response.body.JSON('auth_code'),
                              swapurl = `https://${host}${url3}`;
                      } catch (e) {
                          console.log(`STAGE 2 - Error occurred when assigning url variables. Error: ${e}`);
                          console.error('STAGE 2 - Error occurred when assigning url variables. Error:', e);
                          callback(`STAGE 2 - Error occurred when assigning url variables. Error: ${e}`);
                      }
                      console.log(`The authorisation Code is ${authcode}. Getting Access Token now!`);
                      //Asynchronous callback for the next function - return = defensive architecture
                      return callback(null, swapURL, clientID, clientSecret, authCode);
                  })
                  .catch((err) =&gt; {
                      if (res.statusCode == 400) {
                          console.log(`Error Message: ${res.body.message}. Extra: ${res.body.extra}`);
                          console.error('Error Message:', res.body.message, 'Extra:', res.body.extra);
                          callback(`Error Message: ${res.body.message}. Extra: ${res.body.extra}`);
                      } else {
                          console.log(`Failed to retrieve the authorisation code! Error: ${error}`);
                          console.error('Failed to retrieve the authorisation code! Error: ', error);
                          callback(`Failed to retrieve the authorisation code! Error: ${error}`);
                      }
                  });
          },
  
          //STAGE 3 - USE AUTH CODE TO GET ACCESS TOKEN
          //ASYNC NEEDED?
          getAccessToken = async (swapURL, clientID, clientSecret, authCode, callback) =&gt; {
              //If successful, proceed:
              var options = {
                  method: 'POST',
                  uri: swapURL,
                  qs: {
                      'client_id': clientID,
                      'grant_type': 'authorization_code',
                      'client_secret': clientSecret,
                      'code': authCode
                  },
                  json: true // Automatically stringifies the body to JSON
              };
              console.log(`Beginning HTTP POST Request to ${swapURL}...`);
  
              //await literally makes JavaScript wait until the promise settles, and then go on with the result.
              await rp(options)
                  .then((parsedBody) =&gt; {
                      //POST Succeeded...
                      Console.log('Successful HTTP POST!');
                      try {
                          let accessToken = response.body('access_token'),
                              refreshToken = response.body('refresh_token');
                      } catch (e) {
                          console.log(`STAGE 3 - Error occurred when assigning url variables. Error: ${e}`);
                          console.error('STAGE 3 - Error occurred when assigning url variables. Error:', e);
                          callback(`STAGE 3 - Error occurred when assigning url variables. Error: ${e}`);
                      }
                      console.log(`The access Token is ${accessToken} and the refreshToken which is ${refreshToken}! These are only valid for 2 hours!`);
                      //Asynchronous callback for the waterfall - return = defensive architecture
                      return callback(null, 'done');
                  })
                  .catch((err) =&gt; {
                      console.log(`Failed to retrieve the access/refresh Token! Error: ${error}`);
                      console.error('Failed to retrieve the access/refresh Token! Error:', error);
                      callback(`Failed to retrieve the access/refresh Token! Error: ${error}`);
                  });
          }
  }
  </code></pre>