Creating a plug-and-play authentication system in NestJS means building a module that is:
- Self-contained
- Reusable across multiple apps or microservices
- Easy to configure (e.g., JWT secret, user model)
- Extendable (e.g., social login or OTP)
Let’s walk through this step by step with real-world logic explanations for each part.
Here we are not using any database connections or any custom logics, this is a basic setup where we can enhance it to meet the business needs.
1. Module Structure
auth/
├── auth.module.ts
├── auth.service.ts
├── auth.controller.ts
├── jwt.strategy.ts
├── local.strategy.ts
├── guards/
│ └── jwt-auth.guard.ts
├── dto/
│ └── login.dto.ts
├── interfaces/
│ └── user.interface.ts
2. JWT-Based Plug-and-Play Auth
auth.module.ts
Explanation:
- PassportModule allows plugging in various strategies (JWT, local, Google).
-
JwtModule registers the signing logic. -
JwtStrategy handles decoding and validating the token on each request.
auth.service.ts
Explanation:
-
validateUser() is where you hook your own DB or user service. -
login() creates the JWT token from the payload.
auth.controller.ts
Explanation:
- /auth/login accepts credentials and returns a signed JWT.
- This is a clean API endpoint that can be dropped into any NestJS app.
jwt.strategy.ts
Explanation:
- Extracts token from Authorization header.
- Validates the token and attaches the payload to request.user.
jwt-auth.guard.ts
Explanation:
- A simple wrapper to secure routes using JWT.
3. Securing Routes in Other Modules
any.controller.ts
Explanation:
- This route requires a valid JWT in the header.
- Returns the decoded user info (in real case, fetch from DB).
This is a simple POC plug and play auth made in nestjs. For the more customization keep adding the business flow.
Hope you find it helpful!