Q:

How to generate hash as a global variable using bcrypt and nodeJS

I have a react component for signing into a single password web app. I have an onChange={this.setState({password: event.target.value}} prop on the input to update the password. Then when the user clicks the submit button it calls this function: 
 onSubmitSignIn = () => {
  fetch('http://localhost:3000/signin', {
    method: 'post',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
      password: this.state.password
    })
  })
    .then(response => response.json())
    .then(response => {
      if (response === 'true') {
        this.props.onRouteChange('home');
      }
    })
}

Here is what my server looks like: 
const express = require('express')
const app = express()
const bcrypt = require('bcrypt-nodejs')
var bodyParser = require('body-parser')
var cors = require('cors')

app.use(cors());
app.use(bodyParser.json());
app.get('/', (req, res) => res.send('Hello World!'))

bcrypt.hash("password", null, null, function(err, hash) {
console.log(hash)
});

app.post('/signin', (req, res) => {
var a = JSON.parse(req.body);
  bcrypt.compare(a.password, hashNew, function(err, res) {
if (hash === hashNew) {
    res.send(true);
} else {
    res.send(false);
}
});
})

app.listen(3000, () => console.log('App listening on port 3000!'))

I am trying to make a hash using bcrypt as a global variable to compare to the hash that is created for the password the user has typed on submit. Thanks for any and all help. Please let me know if there is anything I need to clarify anything.

A:

You can't generate hash as a global variable in bcrypt.hash method since this is an asynchronous method. but bcrypt-nodejs has an hashSync method that can be used to generate the hash as a global variable. 
so your code become this:
var hash = bcrypt.hashSync("password", null);

app.post('/signin', (req, res) => {
var a = JSON.parse(req.body);
  bcrypt.compare(a.password, hashNew, function(err, res) {
if (hash === hashNew) {
    res.send(true);
} else {
    res.send(false);
}
});
})

note that using synchronous functions for hashing impacts the performance and is not recommended.

