Create an OTP service in Node Js Part 1

Create an OTP service in Node Js Part 1

Make a fully functional NodeJs server for sending and verifying OTP part 1

Hi there,

This is a part 1 in a 4 part series where we talk about how you can create an OTP service in Nodejs. For this part of the series we are going to set up our project and make sure things are up and running.

if you feel lost along the way, you can check out the git repositiory

Introduction

In case you're wondering

what is an OTP?

Well, OTP stands for One Time Password. Basically, an OTP is used for verification and authentication purposes.

First Steps

initialize a new project

yarn init -y

install the following packages

yarn add nanoid jsonwebtoken express cors dotenv
yarn add -D typescript ts-node-dev @types/express @types/cors @types/jsonwebtoken

What Do Our Packages Do?

nanoid - used to generate OTP's

jsonwebtoken - a safe way to pass information between multiple parties

express - sets up our server

cors - makes our server accessible from any origin

dotenv - stores private keys

ts-node-dev - watches our typescript files for changes and restart's the server

Create some basic files

In the root directory create a .env file where we will store our private keys. Create a src folder and add anindex.ts file. Here, we will initialize our express app

your file structure should look like this

otp-file-structure.png

OOPS! we forgot to initialize our typescript project

tsc --init

add this key in your .env file

PORT = 5000

open up your index.ts file and add the following

import express, { Response, Request } from "express";
import dotenv from "dotenv";
import cors from "cors";

const app = express();
dotenv.config();
app.use(cors());
app.use(express.json());

app.listen(process.env.PORT, () => {
  console.log(`Server is running on port ${process.env.PORT}`);
});

app.get("/", (req: Request, res: Response) => {
  return res.send("⚡⚡⚡Server is up and running⚡⚡⚡");
});

Progress

in order to test if our code is running so far, we need to add this script to our package.json file

"scripts": {
    "dev": "ts-node-dev --respawn --transpile-only src/index.ts"
  },

to start our development server, we need to run this command in our terminal

yarn run dev

to check if things went according to plan, we need to go to localhost:5000 in our browser. If things went well, we should see this pleasant screen

otp-server-running.png

Next Steps

For our next post, we would add MongoDB to our application to store our Users and OTP