Implement AWS Cognito with Express JS(TS)

Part 1 - Project Setup

Link to Source Code

GitHub Repository

Let's begin by creating a starter Node.js/Express.js Starter project

> mkdir CognitoProject
> cd CognitoProject
> npm init -y

The above will create a basic Node.js Application.

Now Let's download and install some packages from npm

> npm install --dev typescript ts-node @types/node @types/express nodemon
> npm install express body-parser express-validator

Add script to compile and build our project

package.json

 "scripts": {
    "dev" : nodemon,
    "start": "ts-node dist/server.js
  },

Let's create our src directory and starter files

  1. Create a directory called src in the root of your project.

  2. Inside the src directory, create two files, app.ts, server.ts

inside app.ts

import express from "express";
import { json } from "body-parser";
const app = express();

app.use(json());

export { app };

inside server.ts

import { app } from "./app";

const start = async () => {
  console.log("STARTING....");
  app.listen(3000, () => {
    console.log("Listening on port 3000!!!!!!!!");
  });
};

start();

Now we need to initialize our project with a tsconfig file, we can simply do that by running the following command in our root file.

$ tsc --init

And ensure your tsconfig matches the following:

{
  "compilerOptions": {
    "sourceMap": true, // helps for debugging
    "target": "es6",
    "module": "commonjs",
    "outDir": "./dist",
    "baseUrl": "./src",
    "removeComments": true, // removes all comments
    "incremental": true, // compares dist and compiles whats needed
    "esModuleInterop": true // allows default export
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

Nodemon Config.

Now we want to add nodemon for our development environment.

Running the App.

$ npm run dev

> cognito@1.0.0 dev
> nodemon

[nodemon] 2.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src/**/*
[nodemon] watching extensions: ts
[nodemon] starting `ts-node ./src/server.ts`
STARTING....
Listening on port 3000!!!!!!!!