Skip to content

AhmadCoderX/node-express-postgres-prisma-starter-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Node.js Backend Starter Template

A comprehensive Node.js backend starter template with authentication, database management, and essential utilities. Built with TypeScript, Express.js, Prisma ORM, and JWT authentication.

Features

  • 🔐 JWT Authentication - Complete auth system with login, register, password reset
  • 👥 User Management - Role-based access control with admin, user, manager, moderator roles
  • 📧 Email Integration - Welcome emails and password reset functionality
  • 🔔 Push Notifications - Firebase integration for device notifications
  • 📊 Database Management - Prisma ORM with PostgreSQL support
  • 📝 API Documentation - Swagger/OpenAPI integration
  • 🛡️ Security - Password hashing, OTP verification, input validation
  • 📱 Device Token Management - Support for web, Android, iOS notifications
  • 🔍 Audit Logging - Track all user actions and changes
  • 🚀 Production Ready - Error handling, logging, and deployment configurations

Tech Stack

  • Runtime: Node.js
  • Framework: Express.js
  • Language: TypeScript
  • Database: PostgreSQL with Prisma ORM
  • Authentication: JWT (JSON Web Tokens)
  • Email: Nodemailer with EJS templates
  • Notifications: Firebase Admin SDK
  • Documentation: Swagger/OpenAPI
  • File Upload: Multer
  • Validation: Custom validation utilities

Quick Start

Prerequisites

  • Node.js (v18 or higher)
  • PostgreSQL database
  • npm or yarn

Installation

  1. Clone the repository

    git clone <repository-url>
    cd nodejs-backend-starter
  2. Install dependencies

    npm install
  3. Environment Setup

    cp .env.example .env

    Update the .env file with your configuration:

    DATABASE_URL="postgresql://username:password@localhost:5432/database_name"
    JWT_SECRET="your-super-secret-jwt-key"
    EMAIL_HOST="smtp.gmail.com"
    EMAIL_PORT=587
    EMAIL_USER="your-email@gmail.com"
    EMAIL_PASS="your-app-password"
    FIREBASE_PROJECT_ID="your-firebase-project-id"
    FIREBASE_PRIVATE_KEY="your-firebase-private-key"
    FIREBASE_CLIENT_EMAIL="your-firebase-client-email"
  4. Database Setup

    npm run db:migrate
    npm run db:generate
  5. Start Development Server

    npm run dev

The server will start on http://localhost:5000

API Documentation

Once the server is running, visit http://localhost:5000/api-docs to view the interactive API documentation.

Project Structure

src/
├── controllers/          # Request handlers
│   └── auth.controller.ts # Authentication logic
├── middlewares/          # Express middlewares
│   ├── auth.middleware.ts # JWT authentication
│   └── role.middleware.ts # Role-based access control
├── routes/              # API routes
│   ├── auth.ts          # Authentication routes
│   └── index.ts         # Main router
├── utils/               # Utility functions
│   ├── appError.ts      # Custom error handling
│   ├── catchAsync.ts    # Async error wrapper
│   ├── email.ts         # Email service
│   ├── firebase.ts      # Firebase configuration
│   ├── generateCode.ts  # Code generation utilities
│   ├── globalErrorHandler.ts # Global error handler
│   ├── helpers.ts       # Helper functions
│   ├── notification.ts  # Push notification service
│   ├── otpUtils.ts      # OTP generation and validation
│   ├── passwordUtils.ts # Password validation
│   └── prisma.ts        # Database connection
├── templates/           # Email templates
├── constants/           # Application constants
└── index.ts            # Application entry point

API Endpoints

Authentication

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - User login
  • POST /api/auth/change-password - Change password
  • POST /api/auth/request-password-reset - Request password reset
  • POST /api/auth/verify-otp - Verify OTP for password reset
  • POST /api/auth/reset-password/:token - Reset password with token

User Management

  • GET /api/auth/users - Get all users (with pagination)
  • GET /api/auth/users/:id - Get user by ID
  • PUT /api/auth/users/:id - Update user
  • DELETE /api/auth/users/:id - Delete user (soft delete)
  • PATCH /api/auth/users/:id/activate - Activate user
  • PATCH /api/auth/users/:id/deactivate - Deactivate user
  • PATCH /api/auth/users/:id/change-role - Change user role

Device Tokens

  • POST /api/auth/device-token - Save device token for notifications
  • DELETE /api/auth/device-token - Remove device token

User Roles

  • ADMIN: Full access to all features
  • MANAGER: Can manage users and view all data
  • MODERATOR: Limited management capabilities
  • USER: Basic user access

Environment Variables

Variable Description Required
DATABASE_URL PostgreSQL connection string Yes
JWT_SECRET Secret key for JWT signing Yes
EMAIL_HOST SMTP server host Yes
EMAIL_PORT SMTP server port Yes
EMAIL_USER SMTP username Yes
EMAIL_PASS SMTP password/app password Yes
FIREBASE_PROJECT_ID Firebase project ID Yes
FIREBASE_PRIVATE_KEY Firebase private key Yes
FIREBASE_CLIENT_EMAIL Firebase client email Yes
PORT Server port (default: 5000) No

Database Schema

The starter template includes these core models:

  • User: User accounts with roles and authentication
  • OTP: One-time passwords for password reset
  • DeviceToken: Device tokens for push notifications
  • AuditLog: Audit trail for all user actions

Customization

Adding New Roles

  1. Update the UserRole enum in prisma/schema.prisma
  2. Update role validation in auth.controller.ts
  3. Add role-specific middleware if needed

Adding New Features

  1. Create new controllers in src/controllers/
  2. Add routes in src/routes/
  3. Update the main router in src/routes/index.ts
  4. Add database models in prisma/schema.prisma

Email Templates

Email templates are located in src/templates/ using EJS format. You can customize:

  • welcome-email.ejs - Welcome email template
  • password-reset-otp.ejs - OTP email template
  • password-reset-success.ejs - Password reset success template

Scripts

  • npm run dev - Start development server
  • npm run build - Build for production
  • npm start - Start production server
  • npm run db:migrate - Run database migrations
  • npm run db:generate - Generate Prisma client
  • npm run db:studio - Open Prisma Studio
  • npm run db:reset - Reset database

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

License

ISC License - see LICENSE file for details

Support

For questions and support, please open an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published