Understanding a NestJS Authentication App for an Express.js Developer

Understanding a NestJS Authentication App for an Express.js Developer


Express Dot JS developer understanding the Nest JS Verification app

If you are coming from the Express Dot JS world, where everything is a bit “manual” and you have to wire routes, middleware and controllers, Nest Jay can feel like stepping into a world where everything is already organized for you. Think about a DIY furniture kit to completely move to the furnaced apartment. Let’s break this Nest JS verification app and compare how you usually create a basic crude app in Express.com.

Understanding a NestJS Authentication App for an Express.js Developer



Enrollment point

Express. JS:
In the express, you will usually start from one app.js Or server.js File where you start the app, set the middleware, and explain the routes.

const express = require('express');
const app = express();

app.use(express.json());

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => console.log('Server running on port 3000'));
Enter the full screen mode

Exit the full screen format

Nest JS:
In the Nest JS, the Entry Point is main.ts. This is the place where the app is bootstream, and the global structures such as middleware or pipes are applied.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
Enter the full screen mode

Exit the full screen format

Comparison:

  • In the express, you manually compile like middleware body-parser.
  • In Nest J., you use decoration and global pipes ValidationPipe To automatically handle verification and change.


Routing

Express. JS:
In the express, you directly describe your way app.js Or divide them into the root files.

const express = require('express');
const router = express.Router();

router.get('/users', (req, res) => {
  res.send('Get all users');
});

router.post('/users', (req, res) => {
  res.send('Create a user');
});

module.exports = router;
Enter the full screen mode

Exit the full screen format

Nest JS:
In the Nest J, the routes are appreciated in controllers using decoration @ControllerFor, for, for, for,. @GetAnd @Post.

import { Controller, Get, Post, Body } from '@nestjs/common';

@Controller('users') // Base route: /users
export class UsersController {
  @Get()
  getAllUsers() {
    return 'Get all users';
  }

  @Post()
  createUser(@Body() body: any) {
    return `Create a user with data: ${JSON.stringify(body)}`;
  }
}
Enter the full screen mode

Exit the full screen format

Comparison:

  • In the express, the routes are the functions associated with http methods (app.getFor, for, for, for,. app.post,
  • In Nest J, there are ways in a class, and decoration describes the HTTP procedures and paths.


Middleware

Express. JS:
The middleware in the Express is a function that processes requests before reaching the Root Handler.

const logger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
};

app.use(logger);
Enter the full screen mode

Exit the full screen format

Nest JS:
The same is the same in Nest J, but it is implemented as a class or function and applied globally or on specific routes.

import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    console.log(`${req.method} ${req.url}`);
    next();
  }
}
Enter the full screen mode

Exit the full screen format

Comparison:

  • In the Express, the middleware is just one function.
  • In Nest J, the middleware can be a class, which can give it more structure and re -establishment.


Controllers and services

Express. JS:
In the Express, you can handle everything in the Route Handler or divide the logic into separate files.

app.post('/auth/register', async (req, res) => {
  const { username, password } = req.body;
  // Hash password, save user to DB, etc.
  res.send('User registered');
});
Enter the full screen mode

Exit the full screen format

Nest JS:
In Nest J, controllers handle routes, but the original logic has been moved Services For a better separation of concerns.

// auth.controller.ts
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @Post('register')
  async register(@Body() body: any) {
    return this.authService.register(body.username, body.password);
  }
}

// auth.service.ts
import { Injectable } from '@nestjs/common';

@Injectable()
export class AuthService {
  async register(username: string, password: string) {
    // Hash password, save user to DB, etc.
    return 'User registered';
  }
}
Enter the full screen mode

Exit the full screen format

Comparison:

  • In the Express, you can combine root handling and business logic in the same file.
  • In Nest J, the controller handles routing, and services handle business logic, which makes the code more modular and testing.


Database Integration

Express. JS:
In the Express, you will use your root handlers or Orm such as mangoes in a separate model file.

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  username: String,
  password: String,
});

const User = mongoose.model('User', UserSchema);

app.post('/auth/register', async (req, res) => {
  const user = new User(req.body);
  await user.save();
  res.send('User registered');
});
Enter the full screen mode

Exit the full screen format

Nest JS:
In Nest JS, you use @Nest J/Mangoz to explain the schemes and inject models in services.

// user.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class User extends Document {
  @Prop({ required: true })
  username: string;

  @Prop({ required: true })
  password: string;
}

export const UserSchema = SchemaFactory.createForClass(User);

// users.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User } from './schemas/user.schema';

@Injectable()
export class UsersService {
  constructor(@InjectModel(User.name) private userModel: Model<User>) {}

