Working with MongoDB Realm tutorial for Node js gives HTTP/1.1 401 Unauthorized error

I have been following the NodeJS MongoDB Realm Quick Start tutorial. The connection is made with the MongoDB Atlas and then immediately the app quits with

Logged in with user 5ff8c70ddd74f48bbe641a4c
Connection[1]: Session[1]: client_reset_config = false, Realm exists = true, async open = false, client reset = false
Connection[1]: Connected to endpoint '"remote-ip-here"' (from '192.168.1.212:60173')
ERROR: Connection[1]: Websocket: Expected HTTP response 101 Switching Protocols, but received:
HTTP/1.1 401 Unauthorized

I have enabled Realm Sync and enabled development mode and anonymous access.

My code is pretty much the same as mentioned in the tutorial:

export const realmApp = new Realm.App({ id: 'my-app-id' });
var realm: Realm;

async function run() {
  const credentials = Realm.Credentials.anonymous();
  await realmApp.logIn(credentials);
  console.log('Logged in with user', realmApp.currentUser?.id);
  realm = await Realm.open({
    schema: [TaskSchema],
    sync: {
      user: realmApp.currentUser as Realm.User,
      partitionValue: 'myPartition',
    },
  });
}

run().catch((err) => {
  console.error('Failed to open realm:', err);
});

Any ideas?

Sheikh,

Make sure that you have a sufficient Node.js version (> 10), see

Then clear your local MongoDB Realm cache

rm -rf mongodb-realm

And try again.

Richard Krueger

1 Like

Hi Richard thank you for the reply. I am using NodeJS version 12.20.1 so I do not think that is causing issues. I have an IoT app that collects data from some devices all day long. I am now using api keys in my app. The app does not error out as before immediately when the app is launched. But after some hours it crashes with the same error.

Connection[1]: Connected to endpoint '<remote-ip-here>:443' (from '192.168.8.105:41332')
ERROR: Connection[1]: Websocket: Expected HTTP response 101 Switching Protocols, but received:
HTTP/1.1 401 Unauthorized

I have tried removing the mongodb-realm folder twice now, but still the same issue occurs. Any further suggestions as to what might be actually happening here?

I had encountered the same issue a while ago. I got no help from the online community and had to come up with my own DIY solution. The error code 401 means the user is unauthorized and must re-login to be authorized. So I implemented a code while opening the app if the device is connected to the internet, log out the user, and re-login. To find out internet connectivity, I installed is-internet-available package and used isInternetAvailable() function.

isInternetAvailable().then(async(internetConnected = console.log)=>{
        //gives true when internet available else gives false
        console.log("internet connected ", internetConnected) 
        if(internetConnected){

            //if old user exists, then logout
            if(app.currentUser){
                //logout first
                app.currentUser.logOut()

                //and then login
                user = await app.logIn(credentials).catch(err=>{
                    console.log("err")
                })
            }
            else{
                //login directly if previous user doesn't exist
                user = await app.logIn(credentials).catch(err=>{
                    console.log("err")
                })
            }
        }
    }).catch(err=>{
        console.log(err)
    })

Now I am facing a situation where if the app is idle for a little longer period of time, it gives the same error. If you also face the problem you can make this a function and call it in a specific period using the setTimeout() function.

1 Like