The Node Authentication Template is a robust, secure, and feature-rich authentication system built with Node.js and TypeScript. It provides a complete authentication solution with advanced security features including email verification, password reset, two-factor authentication (2FA), rate limiting, and more. This template is designed to be easily integrated into any Node.js project requiring secure user authentication.
Node.js TypeScript Express.js PostgreSQL Prisma JWT bcrypt 2FA Nodemailer Google APIs Zod dotenv ESLint Nodemon
- Node.js
- TypeScript
- Express.js
- PostgreSQL
- Prisma ORM
Authentication & Security:
- jsonwebtoken: JWT implementation for token-based authentication
- bcryptjs: Password hashing library
- speakeasy & qrcode: TOTP-based two-factor authentication
- express-rate-limit: API rate limiting to prevent abuse
- sanitize-html: Input sanitization to prevent XSS attacks
Email Services:
- nodemailer: Email sending functionality
- googleapis: Google OAuth2 integration for email services
Validation:
- zod: Schema validation and type checking
Development Tools:
- dotenv: Environment variable management
- eslint: Code linting
- prisma: ORM and database migration tool
- nodemon: Automatic server restarts during development
- ts-node: TypeScript execution environment
Create a .env file in the root directory with the following variables:
# Server Configurations PORT= API_VERSION= BASE_URL= # App Configurations SALT_ROUNDS= # Database Configurations DATABASE_URL= #JWT Configurations JWT_SECRET= JWT_REFRESH_SECRET= # Email Configurations CLIENT_ID= CLIENT_SECRET= REFRESH_TOKEN= USER_EMAIL= REDIRECT_URI=
-
Clone the repository
git clone https://github.com/KhaledSaeed18/node-authentication-template.git cd node-authentication-template -
Install dependencies with Yarn
yarn install
-
Set up environment variables
- Create a
.envfile in the root directory - Add all required environment variables as described in the section above
- Create a
Run the server in development mode with hot-reloading:
yarn dev
-
Build the application
yarn build
-
Start the production server
yarn start
-
Apply database migrations
yarn prisma migrate dev
-
Generate Prisma client
yarn prisma generate
The project follows a modular architecture for better organization and maintainability:
βββ .gitignore βββ eslint.config.mjs βββ package.json βββ prisma β βββ schema.prisma βββ src β βββ api β β βββ auth β β βββ auth.controller.ts β β βββ auth.rateLimiting.ts β β βββ auth.routes.ts β β βββ auth.service.ts β β βββ auth.validation.ts β βββ constants β β βββ auth.constants.ts β β βββ emailTemplates.ts β βββ index.ts β βββ mails β β βββ email.ts β β βββ nodemailer.config.ts β βββ middlewares β β βββ authorization.middleware.ts β β βββ error.middleware.ts β β βββ sanitizeBody.middleware.ts β β βββ securityHeaders.middleware.ts β βββ utils β βββ errorHandler.ts β βββ generateOTP.ts β βββ generateTokens.ts β βββ totp.ts βββ tsconfig.json βββ yarn.lock
- api/auth: Contains all authentication-related logic
- constants: Application-wide constants and configurations
- mails: Email service implementation
- middlewares: Express middlewares for security and request processing
- utils: Utility functions for common operations
POST /api/v1/auth/signup: Register a new user- Required fields: firstName, lastName, email, password
- Creates user and sends verification email
POST /api/v1/auth/verify-email: Verify email with OTP- Required fields: email, code (6-digit)
POST /api/v1/auth/resend-verification: Resend verification code- Required fields: email
POST /api/v1/auth/signin: User login- Required fields: email, password
- Returns JWT tokens and user info
- Handles 2FA if enabled
POST /api/v1/auth/refresh-token: Refresh access token- Required fields: refreshToken
- Returns new access token
GET /api/v1/auth/login-history: Get user login history- Protected route (requires authorization)
- Returns list of login attempts with device info
POST /api/v1/auth/forgot-password: Initiate password reset- Required fields: email
- Sends password reset code via email
POST /api/v1/auth/reset-password: Reset password with code- Required fields: email, code, newPassword
POST /api/v1/auth/2fa/setup: Set up 2FA- Protected route
- Returns QR code and secret for TOTP apps
POST /api/v1/auth/2fa/verify: Verify and enable 2FA- Protected route
- Required fields: token (6-digit TOTP code)
POST /api/v1/auth/2fa/signin: Complete login with 2FA- Required fields: email, password, token
POST /api/v1/auth/2fa/disable: Disable 2FA- Protected route
- Required fields: token (6-digit TOTP code)
- Strong password requirements with complexity validation
- Bcrypt hashing with configurable salt rounds
- Common password detection and prevention
- Rate limiting on all authentication endpoints
- CORS protection with configurable allowed origins
- Security headers (CSP, HSTS, XSS Protection, etc.)
- Input sanitization to prevent XSS attacks
- Short-lived JWT access tokens (20 minutes)
- Longer-lived refresh tokens (7 days)
- Login anomaly detection with IP, device tracking