Importing bcrypt into mongodb function not working

I am trying to create a https endpoint that uses bcrypt to compare the users password with the database password. I have downloaded bcrypt with version 5.1.0 through the atlas ui and it shows up on the dependencies. However, when i try to import the library i get an error.
I use this to import bcrypt

const bcrypt = require('bcrypt');

and i get this error

> error: 
failed to execute source for 'node_modules/bcrypt/bcrypt.js': TypeError: Value is not an object: undefined
	at node_modules/@mapbox/node-pre-gyp/lib/pre-binding.js:29:18(4)
	at node_modules/bcrypt/bcrypt.js:15:35(37)
1 Like

Have you found a solution for it, I am facing the same issue @Tamothee_N_A

I have found a solution.

This error occurs because the bcrypt package requires native dependencies that must be compiled specifically for the environment where the code is running. Since MongoDB Realm runs in a serverless environment, it does not provide access to the native dependencies required by bcrypt, causing the error you are seeing.

To use bcrypt in a MongoDB Realm function, you will need to find an alternative implementation that does not rely on native dependencies. One such implementation is bcryptjs, which is a pure JavaScript implementation of the bcrypt algorithm and does not require any native dependencies.

To use bcryptjs, you can simply replace the bcrypt import statement in your code with:

const bcrypt = require('bcryptjs')

this should solve the issue!

(Shout out to ChatGPT for the solution)

using bcryptjs makes my function timeout or fail with 504 error

@Sangat_Shah - Mind sharing how you used bcryptjs? I’m getting the same result as @louis_Muriuki: the function hangs and eventually times out. My implementation looks like this:

const bcrypt = require("bcryptjs");
const hashedPassword = await bcrypt.hash("blahblah", 12);