Skip to content

Initializing a worker

Course: Serverless Backends - chapter 7

To create and deploy your application, you can take the following steps -

Initialize a worker
npm create cloudflare -- my-app

Select no for Do you want to deploy your application

Explore package.json dependencies
"wrangler": "^3.0.0"

Notice express is not a dependency there

Start the worker locally
npm run dev
How to return json?
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return Response.json({
message: "hi"
});
},
};

Question - Where is the express code? HTTP Server?

Section titled “Question - Where is the express code? HTTP Server?”

Cloudflare expects you to just write the logic to handle a request. Creating an HTTP server on top is handled by cloudflare

In express, routing is done as follows -

import express from "express"
const app = express();
app.get("/route", (req, res) => {
// handles a get request to /route
});

How can you do the same in the Cloudflare environment?

export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
console.log(request.body);
console.log(request.headers);
if (request.method === "GET") {
return Response.json({
message: "you sent a get request"
});
} else {
return Response.json({
message: "you did not send a get request"
});
}
},
};

💡 How to get query params - https://community.cloudflare.com/t/parse-url-query-strings-with-cloudflare-workers/90286

Cloudflare does not expect a routing library/http server out of the box. You can write a full application with just the constructs available above.

We will eventually see how you can use other HTTP frameworks (like express) in cloudflare workers.