Cloudflare Workers
Cloudflare Workers enable you to deploy serverless code across the globe. The Workers platform also comes with additional runtime APIs, such as Durable Objects & KV that allow you to build powerful applications. See the API documentation for more information.
Getting Started
Before getting started, you need to install the Cloudflare wrangler
CLI globally.
Next, either use the edge
CLI command or setup manually:
Create a new project using the edge
CLI command:
edge new cloudflare_workers new_project
This command will create a new barebones template in the current directory. Once complete, install the dependencies:
dart pub get
Open the lib/main.dart
file to view the minimal HTTP request fetch handler.
Each incoming request to your edge function will be passed to the fetch
handler, which is expected to return a Response
instance. The fetch
handler provides a Request
instance which contains useful information about the incoming request, such as the method, URL, headers, body and more.
Alongside the Request
instance, you are also provided an Environment
instance, enables you to access service bindings (e.g. Durable Objects). Additionally the ExecutionContext
argument enables you to perform actions such as defining functions which can run after a response has been sent to the client.
Local development
To run your application locally, use the wrangler dev --local
command from the root of your project:
wrangler dev --local
You can remove the
--local
flag to run your code directly on the Cloudflare Worker environment. This is useful for testing the production environment locally, however it will take longer to start up as your code is uploaded.
This command will start a development server where you can access your application, by default at http://127.0.0.1:8787
. Any changes you make to your Dart code will trigger a hot-reload.
Deployment
To deploy your application to Cloudflare Workers, first remove the --dev
flag from the wrangler.toml
file:
[build]
- command = "dart run edge build cloudflare --dev"
+ command = "dart run edge build cloudflare"
Removing the --dev
flag will ensure that your application is built in production mode, which will result in a smaller bundle size and optimized code.
Please upvote this feature request to help remove this manual step!
Next, run the wrangler publish
command from the root of your project:
wrangler publish