Skip to content

nabilrn/simplechatapp-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Express API Starter - Real-time Chat Backend

A modern Express.js backend application with real-time chat, authentication, and push notifications.

πŸ“¦ Tech Stack

  • Express.js 5.1.0 - Web framework
  • TypeScript 5.8.3 - Type safety
  • Sequelize 6.37.7 - ORM for MySQL
  • Socket.IO 4.8.1 - Real-time WebSocket
  • JWT 9.0.2 - Authentication
  • Google OAuth 2.0 - Social login
  • Firebase Cloud Messaging - Push notifications
  • Jest 30.2.0 - Testing framework
  • Swagger UI - API documentation

πŸš€ Features

Authentication

  • JWT-based login and registration
  • Google OAuth 2.0 integration
  • Refresh token mechanism
  • Secure password hashing with bcrypt

Real-time 1-on-1 Chat

  • WebSocket connections via Socket.IO
  • Real-time message delivery
  • Typing indicators
  • Online/offline presence tracking
  • Message status (sent/delivered/read)
  • Multi-device support

Chat REST API

  • Start or retrieve existing chat rooms
  • List all user chat rooms with last message
  • Paginated message history
  • Send text messages
  • Mark messages as read/delivered

Push Notifications

  • Firebase Cloud Messaging (FCM) integration
  • Device token management
  • Automatic offline message notifications
  • Invalid token cleanup

Testing & Documentation

  • Unit tests with Jest (25+ tests)
  • Swagger UI interactive documentation
  • Auto-generated API docs
  • 100% TypeScript type safety

πŸ“‹ Prerequisites

  • Node.js 18+ or 20+
  • MySQL 5.7+ or 8.0+
  • pnpm (recommended) or npm
  • Firebase project (for FCM)
  • Google Cloud project (for OAuth)

πŸ”§ Installation

1. Clone the repository

git clone https://github.com/nabilrn/express-api-starter.git
cd express-api-starter

2. Install dependencies

pnpm install
# or
npm install

3. Setup environment variables

Copy the example file and configure:

cp .env.example .env

Edit .env with your credentials:

# Server
PORT=3000

# Database
DB_HOST=127.0.0.1
DB_USER=root
DB_PASSWORD=your_password
DB_NAME=simplechatapp

# JWT (generate secure random strings)
JWT_SECRET=your_jwt_secret_min_32_chars
JWT_REFRESH_SECRET=your_refresh_secret_min_32_chars

# Google OAuth (from Google Cloud Console)
GOOGLE_CLIENT_ID=your_client_id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_CALLBACK_URL=http://localhost:3000/api/auth/google/callback

# Firebase (FCM Server Key from Firebase Console)
FCM_SERVER_KEY=your_fcm_server_key

# CORS
CLIENT_URL=http://localhost:3000

4. Setup database configuration

cp config/config.example.json config/config.json

Edit config/config.json with your MySQL credentials.

5. Create database

# Create MySQL database
mysql -u root -p
CREATE DATABASE simplechatapp;
exit;

6. Run migrations

npx sequelize-cli db:migrate

7. Start the server

# Development mode with auto-reload
pnpm dev

# Production mode
pnpm build
pnpm start

Server will run on http://localhost:3000

πŸ“˜ API Documentation

Access the interactive API documentation:

πŸ§ͺ Testing

# Run all tests
pnpm test

# Run tests with coverage
pnpm test -- --coverage

# Run tests in watch mode
pnpm test -- --watch

Google OAuth Setup

  1. Go to the Google Cloud Console
  2. Create a new project or select an existing one
  3. Enable the Google+ API
  4. Go to Credentials β†’ Create Credentials β†’ OAuth Client ID
  5. Configure the OAuth consent screen
  6. Add authorized redirect URI: http://localhost:3000/api/auth/google/callback
  7. Copy the Client ID and Client Secret to your .env file

API Endpoints

Authentication

