🐙

Cloudflare + NuxtでCronを実行する方法

2025/02/04に公開

最近、Cloudflareでの開発が増えてきました。私はVueが大好きで、Vue Fes Japanにも参加するほどのNuxtファンです。しかし、まだNuxtを活用したCloudflareでの開発に関する情報が少ない印象です。そこで今回は、Cloudflare CronをNuxtにデプロイしたワーカーで利用する方法を調べ、まとめてみました。

忙しい方向けにgithubにソースコードも載せてます。

https://github.com/EnjoyKojima/nuxt-cron

NuxtをWorkersにデプロイする

Cloudflare WorkersのフレームワークガイドのページにNuxtのプロジェクトを作成するコマンドが記載されているので実行します。

pnpm create cloudflare@latest nuxt-cron --framework=nuxt --experimental

デプロイするか聞かれるのでデプロイしちゃいます。

├ Do you want to deploy your application?
│ yes deploy via `pnpm run deploy`

デプロイされると自動でブラウザが開かれてNuxtの初期画面が表示されます。
たったの1コマンドでプロジェクトがデプロイ出来て最高ですね!

クーロンの使用を設定

nuxt.config.tsのnitroの設定を追加します。

nuxt.config.ts
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  compatibilityDate: '2024-11-01',
  devtools: { enabled: true },

  nitro: {
    preset: "cloudflare_module",
    experimental: {
      tasks: true, // 追加
    },
  },

  modules: ["nitro-cloudflare-dev"]
})

タスクを定義

クーロンが実行された日時をログに出力する簡単なタスクを定義します。
/server/tasks配下にファイルを置くことでクーロンのタスクを定義できます。

/server/tasks/now.ts
export default defineTask({
  meta: {
    name: "now",
    description: "Simple task to check the current time",
  },
  run({ payload, context }) {
    console.log("Current time:", new Date().toISOString());
  },
});

ディレクトリ構造をネストさせる場合には、nameをhello:worldにすると/server/hello/world.tsにタスクを定義することができます。

/server/tasks/hello/world.ts
export default defineTask({
  meta: {
    name: "hello:world",
  },
  run({ payload, context }) {
    return { message: "Hello World!" };
  },
});

実行タイミングを設定

クーロンの使用を設定するのと同様にnuxt.config.tsにスケジュールを定義します。毎分実行されるように設定しました。

これだけだとクーロンが実行されないので次でwrangler.jsonの設定を追加します。

nuxt.config.ts
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  compatibilityDate: '2024-11-01',
  devtools: { enabled: true },

  nitro: {
    preset: "cloudflare_module",
    experimental: {
      tasks: true,
    },
    scheduledTasks: {
      '* * * * *': ['now'] // 追加
    }
  },

  modules: ["nitro-cloudflare-dev"]
})

wrangler.jsoncを設定

Wranglerのクーロンスケジュールを設定します。これを設定することでデプロイした時にクーロンの設定がワーカーに反映されます。

wrangler.jsonc
{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "nuxt-cron",
  "main": "./.output/server/index.mjs",
  "compatibility_date": "2025-01-29",
  "assets": {
    "binding": "ASSETS",
    "directory": "./.output/public/"
  },
  "observability": {
    "enabled": true
  },

  "triggers": {
    "crons": [
      "* * * * *" // 追加
    ]
  }
}

動作確認

クーロン自体はここまでの設定で動作するのでデプロイして確認してみましょう。
通常のログの反映には少しラグがあるのでライブ機能を使います。

pnpm run deploy

少し待っていると、毎分ログが出力されているのが確認できました!

まとめ

イメージに反してかなり簡単にクーロンを実装できたと思います。実は今回の内容はNuxtではなくNitroのドキュメントを参考に作っています。Nuxtのドキュメントに書いていない内容でも、NuxtのサーバーエンジンになるNitroや、HTTPフレームワークのh3など、Nuxtを構成する要素のドキュメントを調べることで実現方法が見つかることが多いです。

困った時こそ、ぜひNuxt以外のドキュメントも読んでみてください!

参考

今回の記事の詳しい内容については参考リンクを貼っておくので気になる方はチェックしてみてね!

https://nuxt.com/docs/guide/concepts/server-engine

https://nitro.build/guide/tasks

Discussion