Unhandled rejection TypeError: Cannot read property 'username' of null

I’m using NodeJS, PassportJS, MySQL, and Sequalize(ORM for MySQL). This code is from my Passport.JS file. When a user registers on my website if the username or email is taken I will return an error. If both username, email can’t be found in database a new create account will be created.

The error I’m getting when I register on my website is…

Unhandled rejection TypeError: Cannot read property ‘username’ of null
at null. (/home/ubuntu/workspace/Authentication.1/config/passport/passport.js:50:16)
at tryCatcher (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:693:18)
at Async._drainQueue (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues [as _onImmediate] (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/async.js:17:14)

        // SELECT * FROM users WHERE username = username || email = ... 
        where: {
            $or: [{username: username}, {email: req.body.email}]

    // GETTING ERROR HERE. If username is already in database
    if(user.username !== null && user.username == req.body.username) {
      return done(null, false, console.log("USER TAKEN"),{message : 'That username is already taken'} );

    // If email is already in database return err.
    else if(user.email !== null && user.email == req.body.email) {
      return done(null, false, console.log("EMAIL TAKEN"),{message : 'That email is already taken'} );

    else [code for create new account]...

Your issue is from the first check in your if statement. In the event the user isn’t found, user will be null and the statement user.username !== null will result in the error message you are getting.

You should perform a null check on the object as a whole, not the property.
if(user!== null && user.username == req.body.username){…}