How To Setup A NodeJS Server With Typescript
Iván Roldán Lusich
Posted on December 22, 2020
Why NodeJS?
If you are here, I assume that you are at least familiar with NodeJS, but if you want to jump into both Typescript and NodeJS at a time, I’ll explain briefly what NodeJS is. It’s a Javascript runtime for the backend, which means that you can write Javascript (or in our case, Typescript) in both our frontend and our backend, which makes the transition between coding in one to the other really easy. And, just to name one of its advantages, thanks to the V8 engine, which makes it really fast.
But now, to the real question: Why Typescript?
In case you don’t know, Typescript is statically-typed Javascript. And one might think that this isn’t a good idea, because typing statically required declaring types in your variables, functions, defining interfaces, and a lot of time-consuming stuff.
But I don’t see it that way, by defining your types in your code, you are setting yourself up for fewer errors and headaches since you don’t even need to run your code to realize that you’re are passing the wrong type of variable to your function.
You can see how we are indicating that the function ‘subtract’ takes to numbers as arguments. And typescript indicates the developer that something is wrong with your function call by showing a red underline, if you hover over it you’ll see something like this:
Indicating that the subtract function returns a number, which can’t be assigned to subtractResult since we declared it as a string.
In the line before that, you can see how we can call the function with incorrect types in its arguments either.
Although in this example it doesn’t seem as important, when you have bigger programs with a lot of functions and types, getting rid of small headaches related to types of variables saves a lot of time.
And that’s why we are going to be setting up a NodeJS/Express server with Typescript today. Let’s get started.
Setting up the environment
I’m going to be using Yarn during this tutorial, but I’ll also add NPM commands, however, feel free to use any package manager you want to.
Let's first call yarn or npm init --y to stark working on our project.
Now, we’ll install all the packages we need to get started.
We are going to be needing typescript and express, for obvious reasons. We are also going to need express-session to handle our sessions. Let’s go ahead and install those for now.
yarn add typescript express express-session
npm i typescript express express-session — save
One little caveat that you have to take into account when using typescript, is that external packages need to have typings, this is normally not a problem since most packages have them, but some not installed by default. If the one you are trying to use doesn’t have typings by default, you should try doing:
yarn add -D @types/nameOfPackage
npm i -D @types/nameOfPackage
An example of this is the node, express, and express-session libraries, we need to install typings for it if we want to work with typescript. Let’s do it by running
yarn add -D @types/node @types/express @types/express-session
npm i -D @types/node @types/express @types/express-session
Creating the server
Because I’m going to be using this exact project to do more tutorials in the future, I’m going to get a proper folder structure. Create a new folder called ‘src’, and inside of it, a file called index.ts, this is going to be the entry point of our application.
Don’t forget, since this is typescript, we can take advantage of ES6 imports, which I like a lot more than the ones you normally use on NodeJS.
Let’s start by writing a very basic server:
Line 1: We are importing express from our just installed express package.
Line 3: We are initializing the express framework and storing it into the ‘app’ constant.
Line 5: process.env.PORT is going to check your environmental variables to see if there’s a PORT defined in there, if there isn’t, it’ll default to 5000.
Line 7: We use the listen function, already included with the Express framework, that expects the port number that the application will be using as a first parameter. It also accepts a second optional parameter, which we are using to log into the console that our app is listening in the desired port.
Running the server
To run the server in our development environment, we are going to use the ts-node package. It comes included as a dependency in ts-node-dev, so we proceed by installing it.
yarn add -D ts-node-dev
npm i --only=dev ts-node-dev
Now, we head over to our package.json file that was automatically created when you installed these packages, and under the ‘scripts’ tag, we must define one to start our server.
We are almost ready to start, but we first need to create a tsconfig.json file, this will tell ts-node how strict to be, as well as how to compile the code. Since we are using ES6 imports, we need to set it as a target. This is my current Typescript configuration, but feel free to use the one you find most comfortable:
Most of the options explain their functionality with their name, but you can check out available options here.
We are now officially ready to start our server. Run
yarn start
npm run start
Your server should now be up and running.
A little bit more setup before sessions
Now that our server is running, let’s add some session handling with the help of our previously installed module express-session. We need to create a cookie-secret for our session, and it can’t be available to anyone because that would create a security risk on our application. Let’s go ahead and create some files to handle our keys.
In our source directory, create a config folder, and inside of that, we are going to create three files: ‘dev.ts’, ‘prod.ts’, and ‘keys.ts’. Your directory should look like this:
Now, on ‘dev.ts’, we’ll add the following code:
Now, on ‘prod.ts’:
And finally, on ‘keys.ts’:
The first two files are pretty straight forward, we just define an object with our cookie-secret and export it, if it’s in production you’ll have it declared as an environmental variable so it can’t be accessed by any intruder.
‘keys.ts’, however, is more involved.
Line 1 and 2: We import our objects from the ‘dev.ts’ and ‘prod.ts’.
Line 4 to 6: We create an interface that defines what our keys function is going to return. This ensures that the keys function will return an object that contains a key named ‘cookieSecret’, which value is a string.
Line 8 to 14: We export a function that returns our production keys if we are in a production environment, or our development keys otherwise.
Now it’s time to add sessions to our application.
Handling sessions with express-session
This is the code after adding sessions to our application:
Line 2: We import express-session to a constant called ‘session’.
Line 3: We import our just created ‘keys’ function from its directory.
Line 7: Destructure ‘cookieSecret’ from our ‘keys’ function.
Line 9 to 19: Using the built-in ‘use’ function in express, we declare a session object with some configuration. In which we include our cookieSecret constant as the session secret. You can check more about express-session configuration in the official documentation.
And that concludes this tutorial! I uploaded the final code to a Github repository to make your life easier.
It’s the first time I’ve ever done this, so feel free to criticize me or tell me how I can improve.
Posted on December 22, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 24, 2024