POST /api/auth/register
- Register a new user
- Body: { username: string, email: string, password: string }

POST /api/auth/login
- Login with credentials
- Body: { email: string, password: string }

POST /api/auth/refresh
- Get new access token using refresh token
- Body: { refreshToken: string }

GET /api/auth/google
- Initiate Google OAuth flow

GET /api/auth/google/callback
- Google OAuth callback

Chat (Requires Authentication)

All chat endpoints require JWT token in Authorization header:

Authorization: Bearer <your_jwt_token>
POST /api/chats/start
- Start or get existing chat room
- Body: { targetUserId: number }

GET /api/chats
- Get all chat rooms for current user

GET /api/chats/:roomId/messages
- Get messages in a chat room
- Query: limit (optional), beforeMessageId (optional)

POST /api/chats/:roomId/messages
- Send a message
- Body: { message: string }

PUT /api/chats/:roomId/messages/:messageId/read
- Mark message as read

PUT /api/chats/:roomId/messages/delivered
- Mark messages as delivered

Push Notifications (Requires Authentication)

POST /api/notifications/device
- Register FCM device token
- Body: { token: string }

GET /api/notifications/device
- Get registered device tokens

DELETE /api/notifications/device
- Delete device token
- Body: { token: string }

πŸ”Œ Socket.IO Events

Connect with JWT token:

import io from 'socket.io-client';

const socket = io('http://localhost:3000', {
  auth: { token: 'your_jwt_token' }
});

// Join a chat room
socket.emit('room:join', { roomId: 1 });

// Send a message
socket.emit('message:send', { 
  roomId: 1, 
  message: 'Hello!' 
});

// Listen for new messages
socket.on('message:new', (data) => {
  console.log('New message:', data);
});

// Typing indicator
socket.emit('message:typing', { 
  roomId: 1, 
  isTyping: true 
});

// Mark message as read
socket.emit('message:read', { 
  roomId: 1, 
  messageId: 123 
});

// Listen for user online/offline
socket.on('user:online', (data) => {
  console.log('User online:', data.userId);
});

socket.on('user:offline', (data) => {
  console.log('User offline:', data.userId);
});

πŸ“‚ Project Structure

express-api-starter/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ __tests__/          # Jest unit tests
β”‚   β”œβ”€β”€ config/             # Database & Passport config
β”‚   β”œβ”€β”€ controllers/        # Route controllers
β”‚   β”œβ”€β”€ docs/               # Swagger YAML
β”‚   β”œβ”€β”€ middleware/         # Auth & validation
β”‚   β”œβ”€β”€ models/             # Sequelize models
β”‚   β”œβ”€β”€ modules/            # Feature modules
β”‚   β”‚   β”œβ”€β”€ chat/           # Chat service, routes
β”‚   β”‚   └── notification/   # FCM service, routes
β”‚   β”œβ”€β”€ routes/             # Express routes
β”‚   β”œβ”€β”€ socket/             # Socket.IO server & events
β”‚   β”œβ”€β”€ utils/              # Helpers & logger
β”‚   └── index.ts            # App entry point
β”œβ”€β”€ migrations/             # Database migrations
β”œβ”€β”€ config/                 # Sequelize config
β”œβ”€β”€ .env.example            # Environment variables template
└── README.md               # This file

πŸ› οΈ Development Commands

# Start development server with auto-reload
pnpm dev

# Build TypeScript
pnpm build

# Start production server
pnpm start

# Run tests
pnpm test

# Run tests with coverage
pnpm test -- --coverage

πŸ“Š Database Schema

Tables

  • users - User accounts
  • tokens - Refresh tokens
  • chat_rooms - Chat room metadata
  • chat_participants - Room-user relationships
  • messages - Chat messages
  • device_tokens - FCM device tokens

See migrations in migrations/ for complete schema.

πŸ“ License

MIT License - feel free to use this project for learning or production.


Built with ❀️ using Express.js, Socket.IO, and TypeScript

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors