This is a basic TypeScript template for Mastro when using Cloudflare Workers to run your server code on-demand on the edge. If you only need to generate a static site for the Cloudflare CDN, you don't need this template.
Click the green Use this template button in the top right to create your own copy of this repository. Then clone the Code to your computer.
If you have multiple projects on your computer that require different Node.js versions, you should install a tool to manage those version for you; for example Volta (see pnpm Support).
Mastro requires Node.js >=24, and JSR recommends to use pnpm.
The first time, you need to:
pnpm install
After that, to start the Cloudflare Workers runtime using Wrangler:
pnpm run dev
Then open http://localhost:8787 in your browser.
If you check out the dev script in the package.json file, you'll see that it first runs pnpm run generate (which creates the generated folder with the static assets using --only-pregenerate) and then runs wrangler dev (which bundles all your code using esbuild, and then runs it in the workerd JavaScript runtime).
This mirrors how Cloudflare works in production: when a request comes in, it fill first try to find a static asset (what's in the generated folder) and serve that directly from the CDN. Only if there's no match, it will spin up the Worker and run your server code (what's in dist/server.js if you've run pnpm run build – this can be useful for debugging, but otherwise isn't required).
For Cloudflare, the above build step is recommended. However, for local development, you can use Deno to spin up a server that reloads more quickly than Wrangler:
deno task start
Then open http://localhost:8000 in your browser.
However, be aware that the Deno and workerd JavaScript runtimes don't support exactly the same features. Thus to get the exact same behaviour as on production, you should use pnpm run dev.
Note that currently, Mastro on Cloudflare Workers only works with the programmatic router, not the file-based router which is the default when using Mastro with Deno, Bun or plain Node.js.
To see how Mastro works, follow the guide.
To make sure you're on the latest Mastro version:
pnpm update @mastrojs/mastro --latest
To deploy to production directly from your commandline, run:
pnpm run deploy
Alternatively, to set up automatic deployment from your GitHub repo, go to the Cloudflare Dashboard. On the Build > Workers & Pages page, click Create application, choose Continue with GitHub, and follow the instructions. Make sure you've set:
Build command: pnpm run build
Deploy command: npx wrangler deploy
And that the Node.js version in your .node-version file is the same as in the engines field of your package.json.