Node Rest API + JWT in Typescript

Philippe Collignon
4 min readFeb 21, 2019

--

In this story, we are going to build simple Node.js/Express Rest API written in Typescript. The routes of the API can be protected with JWT Tokens.

The architecture is the following :

  • A Node Server dispatches requests to express routers.
  • The routers delegate the implementation to controller’s express middleware .
  • If the route must be protected, a JWT middleware is called before the controller middleware. It verifies the authentication with a Passport strategy.
  • The controllers then call the models that connect to the mongo database.

If you want the full code with a demo of this API with an JWT token authentification, just have a look the following GitHub repository, for the explanations continue reading the story !

The Server

Because we are writing the API in Typescript, the Server can be implemented as a class and the express app is a simple class property :

Then we add a server config method add call it in the constructor :

Our API uses json body parser and some other middlewares.

Finally we add a mongodb client setup using mongoose.

Note that we are using async/await to fully take advantage of Typescript. The MONGODB_URI should be loaded from environnement variable with a secret.ts file as this :

The Routes

Every Rest API has some routing. The routing has two levels : first a routing depending of the model (products, clients, ..) then a routing depending of the operation (get, create, update,..)

Implement a nice routing strategy in the following way : the first level of routing is defined in the server.ts file :

Then a second level of routing is implemented in a Routing class, one class for each model. Routes are relative to the model, define one route for each operation.

If the route must be protected, just add a JWT middelware to check the authentification by JWT tokens (more information later).

The Controllers

The controller defines some middelwares, one for each operation. Async/await is again used for better Typescript code.

The Models

The models define an interface code and use mongoose for database persistence. They are imported and used by the controllers.

JWT Authentification

Protecting some API routes is often needed. Here the routes are protected by JWT tokens. The implementation is based on Passport.js JWT strategy.

Store your JWT secret in an environnement variable and load it with a secret.ts file :

Then you just have to add the JWT middleware to the route :

Finally, you can test a call with or without JWT token. Add the token to the HTTP Header as this :

If you want the full code with a demo of this API with an JWT token authentification, just have a look to this GitHub repository :

--

--