👻

bcrypt (npm) パッケージのimportエラー対策

2025/01/11に公開

パスワードハッシュ化などで bcrypt npm モジュールを利用する際に、何らかの理由によって下記のようなエラーが発生するケースが有る。

treasure-app1_3  |  GET / 404 in 1ms
treasure-app1_3  |  ⚠ ./node_modules/@mapbox/node-pre-gyp/lib/util/compile.js
treasure-app1_3  | Module not found: Can't resolve 'node-gyp' in '/app/node_modules/@mapbox/node-pre-gyp/lib/util'
treasure-app1_3  |
treasure-app1_3  | Import trace for requested module:
treasure-app1_3  | ./node_modules/@mapbox/node-pre-gyp/lib/util/compile.js
treasure-app1_3  | ./node_modules/@mapbox/node-pre-gyp/lib/ sync ^\.\/.*$
treasure-app1_3  | ./node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js
treasure-app1_3  | ./node_modules/bcrypt/bcrypt.js
treasure-app1_3  | ./lib/next-auth/authOptions.ts

その場合は bcrypt の代わりに bcryptjs を利用したほうがエラーが解決しやすい

$ npm uninstall bcrypt
$ npm install bcryptjs

ただし利用法が変わるので注意

// import bcrypt from 'bcrypt';
import bcrypt from 'bcryptjs'; // 修正後

// パスワード比較
// const isCorrectPassword = await bcrypt.compare(credentials.password, user.hashedPassword); // 修正前
const isCorrectPassword = bcrypt.compareSync(credentials.password, user.hashedPassword); // 修正後

Discussion