Setup Express with TypeScript in 3 Easy Steps
Create an Express server in a classic object-oriented style
Are you attracted to the ease-of-use and rapid-development of NodeJS with the Express web-server, but worried about the scalability and type-safety needed for large applications? Not to fear, TypeScript has got you covered. It still provides the advantages of a scripting language with the robustness of a static language like C# or Java. Learning TypeScript is trivial if you already know JavaScript, configuring it just requires a little extra setup.
Just to point out, I know there are some articles on Medium which show you how to use Express with TypeScript, but they either spend a lot of time talking about why you should use TypeScript and/or they don’t emphasize setting up Express in an object-oriented fashion. The point of this article is to show you the best and easiest configuration for TypeScript while developing for NodeJS/Express.
Edit Jun 2019
If you’re starting a project from scratch there is a npm library which can do all of this for us now named express-generator-typescript.
All the source code for this tutorial is available on GitHub here. You should observe the corresponding files/folders while you read the tutorial.
Setup TypeScript
During development, we can run our TypeScript code directly from the .ts
files that we create. For production though, we should transpile them to JavaScript so our server can be run directly from NodeJS. To configure how our TypeScript is transpiled and to set rules for the styling our code, we need to create the tsconfig.json
and a tslint.json
files respectively. Using tslint is not required but is extremely handy for enforcing coding standards and will lead to much cleaner code in the long run.
Create a new folder for your project and at the root add tsconfig.json
with the following content:
Notice the
exclude
option on line 23 which shows/src/public/
. We’re not going to cover the front-end for this tutorial, but once you do get around to adding some front-end content, it should go there.
Now add the following code for the tslint.json
file. I tend to use the recommended settings with a few tweaks. Feel free to play around with these settings if you want.
To allow us to execute some code, let’s create a start script which will boot up our server. Since we don’t have a server yet, just have it print out "hello world"
for now. Create the folder and file src/start.ts
and add the following 2 lines:
tslint is disabled because it pushes us not to use
console.log()
and it’s not good to leave it in production code.
// tslint:disable-next-line
console.log('hello world');
We don’t want to have to restart everything manually when we make a code change, so let’s use nodemon
to watch for changes in our files and re-execute our start script.
Great! We got everything we need to start developing in TypeScript, we just need to install dependencies. Run npm init
if you haven’t done so yet to your project in an npm package, then install the following npm libraries:
npm i -D ts-node nodemon typescript tslint
So we can start things with ease without having to enter a bunch of long commands in the console each time we want to start developing, let’s add a script to package.json
to run the start script through nodemon with ts-node
.
See line 8 below:
Run npm run start-dev
and you should see hello world
output to the console.
Setup Express
Now that TypeScript is all setup and running well, let’s create a simple ExpressJS webserver and few routes. We could use ExpressJS directly but then we wouldn’t take advantage of TypeScript. It would be nice to create classes with methods instead of having to type let router = express.Router(), router.get/put/post, app.use(router)
and all that over and over again.
To stay closer to the MVC pattern and utilize OO style programming, I recommend OvernightJS
to add controllers and route decorators to Express. Yeah I know what you’re going to say, “Aren’t there frameworks out there like NestJS and ts-express-decorators which can decorate Express routes?” Yes, that’s true, but these are all massive frameworks with entire websites dedicated to their documentation. Overnight is just a simple, small collection of libraries for adding decorators to Express and a couple other things. It’s not an abstraction layer on top of Express, and you can learn it in about 10 minutes if you’re already familiar with Express.
Let’s install Express and Overnight and spin-up a web-server:
The body-parser package is so we can send our data as JSON.
npm i -s express body-parser @overnightjs/core @overnightjs/logger
npm i -D @types/node @types/express
Under src/
, create a file for the server (mine is ExampleServer.ts
) and create a class of the same name. Then add another folder/file controllers/ExampleController.ts
. We’ll implement the controller first then import it into our server file.
Add the following content to the controller file:
Notice we created a method for every route just to see each one in action. The Logger class is handy because it can be configured to print to a file, the console, turned-off completely, or something custom depending on your server environment.
When you’re done with the controller, make sure to add an index.ts
file to controllers/
, with the line export * from ‘./ExampleController’;
so that any new controller files created in the future can be easily added with just an extra line of code.
In the server, import the controllers and the extend the class with Overnight’s Server
export. By extending Server
, you will have access to the Express instance with this.app
, which you can interact with just like any normal Express instance made with require(‘express’)()
.
Controllers must be instantiated and added as an array to super.addControllers(…)
to activate your routes. Make sure to add your controllers after setting the middleware but before starting the server.
Now that we have our server and controllers, we just need to boot everything from the start script. Import the server, instantiate it, and call start(portNumber)
.
Once you see "[someTimestamp]: Example server started on port: 3000"
print out to the console, you can open up an API calling tool of your choice (i.e. Postman) and fire of requests to the server. If you followed my examples to the letter, you should see the :msg
part of your routes print out to the console.
Build your code
Now that we have a fully functional development server up and running, all we need to is build it for production. In case you delete .ts
files as you develop, you should remove the build/
folder every time you transpile or you’ll end up with junk .js
files .
To start the production code, we need to run build/start.js
instead of src/start.ts
. Let’s add two more scripts to package.json
to build and run the code for production.
The
tsc
command tranpsiles our code. See line 9 below:
Once your server is started, all your routes should work just the same as they did before.
Please star the tutorial’s repo and the OvernightJS repo on GitHub if you found this article helpful. Happy web-deving :)