Create a simple web server using Node.js, Express and TypeScript

Updated: December 28, 2023 By: Guest Contributor Post a comment

Overview

In this tutorial, we will dive into the creation of a simple web server using Node.js, Express, and TypeScript. Node.js provides the runtime environment for executing JavaScript on the server side, Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications, and TypeScript is a typed superset of JavaScript that compiles to plain JavaScript and has gained popularity for its ability to improve code quality and understandability.

Why TypeScript?

TypeScript adds static typing to JavaScript, which can catch errors at compile time, leading to more robust codebases. It’s especially useful in larger applications or when working with teams. TypeScript also offers better autocompletion, navigation, and refactoring services in IDEs, improving the developer experience and productivity.

Steps to Create a Simple Web Server Using Node.js

Step 1: Setting Up the Project

mkdir my-web-server
cd my-web-server
npm init -y
tsc --init
npm install express @types/express --save

First, we create the project directory and initialize it with a package.json file. Then we initialize TypeScript in the project with the tsc --init command, which creates a tsconfig.json file. Lastly, we install Express and its TypeScript types.

Step 2: Creating the Server

import express from 'express';

const app = express();

app.get('/', (req, res) => {
  res.send('Hello TypeScript with Express!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

We import Express, create an instance of it, define a route for the root path, and make the server listen on a port. We use an environment variable for the port with a default fallback.

Express and TypeScript Best Practices

When using TypeScript with Express, it’s important to always define types for request and response objects. This improves code reliability and helps with documentation. Structuring your project into models, routes, and services can also help keep your codebase clean and maintainable.

Conclusion

In this tutorial, we’ve explored the basics of setting up a simple web server with Node.js, Express, and TypeScript. This setup grants us the benefit of static typing in JavaScript, leading to fewer runtime errors and more maintainable code. By following the steps and best practices outlined in this guide, developers can build robust web applications effectively.