Creating A Cloudflare Worker Using Rust For Fetching Resources

Edward Fitz Abucay
5 min readDec 12, 2020

--

Photo by Henry Dick on Unsplash

Have you ever worked on Web Assembly project? Actually, now is a good time, first because its already supported by your browser from Chromium based (e.g. Edge, Brave, Google Chrome) to Firefox and its enabled by default since 2019. Plus you can use your favorite language (technically not all) to develop web assembly.

In this quick tutorial we will be using Rust, not the game though.

Ferris, the Rust language mascot.

Ferris saying hello 👋.
Come on, let’s jump in! 💪

Prerequisites

First of all, you must have a Cloudflare account. Second, the Rust tool chain installed in your computer and I also assumed you are currently running Windows 10 or a Linux distro with proper environment set.

If you don’t have Rust, go to this link in order to install it. And for the Cloudflare account, basically just use the free tier which gives you 100,000 worker calls per day and a free Key-Value (KV) storage.

So where do we start?

The first thing we need to do, is to install wrangler which is a command-line tool specifically developed by Cloudflare to complement the deployment and development of Workers. Install the wrangler tool using the cargo command utility.

Fig. 1: Install the wrangler tool

The command above will first fetch the source from crates.io and compile it as binary. The command will also automatically install it on your ~/.cargo/bin directory.

💡: Cloudflare Worker is similar to AWS Lambda and Azure Cloud Function. They're both under the serverless computing category.

After the installation of wrangler, you need to authenticate using your Cloudflare account API key, on which you can get on the user settings panel.

Fig. 2: Authenticating wrangler session

If all works well, the next thing we need to do is to generate the cargo project using the wrangler command line. Execute the code below to generate a cargo project using the Rust WASM worker template:

Fig. 3: Generate a cargo project using template

After that, go inside the folder named worker_fetch_demo to edit the file cargo.toml . Add the following crate dependencies.

Fig. 4: Add required crate dependencies

The wasm-bindgen package is the most important, as that is what links the package to call to JavaScript scopes and other web and web assembly related functionalities. You also need to add the web-sys package as that will provide basic mapping and calls to JavaScript functions.

You’ll be able to get to know what the other package are for, if you’ve already read the Rust Programming Language Book.

Fig. 5: Add the web-sys dependencies with custom features

After adding those crate dependencies it will automatically be fetched on build or upon call to cargo update .

Next thing we modify is the file worker > worker.js . This file serves as the main entry-point of our program that will call our compiled wasm files. We need to add minor modification to it, specifically capturing request and serving the wasm response as JSON.

Fig. 6: Modify the handle request to output our fetch resource data

We move on now to the rust files. 🦀

On the file src > lib.rs add the following code, this particular instruction will add a basic initialization for our console log (similar to JavaScript console.log ) if the console_log dependency is present.

Fig. 7: Add console log so we can easily debug our project

Next, we add a function that will hook to js_sys to return the ServiceWorkerGlobalScope.

Specifically on Cloudflare, the normal browser fetch call won’t work, as the workers run on headless V8 JavaScript engine. That’s why we need to hook on internal HTTP client for service workers.

Fig. 8: Add the ServiceWorkerGlobalScope

After adding our worker_global_scope , we proceed with editing the greet function. First, rename it to run then add our first instruction to hook rust panic to console_error . Then call init_log to initialize basic logging functionality.

Fig. 9: Set a panic hook and initialize default logger

Then we initialize our request with the method GET, you could also use other HTTP methods (e.g. POST, PUT, DELETE, …). The method depends on your application needs and endpoints you want to call.

Fig. 10: Initialize the request with method GET

Next, will be creating the request payload that we will submit to our custom fetch. The instruction will contain the endpoint and request options.

Fig. 11: Create the request payload

After finishing that, we will now scope and call the function we created earlier. Then we wrap it in a future (asynchronous method calls similar to JavaScript promise if your much more familiar in that term) .

Fig. 12: Submit the request to global fetch

On the returned response, unwrap it and return its JSON value.

Here is our full wasm function that will be called on our worker.js that we defined earlier above.

Fig. 13: Full wasm function

Now, we need to test it, to see if everything’s okay. Spin up a local server using the following command below.

Fig. 14: Run a local test server

Test everything and try to call the URL returned by wrangler dev using Postman or Insomnia HTTP client. If everything is working fine, its now time to deploy the worker to live server.

Fig. 15: Publish to Cloudflare servers

After running the command above, it will return a live worker URL which you can now access everywhere.

That’s all guys!

Conclusion

You can found the complete repository here.

This is not the only way to call fetch on Cloudflare worker rust, the other method involves in hooking directly to JavaScript exposed fetch (kindly look at Cloudflare example files). If you have any questions kindly leave a comment or DM me 😉.

Follow me for similar article, tips, and tricks ❤.

--

--