1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript】Cloudflare Workers環境でMongoDB Atlasにアクセスできるようにする

1
Posted at

概要

Cloudflare Workers環境でもMongoDBにアクセスしたいなと思い、とりあえずローカル環境で実現できるか確認したメモ書きです。接続先はMongoDB Atlasでテスト用に作成したDBとします。

前提

  • 使用したwranglerのバージョンは4.92.0です。
  • 使用したmongodbのバージョンは7.2.0です。

手順など

以下の手順にて、mongodbのライブラリを使用しMongoDB Atlasにクエリ発行できることを確認しました。

1. patch-packageのインストール

そのままmongodbのライブラリをインストールしただけでは、おそらくサーバーが起動しません(2026年5月時点だと)。Error: Calling require for "punycode/" in an environment that doesn't expose the require functionのようなエラーが出ると思います。
Cloudflare + MongoDB: How to fix 'Error: Dynamic require of "punycode/" is not supported'の記事で紹介されている通り、patch-packageの対応が必要なようです。記事にも書かれていますが、以下のコマンドで取り急ぎpatch-packageをインストールします。

npm install patch-package
npm pkg set scripts.postinstall="patch-package && npm run cf-typegen"
sed -i '' 's/require("punycode\/")/require("punycode")/g' node_modules/tr46/index.js
npx patch-package tr46
npm install

2. compatibility_flagsの設定

Cloudflare Workers and MongoDBの記事で紹介されている通り、wranglerのconfigファイルにて、compatibility_flagsnodejs_compatを設定します。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?