» Node.js: Building Event-Driven Microservices with Kafka » 2. Producer: Web Service » 2.2 Express Web Server

Express Web Server

Create a package

Run the npm init command to create a package.json file for your application.

npm init

This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them except the entry point.

We prefer to use app.js rather than index.js.

Its result should be similar to this:

package name: (lr_event_driven_node) 
version: (1.0.0) 
description: Example project: building event driven microservices in Node.js.
entry point: (index.js) app.js
test command: 
git repository: https://github.com/Literank/lr_event_driven_node.git
keywords: event-driven,kafka,express
author: literank.com
license: (ISC) MIT

{
  "name": "lr_event_driven_node",
  "version": "1.0.0",
  "description": "Example project: building event driven microservices in Node.js.",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Literank/lr_event_driven_node.git"
  },
  "keywords": [
    "event-driven",
    "kafka",
    "express"
  ],
  "author": "literank.com",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/Literank/lr_event_driven_node/issues"
  },
  "homepage": "https://github.com/Literank/lr_event_driven_node#readme"
}

This command creates a package.json file in which dependencies you add will be listed for tracking.

Install Express

npm install express

This command updates the package.json file and creates a package-lock.json file in your project.

Create templates

Create a folder named templates, and move index.html into the folder. Change its name to index.handlebars.

Tune its title:

- <title>LiteRank Book Store</title>
+ <title>{{ title }}</title>
...
- <h1 class="text-4xl font-bold">LiteRank Book Store</h1>
+ <h1 class="text-4xl font-bold">{{ title }}</h1>

{{ title }} is a template syntax used by the Handlebars templating engine. You can use any template engine you want with Express.

Install Handlebars

npm install express-handlebars

express-handlebars is a Handlebars view engine for Express.

Tune package.json

Ensure that your package.json file has "type": "module" to indicate that your project uses ES modules:

{
  "type": "module",
  "dependencies": {
    "express": "^4.19.2",
    "express-handlebars": "^7.1.2"
  }
}

Create app.js:

import express from "express";
import { engine } from "express-handlebars";

const app = express();
const port = 3000;

// Set Handlebars as the template engine
app.engine("handlebars", engine());
app.set("view engine", "handlebars");
// Set the directory for template files
app.set("views", "./templates");

// Define a route to render the template
app.get("/", (req, res) => {
  // Render the 'index.handlebars' template, passing data to it
  res.render("index", { layout: false, title: "LiteRank Book Store" });
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Read more about layout property here: https://www.npmjs.com/package/express-handlebars#layouts

Run the program like this:

node app.js

You will get one line like this:

Server is running on http://localhost:3000

Your web server is runnong on port 3000 now.

Try visiting the URL http://localhost:3000/ in your browser. It should display the webpage we designed in the previous section.

Use TypeScript

Using TypeScript in a Node.js project offers several benefits:

  1. Static Typing: TypeScript allows you to define types for variables, parameters, and return values. This helps catch type-related errors during development rather than at runtime, leading to more robust and predictable code.
  2. Improved Code Readability: With type annotations, code becomes more self-documenting, making it easier for developers to understand the codebase and collaborate effectively. Type information serves as additional documentation, especially for large projects.
  3. Enhanced IDE Support: TypeScript provides better tooling support in IDEs like Visual Studio Code, offering features such as code navigation, auto-completion, and inline documentation, which can improve productivity and code quality.

So, let's transform it.

Run the following command to install typescript dependencies:

npm install typescript ts-node @types/node @types/express --save-dev

The --save-dev flag ensures that these dependencies are saved as devDependencies, as they are only required during the development process.

Create tsconfig.json in your root directory:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "CommonJS",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

Move app.js to src/app.ts.

Changes in package.json:

@@ -1,11 +1,11 @@
 {
   "name": "lr_event_driven_node",
   "version": "1.0.0",
-  "type": "module",
   "description": "Example project: building event driven microservices in Node.js.",
   "main": "app.js",
   "scripts": {
-    "test": "echo \"Error: no test specified\" && exit 1"
+    "dev": "ts-node src/app.ts",
+    "build": "tsc"
   },
   "repository": {
     "type": "git",
@@ -25,5 +25,11 @@
   "dependencies": {
     "express": "^4.19.2",
     "express-handlebars": "^7.1.2"
+  },
+  "devDependencies": {
+    "@types/express": "^4.17.21",
+    "@types/node": "^20.12.7",
+    "ts-node": "^10.9.2",
+    "typescript": "^5.4.5"
   }
 }

Run the new program like this:

npm run dev

Again, try to visit the URL http://localhost:3000/ in your browser.

If the webpage looks good, that means your TypeScript version web server is doing well.

PrevNext