This repository is an advanced version of the original NestJS GraphQL Foundation, extended with real-time WebSocket features (chat, notifications, subscriptions) on top of the core GraphQL foundation.
A comprehensive, production-ready NestJS GraphQL foundation with advanced authentication, security, and enterprise-grade features. Built with PostgreSQL, TypeORM, GraphQL, JWT authentication, refresh tokens, role-based access control, audit logging, real-time chat, notifications, file uploads, and analytics via WebSockets and GraphQL subscriptions.
- NestJS - Progressive Node.js framework
- GraphQL - Query language with Apollo Server
- TypeORM - ORM for TypeScript with migration support
- PostgreSQL - Relational database
- JWT - Access and refresh token authentication
- bcrypt - Password hashing
- Winston - Logging library
- Nodemailer - Email service for password reset and verification
- Socket.IO - Real-time chat and notifications
- Cloudinary - Cloud-based image storage and optimization
- TypeScript - Type safety
- π JWT Authentication (Access + Refresh Tokens)
- π Token Refresh Mechanism
- π‘οΈ Role-Based Access Control (Admin/User)
- π Hashed Passwords with bcrypt
- π§ Password Reset via Email (Secure token-based reset)
- βοΈ Email Service Integration (Nodemailer with Gmail)
- π Pagination Support (GraphQL queries with pagination)
- π§Ή Soft Delete Support (e.g., cities)
- π§Ύ Request Logging - Winston logger with file output
- π Audit Logging - User activity tracking for security and compliance
- π GraphQL API - Type-safe queries and mutations with Apollo Server
- π Database Integration - PostgreSQL with TypeORM
- π Database Migrations - Version control for database schema
- π― Type Safety - Full TypeScript support
- π§ͺ Comprehensive Testing - Unit tests, E2E tests, and test coverage
- π¬ Real-Time Chat - Chat rooms, messaging, and subscriptions
- π Notifications - User notifications, unread count, mark as read, and real-time updates
- π File Upload - Cloudinary integration with image optimization
- π Analytics Dashboard - User growth, activity stats, and insights
- π³ Payments - Stripe integration (optional branch)
- π GraphQL Playground - Interactive GraphQL query interface
- β‘ Production Ready - Error handling, validation, and security best practices
Core foundation with essential features:
- Authentication & Security
- Real-time Chat & Notifications
- File Uploads (Cloudinary)
- Analytics Dashboard
- Production-ready setup
Complete foundation + Stripe payments integration:
# To use payments version
git checkout feature/payments
# or merge into your project
git merge feature/paymentsgit clone https://github.com/saadamir1/nestjs-graphql-realtime-foundation.git
cd nestjs-graphql-realtime-foundation
npm installCREATE USER dev WITH PASSWORD 'secret';
CREATE DATABASE demo OWNER dev;
GRANT ALL PRIVILEGES ON DATABASE demo TO dev;Copy and configure environment:
cp .env.example .env
# Edit .env with your actual valuesRequired environment variables:
# Database
DB_HOST=127.0.0.1
DB_PORT=5432
DB_USERNAME=dev
DB_PASSWORD=secret
DB_NAME=demo
# JWT
JWT_SECRET=jwt-secret-key
JWT_EXPIRES_IN=900s
JWT_REFRESH_SECRET=jwt-refresh-secret
JWT_REFRESH_EXPIRES_IN=7d
# Email Configuration (for password reset and email verification)
EMAIL_USER=[email protected]
EMAIL_PASS=your-gmail-app-password
FRONTEND_URL=http://localhost:3001
# Cloudinary (for file uploads)
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret
# Stripe (only in payments branch)
STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key
STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_publishable_keynpm run migration:runnpm run start:devLocal Development:
- GraphQL Playground:
http://localhost:3000/graphql - GraphQL API:
http://localhost:3000/graphql
This backend is designed to be used with a separate React frontend. You can:
- Use the companion React frontend:
nestjs-graphql-realtime-frontend - Build your own custom frontend
- Connect any GraphQL-compatible frontend framework
WebSocket Connection:
// Frontend WebSocket connection example
import io from 'socket.io-client';
const socket = io('http://localhost:3000', {
auth: {
token: 'your-jwt-token'
}
});
// Listen for real-time messages
socket.on('messageAdded', (message) => {
console.log('New message:', message);
});Access the interactive GraphQL playground at http://localhost:3000/graphql to:
- Explore the schema
- Write and test queries/mutations
- View documentation
- Test authentication
# Bootstrap Admin (First time setup)
mutation {
bootstrapAdmin(
bootstrapInput: {
email: "[email protected]"
password: "admin123"
firstName: "Admin"
lastName: "User"
}
) {
access_token
refresh_token
}
}
# Login
mutation {
login(loginInput: { email: "[email protected]", password: "admin123" }) {
access_token
refresh_token
}
}
# Refresh Token
mutation {
refreshToken(refreshTokenInput: { refreshToken: "YOUR_REFRESH_TOKEN" }) {
access_token
refresh_token
}
}{
"Authorization": "Bearer YOUR_ACCESS_TOKEN"
}# Get current user
query {
me {
id
email
firstName
lastName
role
}
}
# Get all users (Admin only)
query {
users {
id
email
firstName
lastName
role
isEmailVerified
}
}# Get all cities with pagination
query {
cities(filter: { page: 1, limit: 10 }) {
data {
id
name
description
country
active
}
total
page
lastPage
}
}
# Create a city
mutation {
createCity(
createCityInput: {
name: "New York"
description: "The Big Apple"
country: "USA"
}
) {
id
name
description
country
}
}# Send password reset email
mutation {
forgotPassword(forgotPasswordInput: { email: "[email protected]" }) {
message
}
}
# Reset password with token
mutation {
resetPassword(
resetPasswordInput: {
token: "reset-token-from-email"
newPassword: "newSecurePassword123"
}
) {
message
}
}
# Send email verification
mutation {
sendEmailVerification(emailVerificationInput: { email: "[email protected]" }) {
message
}
}
# Resend email verification (for expired tokens)
mutation {
resendEmailVerification(emailVerificationInput: { email: "[email protected]" }) {
message
}
}
# Verify email with token
mutation {
verifyEmail(verifyEmailInput: { token: "verification-token-from-email" }) {
message
}
}# Upload profile picture
mutation {
uploadProfilePicture(file: $file)
}
# Upload general image
mutation {
uploadImage(file: $file)
}# Dashboard stats
query {
dashboardStats {
totalUsers
totalMessages
totalNotifications
recentUsers {
email
firstName
}
}
}
# User growth data
query {
userGrowth(days: 30) {
date
count
}
}# Create chat room
mutation {
createRoom(createRoomInput: { name: "General", participantIds: [1, 2] }) {
id
name
participantIds
}
}
# Get notifications
query {
myNotifications {
id
type
title
message
read
}
}
# Subscribe to new messages
subscription {
messageAdded {
id
content
senderId
roomId
}
}# Create payment intent
mutation {
createPaymentIntent(createPaymentInput: {
amount: 29.99
description: "Premium subscription"
}) {
clientSecret
paymentIntentId
}
}
# Get user payments
query {
myPayments {
id
amount
status
description
createdAt
}
}src/
βββ auth/ # Authentication (GraphQL resolvers)
βββ users/ # User management (GraphQL resolvers)
βββ cities/ # Cities CRUD example (GraphQL resolvers)
βββ chat/ # Real-time chat functionality
βββ notifications/ # User notifications system
βββ upload/ # File upload with Cloudinary
βββ analytics/ # Dashboard and user insights
βββ payments/ # Stripe integration (payments branch only)
βββ websockets/ # WebSocket gateway
βββ common/ # Guards, decorators, middleware, services
β βββ services/ # Email, Audit, Cloudinary services
β βββ entities/ # Audit log entity
β βββ guards/ # JWT, Roles, GraphQL guards
β βββ middleware/ # Logger middleware
βββ migrations/ # Database migrations
βββ data-source.ts # TypeORM CLI configuration
βββ schema.gql # Auto-generated GraphQL schema
βββ main.ts
# Create version tags
git tag -a v1.0.0 -m "Core foundation release"
git tag -a v1.1.0 -m "Added file uploads and analytics"
git push origin --tagsThis foundation is production-ready and can be used for:
- SaaS Applications - Complete user management and real-time features
- E-commerce Platforms - With payments branch for transactions
- Social Platforms - Chat, notifications, file uploads
- Analytics Dashboards - Built-in user insights and growth tracking
- Starter Kit Sales - Commercial foundation ($200-500+ value)
- Fork the repository
- Create feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'feat: add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open Pull Request
Happy Coding! π
- Enterprise-Grade Foundation - Production-ready architecture
- Modular Design - Optional payments branch for flexibility
- Real-time Features - WebSockets, chat, notifications
- File Management - Cloudinary integration with optimization
- Analytics Built-in - Dashboard stats and user insights
- 100% TypeScript - Full type safety
- Comprehensive Testing - Unit tests and E2E coverage
- Database Migrations - Version-controlled schema changes
nestjs graphql realtime websockets chat notifications file-upload analytics payments stripe cloudinary jwt-auth typescript production-ready