Home > front end >  I am trying to hash admin password to save into database using bcrypt in nextjs but receiving error
I am trying to hash admin password to save into database using bcrypt in nextjs but receiving error

Time:10-03

so everything is fine if I do not import bcrypt but once I do it I receive the following error in the terminal. I have searched a lot with no luck at this point I am clueless as what to do. any help would be greatly appreciated.

error - ./node_modules/@mapbox/node-pre-gyp/lib/clean.js:8:0
Module not found: Can't resolve 'fs'

Import trace for requested module:
./node_modules/@mapbox/node-pre-gyp/lib/ sync ^\.\/.*$
./node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js
./node_modules/bcrypt/bcrypt.js
./pages/adminlogin.js

https://nextjs.org/docs/messages/module-not-found

here is my adminlogin.js file

import bcrypt from "bcrypt";
export default function AdminLogin() {
  const saltRounds = 10;
  const createAdminData = async (e) => {
    const usernameInfo = e.target.username.value;
    console.log(usernameInfo);
    const passwordInfo = e.target.password.value;
    const salt = bcrypt.genSalt(saltRounds);
    const hashedPassword = bcrypt.hash(passwordInfo, salt);
    const res = await fetch("api/database/addadmindata", {
      method: "POST",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify({
        username: usernameInfo,
        password: hashedPassword,
      }),
    });
    const result = await res.json();
    router.reload();
  };

 

CodePudding user response:

That error happens because in client-side somewhere in your app you are using fs module. you can use fs module only on the server side, either getserverSideProps or apis directory.

When you import "fs" and use it in server-side, next.js will see that you use it in server-side so it won't add that import into the client bundle

probably that @mapbox is not a client library but you are using it in client-side

You probably have mongoose userSchema. in that schema file:

// hashing password before saving user
// for findAndUpdate(), pre save hook is not triggered
userSchema.pre("save", async function (next) {
  // if password did not get changed, next()
  if (!this.isModified("password")) {
    next();
  }
  this.password = await bcrypt.hash(this.password, 10);
});

Now you do not need to do hashing on the server. you extract the data from req.body, you contract the user with the raw password, then run

await user.save()

so before "user" is saved, raw password will be hashed automatically and hashed password will be saved to the database

  • Related