NestJS: Authentication With JWT and Postgres | by Kevin Vogel | Mar, 2022

Build a NestJS app for authentication with Postgres, JWT, and environment variables

Kevin Vogel
NestJS Authenfication API
$ psql postgres
$ CREATE DATABASE nest_auth_api;
$ l
$ q

Command Explanation:

$ npm i -g @nestjs/cli
$ nest new nest-auth-api -p npm
$ cd nest-auth-api
$ code .
$ git add .
$ git commit -m "chore(): init nest.js"

Installing Dependencies

$ npm i @nestjs/config @nestjs/typeorm @nestjs/jwt @nestjs/passport passport-jwt typeorm pg passport class-transformer class-validator class-sanitizer bcryptjs
$ npm i -D @types/passport-jwt @types/node

Create Project Structure

$ mkdir src/shared && mkdir src/shared/typeorm
$ mkdir src/common && mkdir src/common/envs && mkdir src/common/helper
$ touch src/shared/typeorm/typeorm.service.ts
$ touch src/common/envs/development.env
$ touch src/common/helper/env.helper.ts
$ nest g mo api
$ nest g mo api/user && nest g co api/user
--no-spec && nest g s api/user --no-spec
$ nest g mo api/user/auth && nest g co api/user/auth
--no-spec && nest g s api/user/auth --no-spec
$ touch src/api/user/user.dto.ts
$ touch src/api/user/user.entity.ts
$ touch src/api/user/auth/auth.dto.ts
$ touch src/api/user/auth/auth.guard.ts
$ touch src/api/user/auth/auth.helper.ts
$ touch src/api/user/auth/auth.strategy.ts

Environment Variables

nest-cli.json
nest-cli.json
src/common/helper/env.helper.ts
src/common/envs/development.env

Alias ​​Paths

tsconfig.json
tsconfig.json

Configuration and Connect to Database (Postgres)

src/shared/typeorm/typeorm.service.ts
src/app.module.ts
src/app.module.ts
$ npm run start:dev

User Entity

src/api/user/user.entity.ts

AuthHelper Class

src/api/user/auth/auth.helper.ts

Guard

src/api/user/auth/auth.guard.ts

JWT Strategy

src/api/user/auth/auth.strategy.ts

Auth Service

src/api/user/auth/auth.service.ts
src/api/user/auth/auth.service.ts

Validation

src/api/user/auth/auth.dto.ts

Auth Controller

src/api/user/auth/auth.controller.ts
src/api/user/auth/auth.controller.ts

Auth Module

src/api/user/auth/auth.module.ts
src/api/user/auth/auth.module.ts

Validation

src/api/user/user.dto.ts

Service

src/api/user/user.service.ts
src/api/user/user.service.ts

Controller

src/api/user/user.controller.ts
src/api/user/user.controller.ts

Module

src/api/user/user.module.ts
src/api/user/user.module.ts

Leave a Comment