A comprehensive, production-ready backend for an AI-powered blog website built with Express.js, PostgreSQL, Prisma ORM, and modern security practices.
- User Authentication & Authorization: JWT-based auth with role-based access control
- Blog Management: Full CRUD operations with approval workflow
- Comment System: Threaded comments with real-time notifications
- Admin Panel: Comprehensive dashboard for content moderation
- AI Services: Title suggestions, tag generation, SEO optimization
- File Uploads: Image management with validation and optimization
- Notifications: Real-time user notifications system
- Helmet.js: Security headers and CSP configuration
- Rate Limiting: API rate limiting with configurable thresholds
- Input Validation: Comprehensive request validation using express-validator
- CORS Protection: Configurable CORS policies
- JWT Authentication: Secure token-based authentication
- Password Hashing: Bcrypt-based password security
- PostgreSQL: Robust relational database
- Prisma ORM: Type-safe database operations
- Migrations: Database schema management
- Relationships: Complex data relationships with cascading operations
- Runtime: Node.js with Express.js
- Database: PostgreSQL with Prisma ORM
- Authentication: JWT with bcrypt
- Validation: express-validator
- Security: Helmet.js, rate limiting
- File Uploads: Multer with validation
- TypeScript: Full type safety
- Environment: Configurable via .env files
- Node.js 18+
- PostgreSQL 12+
- pnpm (recommended) or npm
git clone <repository-url>
cd blog-ai
pnpm installCopy the environment template and configure your settings:
cp env.example .envEdit .env with your configuration:
# Database
DATABASE_URL="postgresql://username:password@localhost:5432/aiblog_db?schema=public"
# JWT Configuration
JWT_SECRET="your-super-secret-jwt-key-change-in-production"
JWT_EXPIRES_IN="7d"
JWT_REFRESH_SECRET="your-super-secret-refresh-key-change-in-production"
JWT_REFRESH_EXPIRES_IN="30d"
# Server Configuration
PORT=8080
NODE_ENV="development"# Generate Prisma client
npx prisma generate
# Run database migrations
npx prisma migrate dev
# (Optional) Seed database with sample data
npx prisma db seedpnpm devThe server will start on http://localhost:8080
- User: Authentication, profiles, roles, social links
- Blog: Content, status workflow, analytics
- Comment: Threaded comments with user associations
- Notification: User notifications system
- BlogAnalytics: Performance metrics and tracking
- AISuggestion: AI-generated content suggestions
- Users can create multiple blogs
- Blogs have threaded comments
- Notifications track user activities
- Analytics track blog performance
- AI suggestions are user-specific
POST /register- User registrationPOST /login- User loginPOST /refresh- Token refreshGET /me- Get current user profilePUT /me- Update user profilePUT /change-password- Change passwordDELETE /me- Delete account
GET /- List blogs with filtering and paginationGET /:identifier- Get blog by ID or slugPOST /- Create new blogPUT /:id- Update blogDELETE /:id- Delete blogPUT /:id/status- Admin: Update blog statusPOST /:id/like- Like/unlike blogGET /trending- Get trending blogsGET /categories- Get blog categoriesGET /tags- Get blog tags
GET /blog/:blogId- Get comments for a blogPOST /- Create new commentPUT /:id- Update commentDELETE /:id- Delete commentGET /user/:userId- Get user's commentsGET /:id/replies- Get comment replies
GET /stats- Dashboard statisticsGET /users- List all usersPUT /users/:id/role- Update user rolePUT /users/:id/block- Block/unblock userDELETE /users/:id- Delete userGET /blogs/pending- Get pending blogsPOST /blogs/bulk-action- Bulk blog actionsGET /analytics- System analyticsGET /health- System health check
GET /- Get user notificationsGET /unread-count- Get unread countPUT /:id/read- Mark notification as readPUT /read-all- Mark all as readDELETE /:id- Delete notificationDELETE /read- Delete read notifications
POST /suggest-title- Generate title suggestionsPOST /suggest-tags- Generate tag suggestionsPOST /generate-seo- Generate SEO metadataPOST /summarize-content- Content summarizationPOST /improve-readability- Readability improvementsGET /history- Get AI suggestion history
POST /image- Upload single imagePOST /images- Upload multiple imagesPOST /blog-cover- Upload blog cover imagePOST /avatar- Upload user avatarDELETE /:filename- Delete uploaded fileGET /my-files- Get user's files
- JWT-based authentication with refresh tokens
- Role-based access control (User/Admin)
- Password hashing with bcrypt
- Token expiration and validation
- Rate limiting to prevent abuse
- Input validation and sanitization
- CORS configuration
- Security headers with Helmet.js
- SQL injection prevention via Prisma
- File type validation
- File size limits
- Secure filename generation
- Path traversal prevention
# Create initial migration
npx prisma migrate dev --name init
# Apply migrations
npx prisma migrate deploy# After schema changes
npx prisma migrate dev --name update_description
# Generate updated client
npx prisma generate# Run tests
pnpm test
# Run tests with coverage
pnpm test:coverage
# Run tests in watch mode
pnpm test:watchEnsure all production environment variables are set:
- Strong JWT secrets
- Production database URL
- Proper CORS origins
- Rate limiting configuration
- Use production PostgreSQL instance
- Configure connection pooling
- Set up automated backups
- Monitor performance
- Enable HTTPS
- Configure proper CORS origins
- Set up monitoring and logging
- Regular security updates
- Use cloud storage (AWS S3, Google Cloud Storage)
- Configure CDN for performance
- Implement proper access controls
server/
โโโ lib/ # Utility libraries
โ โโโ auth.ts # Authentication utilities
โ โโโ database.ts # Database connection
โ โโโ validation.ts # Request validation
โ โโโ utils.ts # General utilities
โโโ routes/ # API route handlers
โ โโโ auth.ts # Authentication routes
โ โโโ blogs.ts # Blog management
โ โโโ comments.ts # Comment system
โ โโโ admin.ts # Admin panel
โ โโโ notifications.ts # Notification system
โ โโโ ai.ts # AI services
โ โโโ upload.ts # File uploads
โโโ index.ts # Main server file
โโโ node-build.ts # Production build
shared/
โโโ api.ts # Shared TypeScript interfaces
prisma/
โโโ schema.prisma # Database schema
โโโ migrations/ # Database migrations
RATE_LIMIT_WINDOW_MS=900000 # 15 minutes
RATE_LIMIT_MAX_REQUESTS=100 # Max requests per windowMAX_FILE_SIZE=5242880 # 5MB in bytes
ALLOWED_FILE_TYPES=image/* # Allowed MIME typesDATABASE_URL="postgresql://..."
DATABASE_POOL_SIZE=10 # Connection pool size/healthendpoint for system status- Database connection monitoring
- Response time tracking
- Global error handler
- Structured error responses
- Error logging and monitoring
- Database query optimization
- Response caching strategies
- Load balancing considerations
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Create an issue in the repository
- Check the documentation
- Review the API endpoints
- Real-time Features: WebSocket integration for live updates
- Advanced AI: Integration with OpenAI, Claude, or other AI services
- Analytics: Advanced analytics and reporting
- Caching: Redis integration for performance
- Search: Full-text search with Elasticsearch
- Email: Newsletter and notification emails
- Social: Social media integration
- Mobile: Mobile app API endpoints
Built with โค๏ธ for the AI Blog Community