  async create(username: string, password: string) {
    const user = new this.userModel({ username, password });
    return user.save();
  }
}
Enter the full screen mode

Exit the full screen format

Comparison:

  • In the Express, you use the Mangoes model directly in your route handlers.
  • In Nest J, the code is clean and more testing, models are injected into services.


Confirmation

Express. JS:
In the express, you’ll use like a middleware passport Or manually verify JWT token.

const jwt = require('jsonwebtoken');

const authMiddleware = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')(1);
  if (!token) return res.status(401).send('Unauthorized');

  try {
    const decoded = jwt.verify(token, 'secret');
    req.user = decoded;
    next();
  } catch {
    res.status(401).send('Unauthorized');
  }
};

app.get('/protected', authMiddleware, (req, res) => {
  res.send(`Hello ${req.user.username}`);
});
Enter the full screen mode

Exit the full screen format

Nest JS:
In Nest J, you use guards and strategies to handle confirmation.

// jwt.strategy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secret',
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}

// jwt-auth.guard.ts
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

// auth.controller.ts
@UseGuards(JwtAuthGuard)
@Get('protected')
getProtected(@Request() req) {
  return `Hello ${req.user.username}`;
}
Enter the full screen mode

Exit the full screen format

Comparison:

  • In the express, you manually verify the token in the middleware.
  • In Nest J, the guards and strategies handle the verification, which is more reusable and proclaimed.


Confirmation

Express. JS:
In the express, you’ll use like a library joi Or verify the inputs manually.

const Joi = require('joi');

const schema = Joi.object({
  username: Joi.string().required(),
  password: Joi.string().min(8).required(),
});

app.post('/auth/register', (req, res) => {
  const { error } = schema.validate(req.body);
  if (error) return res.status(400).send(error.details(0).message);

  res.send('User registered');
});
Enter the full screen mode

Exit the full screen format

Nest JS:
In Nest JS, verification is used class-validator And class-transformer.

import { IsString, MinLength } from 'class-validator';

export class RegisterDto {
  @IsString()
  username: string;

  @IsString()
  @MinLength(8)
  password: string;
}

// auth.controller.ts
@Post('register')
async register(@Body() registerDto: RegisterDto) {
  return this.authService.register(registerDto.username, registerDto.password);
}
Enter the full screen mode

Exit the full screen format

Comparison:

  • In the express, you manually verify the input using libraries.
  • In Nest J, the announcement of the authentication and the DTOs is connected to the (data transfer object).


Final views 😊

Nest is like Express Dot J on JS Steroids. It takes care of a lot of boiler plate and enforces clean, modular structures. Although the Express gives you the freedom to work in your own way, Nest JS provides a framework that attracts you to the best ways.

If the Express is an empty canvas, the nestjas are painted by number cut. Both let you create beautiful art, but Nest JS ensures that you are on the lines. And hey, who doesn’t like a small structure in their life? 🎨😉😂😉🎨 🎨😉😂😉🎨

You can check my article about the construction of Nest JS Verification API with Mango DB and JWT: a phased guide

Farewell

Unlock Your Business Potential with Stan Jackowski Designs

At Stan Jackowski Designs, we bring your ideas to life with cutting-edge creativity and innovation. Whether you need a customized website, professional digital marketing strategies, or expert SEO services, we’ve got you covered! Our team ensures your business, ministry, or brand stands out with high-performing solutions tailored to your needs.

🚀 What We Offer:

  • Web Development – High-converting, responsive, and optimized websites
  • Stunning Design & UI/UX – Eye-catching visuals that enhance engagement
  • Digital Marketing – Creative campaigns to boost your brand presence
  • SEO Optimization – Increase visibility, traffic, and search rankings
  • Ongoing Support – 24/7 assistance to keep your website running smoothly

🔹 Take your business to the next level! Explore our outstanding services today:
Stan Jackowski Services

📍 Located: South of Chicago

📞 Contact Us: https://www.stanjackowski.com/contact

💡 Bonus: If you’re a ministry, church, or non-profit organization, we offer specialized solutions, including website setup, training, and consultation to empower your online presence. Book a FREE 1-hour consultation with Rev. Stanley F. Jackowski today!

🔥 Looking for a done-for-you autoblog website? We specialize in creating money-making autoblog websites that generate passive income on autopilot. Let us handle the technical details while you focus on growth!

📩 Let’s Build Something Amazing Together! Contact us now to get started.

Share:

Facebook
Twitter
Pinterest
LinkedIn

Most Popular

Daily Newsletter

Get all the top stories from Blogs
to keep track.

Social Media

Facebook
Twitter
LinkedIn
WhatsApp
Tumblr