Step by Step guide to setup Node server with Typescript

Garima - Oct 29 - - Dev Community

So, I’m pretty new to TypeScript. As someone who’s been working with Node.js and JavaScript for a while, I thought switching to TypeScript would be a breeze. You know, it's just JavaScript with types slapped on, right? Well, I quickly realized it’s not that simple.

I wanted to find a good guide or video that explained how to build a Node.js server with TypeScript from scratch—something that didn’t feel like a puzzle missing half the pieces. But honestly, most of the stuff out there either skimmed over the basics or assumed I was already some TypeScript expert. It was frustrating!

That’s when I thought, why not write down everything I’ve learned so far? If you’re a JavaScript or Node.js developer like me, and you’re struggling to find a decent step-by-step on how to get started with TypeScript, I’ve got you covered. Let’s make this transition as smooth as possible, without the head-scratching moments.

Alright, let’s dive in! We will set up a Node.js server with TypeScript, and we will look at some other cool tricks along the way.

Step 1: Initialize Your Node Project

First things first, we need to initialize a Node.js project. Open up your terminal, go to your project folder, and run this command:

npm init -y 
Enter fullscreen mode Exit fullscreen mode

The -y flag just skips all the annoying setup questions like package name, version, etc. It says "yes" to everything, and bam! You’ve got yourself a package.json file. This is where Node.js tracks all the dependencies and scripts for your project.

Step 2: Create Your First File

Next up, create a file named index.js. For now, we’ll work in plain JavaScript to see how things work before we switch to TypeScript.

In index.js, let’s try importing a package. The traditional way of doing this in Node.js is by using CommonJS syntax:

const fs = require('fs');
Enter fullscreen mode Exit fullscreen mode

Here, we are using the built-in file system module, a common pattern in Node.js. If you’ve worked with JavaScript before, this should be familiar. However, most developers today prefer using the import-export syntax as it looks cleaner, more organized, and fancy.

Now if we convert this to the new syntax

import fs from 'fs';
Enter fullscreen mode Exit fullscreen mode

Now of we try to run this code we might be getting some errors stating some warning saying we cannot use this ES module unless we update our package.json and change the type to module

Image description

Simply add type: 'module' in the package.json file. This tells Node to use Es module instead of require. And now our code might be working fine.

type: 'module'
Enter fullscreen mode Exit fullscreen mode

Now, let's talk about Typescript because this is what this blog is all about. Go ahead and install typescript as a dev dependency because we don't need it in the production environment. You can use any package manager you want to use for installing the packages whether it be pnpm, bun, npm or whatever.

npm i typescript --save-dev
Enter fullscreen mode Exit fullscreen mode

Yeah, we have installed it but what exactly is typescript?

TypeScript is a superset of JavaScript, meaning it is built on top of JavaScript by adding optional static typing. This means you can define the types of variables, functions, and objects, helping to catch errors early in the development process.

Now this is important! TypeScript code needs to be compiled into regular JavaScript so that it can run in browsers or Node.js environments, as they don't natively understand TypeScript. And now we know why we don't need it in the production environment.

To convert the Typescript code to Javascript, we need to add a script in out package.json that will run the Typescript compiler that converts the TS code to the JS or technically speaking building the application. Go to the package.json and inside the scripts object add a build command that helps us to do the covering thing.

scripts: { 
build: "tsc".
// ... rest of the commands
}
Enter fullscreen mode Exit fullscreen mode

Typescript needs some configurations to get started with it. Before actually starting the configuration let's organise out root directory. Create a src folder and drag the index.js file we just created and change the extension to .ts now we have an index.ts file inside the src folder.

When using node built-in modules you might get an error that says it cannot find corresponding type declarations. In lay man, it says install the types for node. Install the types for node using this command and the error should disappear.

npm i @types/node --save-dev
Enter fullscreen mode Exit fullscreen mode

Run tsc --init, you might be able to see a tsconfig.json file if not go ahead and create it, we don't have to worry about it. We will now configure typescript to make it behave like we want it to.

{
  "compilerOptions": {
    "target": "es2020",
    "module": "NodeNext",
    "rootDir": "./", // Update this to your source directory
    "outDir": "./dist" // Update this to your desired output directory
  },
  "include": ["./" ], // Ensure this matches your source directory
  "exclude": [ "node_modules", "dist"] // Exclude output and dependency directories
}
Enter fullscreen mode Exit fullscreen mode

You can copy-paste the configurations above or create your own to, but trust me this config works for almost all of the TS projects.

target: Specifies the JavaScript version that TypeScript should compile to. "es2020" here means the compiled code will use ECMAScript 2020 features.

module: Determines the module code generation method. "NodeNext" is suited for modern Node.js environments that use ES Modules (import/export syntax) rather than CommonJS.

rootDir: Specifies the directory where your source code files are located. "./" means the root directory, but you can change it to your specific source folder.

outDir: Defines where the compiled JavaScript files will be output. "./dist" sets this to the dist folder, so all compiled files go there.

include: Specifies which files and folders to include in the compilation. "./" includes all files in the root directory. Adjust it if your source files are in a different folder.

exclude: Excludes certain directories from compilation, typically those you don’t want TypeScript to process. Here, "node_modules" (dependencies) and "dist" (output folder) are excluded to avoid redundant checks.

Go into the terminal and run the build command we just wrote in package.json

npm run build
Enter fullscreen mode Exit fullscreen mode

Now, you might be able to a dist folder in your root directory containing an index.js file. This command generates the dist folder that contains the Javascript code that we can actually run on NodeJs.

Voila! We are done with setting up typescript for creating our Nodejs server using Typescript. There are tons of other options to configure the tsconfig but I don't think we would need to use them.

Set up a Node Server

Creating a Node server will work the same as we do it while working with Javascript. We just need to install types for our dependencies eg. express node module. We need the express module in production environment and types are needed only the development environment.

Install dependencies

npm i express;
npm i ts-node @types/express --save-dev
Enter fullscreen mode Exit fullscreen mode

Basic Server

import express, { urlencoded, json } from "express";

const app = express();

app.use(urlencoded({ extended: true }));
app.use(json());

app.listen(4000, () => {
  console.log(`Server is listening at port 4000`);
});
Enter fullscreen mode Exit fullscreen mode

We're done with setting up a Node server. Run npm run dev, your server might be up and running.

Now the question is do we need Typescript?

Whether or not, it totally depends on one's project's needs. But, I believe using Typescript makes Javascript somewhat strict. It provides type-checking and various other features. As Javascript is a dynamically typed language, it can do blunders sometimes, you may never know what is leading to the server crash. Where you might be accidentally updating a string var with an integer. Javascript is sweet it will allow you to do that, but Typescript no,no sweetheart!

In the end, it's all Javascript :)

Want to connect?

twitter · blogs · portfolio · email · linkedin

Written and edited by me❤️

. . . . . . . . . . . . . . . . . . .