std9.jp

nuxt3 で ulid を使うと『secure crypto unusable, insecure Math.random not allowed』エラーが発生するときの対処方法

nuxt3 (3.0.0-rc.6) でセットアップしたプロジェクトに ulid:2.3.0 パッケージをインストールして使用すると、`secure crypto unusable, insecure Math.random not allowed` エラーが表示される

目次 (3)
  1. 現象
  2. 再現コード
  3. 原因と対策

現象

nuxt3 (3.0.0-rc.6) でセットアップしたプロジェクトに ulid

.3.0 パッケージをインストールして使用すると、secure crypto unusable, insecure Math.random not allowed エラーが表示される。

以下、コンソールに表示された詳細なエラー。

[h3] [unhandled] H3Error: secure crypto unusable, insecure Math.random not allowed
    at createError (…/nuxt3-ulid-example/node_modules/h3/dist/index.mjs:196:15)
    at Server.nodeHandler (…/nuxt3-ulid-example/node_modules/h3/dist/index.mjs:386:21) {
  statusCode: 500,
  fatal: false,
  unhandled: true,
  statusMessage: 'Internal Server Error'
}

再現コード

{
  "dependencies": {
    "ulid": "^2.3.0"
  },
  "devDependencies": {
    "nuxt": "^3.0.0-rc.6"
  }
}
<script lang="ts" setup>
// ulidパッケージを静的インポート
import { ulid } from "ulid";

// ボタンを押した際のクリックイベント
async function onClick() {
  // ulidを出力する
  console.log(ulid());
}
</script>

<template>
  <div>
    <!-- テスト用のボタン -->
    <button @click="onClick">button1</button>
  </div>
</template>

原因と対策

詳細な調査をしていないので原因は不明です(/ω\) 暫定対策としては ulid を静的インポートから動的インポートにすることで、ひとまず回避できます。

<script lang="ts" setup>
// ボタンを押した際のクリックイベント
async function onClick() {
  // 動的にulidをインポートする
  const { ulid } = await import(`ulid`);

  // ulidを出力する
  console.log(ulid());
}
</script>

おわり。