Express.js With Typescript Decorators in Examples

Artem Diashkin
Nov 22, 2020 · 5 min read

Let’s take a look at how we can make our Express.js Server code cleaner with use of the Typescript Method Decorators.

What will be covered in this story:

  1. Prerequisites. Creating Express Typescript project
  2. Wrapping Express API Route with Typescript Method Decorator
  3. Async Method Decorator
  4. Adding Logging Decorator
  5. Adding Authentication Decorator
  6. Codesandbox Playground

1. Prerequisites. Creating Express Typescript project

Before we will start exploring Express.js with Typescript Decorators examples, we will create a simple Typescript Node.js project with Express.js and some additional npm packages that will be in use in our work. Let’s get started.

First, create an empty folder and initialize npm project by running npm init -y in the root directory: (-y flag means that you are answering yes to all npm questions):

Empty project, running npm init -y

We will need to add some npm packages to the dependencies:

yarn add express body-parser

And some npm packages to the dev dependencies:

yarn add typescript @types/node @types/express ts-node -D
package.json

Next, we will need to add tsconfig.json file by running npx tsc — init in the root of our project:

tsconfig.json

⚠️NOTE: To enable experimental support for decorators, you must enable the experimentalDecorators compiler option in your tsconfig.json file

Next, we will need to create a /src/server.ts file:

src/server.ts file. GitHub gist

… and the index.ts file that will be an entry point of our application:

NOTE: I have already created a “start” script in the package.json file.

index.ts file. GitHub gist

Before we will start implementing our first API Route with use of the Typescript Decorators, let’s test that everything works as expected by running “start” script in the console:

yarn run start

If everything was configured without any issues you will see this message in the console:

🚀 Server is running on port 3000
Terminal. Server is successfully launched on port 3000

🎉 Congratulations! We are ready to implement our first API Route.

2. Wrapping Express API Route with Typescript Method Decorator

If you are not familiar with Typescript Decorators, what are PropertyDescriptor and descriptor.value are, I would recommend you to check out this story first:

Let’s create our first function in the Routes class:

Added new API Route to the index.ts file. GitHub gist

routeConfig function is a Typescript MethodDecorator that is added to the “anyNameYouLike” function. The main goal of this Decorator is to specify our API Route method (GET/POST), and a path.

Let’s re-run our application and see what we get:

Terminal. Application successfully re-ran on port 3000
Chrome Tab. URL localhost:3000/hello. Result — “Hello World” string

🎉 Nice, we have created our first API Route Decorator.

3. Async Method Decorator

Our previous example will not work with async code, let me demostrate you this issue.

We will create a new “post” endpoint that should return String message after 2 seconds:

If we will re-run our server and will make a request using Insomnia or a Postman to that endpoint we will get 200 status empty response:

Insomnia. No async response

To change such undesirable behaviour we will need to modify our routeConfig Method Decorator so it could handleasync code:

routeConfig Typescript decorator. GitHub gist

Now we can re-run our application to make sure that everything works as expected (gif):

GIF. Async data response in Insomnia after 2 seconds

4. Adding Logging Decorator

For logging user requests we will create a simple Method Decorator that will log user’s request data to the console and pass it through. Decorators work in chain, so we need to pass data to next decorator or execute it:

new “routeLog” Typescript decorator

Now we can add it to our route…

Updated route method with new routeLog() decorator

… and make our request:

Insomnia request data

Result in the terminal:

Terminal results after logging user’s request data

5. Adding Authentication Decorator

Now we can add authentication decorator that will allow us to filter users:

routeAuth Typescript Decorator. GitHub gist

Now we can add this auth decorator to our route:

Updated route with new routeAuth decorator

After adding authorization token “123" (Bearer text will be added automatically by Insomnia):

Insomnia. Post request after adding auth decorator to express route

And result would be:

Terminal. Result with authorization header “Bearer 123”

6. Codesandbox Playground

I have created a codesandbox playgroud for you, so you could test is by yourself:

You can open it in a new tab…

… and see the API server URL (https://kjitb.sse.codesandbox.io/ for example).

🎉 Happy coding!

Geek Culture

Proud to geek out.

Sign up for Geek Culture Hits

By Geek Culture

Subscribe to receive top 10 most read stories of Geek Culture — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Artem Diashkin

Written by

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer

Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Artem Diashkin

Written by

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer

Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store