Express.js with Typescript Decorators in Examples

Image for post
Image for post

What will be covered in this story:

1. Prerequisites. Creating Express Typescript project

Image for post
Image for post
Empty project, running npm init -y
yarn add express body-parser
yarn add typescript @types/node @types/express ts-node -D
package.json
tsconfig.json
src/server.ts file. GitHub gist
index.ts file. GitHub gist
yarn run start
🚀 Server is running on port 3000
Image for post
Image for post
Terminal. Server is successfully launched on port 3000

2. Wrapping Express API Route with Typescript Method Decorator

Added new API Route to the index.ts file. GitHub gist
Image for post
Image for post
Terminal. Application successfully re-ran on port 3000
Image for post
Image for post
Chrome Tab. URL localhost:3000/hello. Result — “Hello World” string

3. Async Method Decorator

Image for post
Image for post
Insomnia. No async response
routeConfig Typescript decorator. GitHub gist
Image for post
Image for post
GIF. Async data response in Insomnia after 2 seconds

4. Adding Logging Decorator

new “routeLog” Typescript decorator
Updated route method with new routeLog() decorator
Image for post
Image for post
Insomnia request data
Image for post
Image for post
Terminal results after logging user’s request data

5. Adding Authentication Decorator

routeAuth Typescript Decorator. GitHub gist
Updated route with new routeAuth decorator
Image for post
Image for post
Insomnia. Post request after adding auth decorator to express route
Image for post
Image for post
Terminal. Result with authorization header “Bearer 123”

6. Codesandbox Playground

Image for post
Image for post

Written by

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

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