Posted on Leave a comment

How to hash passwords in Next.js for logins

Hashing passwords is important for security, so that the developer nor a hacker can steal a password just by looking at it.

To hash a password, we need to install the library named bcrypt.

bcrypt will allow us to hash passwords as well as compare passwords.

To start, we will hash a password. So, we will create a file under the lib folder for easy use in api endpoints. Then, add the default function.

Note: Bcrypt uses async functions, so one needs to add the await command when using these functions in their api.

Next, we will add the functionality to this function.

Above, the hash function accepts a string(in my case a password) and a int for salt rounds. Salt rounds makes the hash more secure, but doubles the time to encrypt by a factor of 2. In this case, it’ll take 10² or 1024 rounds to encrypt each password.

Now, we need to create a new file and add functionality to it.

Here, the compare function accepts a unhash string and a hashed string and then returns the function from the function.

That’s it! Now we can use these functions in our api for password checking and creation.

Leave a Reply

Your email address will not be published.