ExpressJS on Cloudflare

Published on
Platforma

Creating ExpressJS Application for Cloudflare Worker

  1. Create basic Cloudflare Worker Project

    npm create cloudflare@latest -- appName
    • For What would you like to start with?, choose Hello World example
    • For Which template would you like to use?, choose Worker only
    • For Which language do you want to use?, choose TypeScript
    • For Do you want to use git for version control?, choose Yes
    • For Do you want to deploy your application?, choose No

    Change into your new project directory: cd appName

  2. Install Express and dependencies

    • Install Express: npm i express @types/express
    • At Wrangler.jsonc, verify it includes "compatibility_flags": ["nodejs_compat"]
  3. Initialize Express Application page

    At src/index.ts, replace the existing content with:

    import { env } from "cloudflare:workers";
    import { httpServerHandler } from "cloudflare:node";
    import express from "express";
    
    const app = express();
    
    // Middleware to parse JSON bodies
    app.use(express.json());
    
    // Health check endpoint
    app.get("/", (req, res) => {
      res.json({ message: "Express.js running on Cloudflare Workers!" });
    });
    
    app.listen(3000);
    export default httpServerHandler({ port: 3000 });
  4. Test ExpressJS applocation

    • npm run dev
  5. Deploy / Redeploy ExpressJS application on Cloudflare

    NOTE: For deploying through a token, follow Deploy to Cloudflare With a token.

    • npm run deploy

Express With Handlebars

Do not use express-handlebars, use pure handlebars instead.

npm install handlebars
  • Create a structure such as:
    src/
    ├── views/
    │   ├── layout.hbs
    │   ├── pages/
    │   │   ├── page.hbs
    │   │   └── page2.hbs
    │   └── partials/
    │       ├── header.hbs
    │       └── footer.hbs
    └── templates/
        ├── templates.precompiled.cjs (this will be created automatically by a command below))
        ├── partials.precompiled.cjs (this will be created automatically by a command below)
        └── render.ts
  • Recompile Handlebars
    • Recompile templates: npx handlebars src/views -f src/templates/templates.precompiled.cjs -m -e hbs -r src/views -c handlebars/runtime
    • Recompile Partials: npx handlebars src/views/partials -f src/templates/partials.precompiled.cjs -m -e hbs -r src/views/partials -c handlebars/runtime -p
  • Generating env tÿpes: npx wrangler types
Vrealmatic consulting

Anything unclear?

Let us know!

Contact Us