A comprehensive Node.js server built with TypeScript, featuring authentication, file upload, and PostgreSQL integration.
- 🔐 JWT Authentication - Secure token-based authentication
- 🍪 Session Management - Express sessions with cookie support
- 📁 File Upload - Single and multiple file upload with validation
- 🗄️ PostgreSQL Database - With Knex.js query builder and migrations
- 🎨 EJS Templates - Server-side rendering with Bootstrap UI
- 🛡️ Security - Helmet, CORS, rate limiting, bcrypt password hashing
- ⚡ TypeScript - Full TypeScript support with strict typing
- 🔄 Middleware - Custom authentication and validation middleware
- 📊 Logging - Morgan HTTP request logger
- 🗜️ Compression - Gzip compression for better performance
- Node.js (v16 or higher)
- PostgreSQL (v12 or higher)
- npm or yarn
-
Clone and install dependencies:
npm install
-
Database Setup:
- Make sure PostgreSQL is running
- Create a database named
demo - Update
.envfile with your database credentials
-
Environment Variables: Copy
.env.exampleto.envand update the values:NODE_ENV=development PORT=3000 DB_HOST=localhost DB_PORT=5432 DB_USER=minhquang DB_PASSWORD=123456 DB_NAME=demo JWT_SECRET=your-super-secret-jwt-key SESSION_SECRET=your-super-secret-session-key -
Run Database Migrations:
npm run migrate
-
Start the Server:
# Development npm run dev # Production npm run build npm start
POST /api/auth/register- Register a new userPOST /api/auth/login- Login userPOST /api/auth/logout- Logout userPOST /api/auth/refresh-token- Refresh JWT tokenGET /api/auth/me- Get current user profile
GET /api/users- Get all users (paginated, requires auth)GET /api/users/:id- Get user by ID (requires auth)PUT /api/users/:id- Update user profile (requires auth)DELETE /api/users/:id- Delete user (requires auth)POST /api/users/:id/avatar- Upload user avatar (requires auth)
POST /api/upload/single- Upload single file (requires auth)POST /api/upload/multiple- Upload multiple files (requires auth)GET /api/upload/file/:filename- Get uploaded fileDELETE /api/upload/file/:filename- Delete uploaded file (requires auth)
src/
├── config/
│ └── database.ts # Database configuration
├── controllers/
│ ├── AuthController.ts # Authentication logic
│ ├── UserController.ts # User management
│ └── UploadController.ts # File upload handling
├── middleware/
│ ├── auth.ts # Authentication middleware
│ ├── errorHandler.ts # Global error handler
│ └── validation.ts # Request validation
├── migrations/
│ └── 20240101000001_create_users_table.ts
├── models/
│ └── User.ts # User model
├── routes/
│ ├── authRoutes.ts # Authentication routes
│ ├── userRoutes.ts # User routes
│ └── uploadRoutes.ts # Upload routes
├── types/
│ └── index.ts # TypeScript type definitions
└── server.ts # Main server file
id- Primary keyusername- Unique usernameemail- Unique email addresspassword- Bcrypt hashed passwordfirst_name- Optional first namelast_name- Optional last nameavatar- Optional avatar image pathis_active- Account statuscreated_at- Timestampupdated_at- Timestamp
- Password Hashing: bcrypt with salt rounds
- JWT Tokens: Secure token-based authentication
- Session Management: Express sessions with secure cookies
- Rate Limiting: Prevent brute force attacks
- CORS Protection: Cross-origin resource sharing control
- Helmet Security: Security headers
- Input Validation: Joi schema validation
- File Upload Security: MIME type validation and size limits
curl -X POST http://localhost:3000/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"email": "test@example.com",
"password": "password123",
"firstName": "Test",
"lastName": "User"
}'curl -X POST http://localhost:3000/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "test@example.com",
"password": "password123"
}'curl -X POST http://localhost:3000/api/upload/single \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-F "file=@/path/to/your/image.jpg"npm run dev- Start development server with nodemonnpm run build- Build TypeScript to JavaScriptnpm start- Start production servernpm run migrate- Run database migrationsnpm run migrate:rollback- Rollback last migrationnpm run migrate:make <name>- Create new migration
| Variable | Description | Default |
|---|---|---|
NODE_ENV |
Environment mode | development |
PORT |
Server port | 3000 |
DB_HOST |
Database host | localhost |
DB_PORT |
Database port | 5432 |
DB_USER |
Database username | minhquang |
DB_PASSWORD |
Database password | 123456 |
DB_NAME |
Database name | demo |
JWT_SECRET |
JWT signing secret | Required |
JWT_EXPIRES_IN |
JWT expiration time | 7d |
SESSION_SECRET |
Session signing secret | Required |
MAX_FILE_SIZE |
Max upload file size | 5242880 (5MB) |
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License.