Express 5 User Register API (Production Ready)
Step-by-step guide to build a secure user registration API using Express 5 (Node.js 22 LTS) and MongoDB. This documentation focuses on real-world project structure: full server setup, proper folder organization, schema design, request validation, password hashing, duplicate user prevention, JWT token generation, and clean error handling. Ideal for beginners who want production-quality code, not just theory.
Install Required Dependencies
Install all essential packages needed for a real authentication system. Express handles routing, Mongoose connects MongoDB, bcrypt secures passwords, Zod validates inputs, and jsonwebtoken generates authentication tokens.
Main Server Setup
This is the entry point of the backend application. It initializes Express, connects MongoDB, enables JSON parsing, and registers authentication routes. This file should always stay clean and minimal.
User Model (MongoDB Schema)
Defines how user data is stored in MongoDB. Email and username are unique to prevent duplicate accounts. Passwords are stored in hashed form only. Timestamps help track account creation and updates.
Authentication Routes
Defines API endpoints related to authentication. Routes only handle HTTP paths and delegate logic to controllers, keeping code clean and scalable.
Register Controller Logic
Handles the full registration flow: input validation using Zod, duplicate user checks, secure password hashing with bcrypt, user creation, and JWT token generation. Returns meaningful HTTP status codes for frontend usage.
Related Documents
MongoDB & Mongoose Hot Reload Safety in Next.js (TypeScript)
In Next.js development mode, hot reloading can cause Mongoose models and database connections to be recreated multiple times. While MongoDB collections themselves are persistent, improper connection and model handling can lead to model overwrite errors, unexpected collection creation, and unstable schemas. This documentation explains the correct production-ready pattern to cache MongoDB connections and safely reuse Mongoose models in Next.js using TypeScript.