A modern, type-safe REST API server for AuroraMart, an e-commerce platform built with Express.js, TypeScript, and PostgreSQL.
AuroraMart Server is a fully-featured backend API for an e-commerce platform. It provides:
- User Authentication & Authorization - Register, login, logout with session management
- Role-based Access Control - Support for Customer, Seller, and Manager roles
- User Management - Retrieve user profiles and manage user data
- Session Management - PostgreSQL-backed session storage
- Type Safety - 100% TypeScript implementation
- Input Validation - Zod schema validation for all requests
- Error Handling - Centralized error handling middleware
- CORS Support - Cross-origin resource sharing enabled
- Vercel Ready - Configured for deployment on Vercel
- Runtime: Node.js (ESM modules)
- Framework: Express.js 5.x
- Language: TypeScript 6.x
- Database: PostgreSQL
- Validation: Zod
- Authentication: Express Session + bcryptjs
- CORS: cors
- Session Store: connect-pg-simple
- Development: tsx watch, tsc-alias
src/
βββ index.ts # Server entry point, middleware setup
βββ config/
β βββ db.ts # PostgreSQL connection pool
β βββ env.ts # Environment variable configuration
βββ controllers/
β βββ auth.controller.ts # Authentication logic (register, login, logout, profile)
βββ middlewares/
β βββ authorize.ts # Role-based authorization middleware
β βββ errorHandler.ts # Global error handling middleware
β βββ validateData.ts # Request data validation middleware
βββ routes/
β βββ index.ts # Route mounting configuration
β βββ auth.routes.ts # Authentication routes
βββ schemas/
β βββ env.ts # Environment variable schema (Zod)
β βββ user.ts # User data schema (Zod)
βββ types/
β βββ express.d.ts # Express type augmentation for sessions
β βββ index.ts # API response types
β βββ user.ts # User interface types
βββ utils/
βββ error.ts # Custom error classes
βββ password.ts # Password hashing and comparison
dist/ # Compiled JavaScript (generated)
package.json
tsconfig.json
vercel.json # Vercel deployment config
- Node.js 18+ or higher
- npm or yarn package manager
- PostgreSQL 12+ database
- A
.envfile with required environment variables
-
Clone the repository
git clone https://github.com/programmerrakibul/aurora-mart-server.git cd aurora-mart-server -
Install dependencies
npm install
-
Create
.envfilecp .env.example .env
(Or create manually - see Environment Variables section)
-
Set up the database
Ensure PostgreSQL is running and the database specified in
.envexists:CREATE DATABASE aurora_mart;
The application will automatically create the
user_sessiontable on first run.
Create a .env file in the root directory with the following variables:
# Server
NODE_ENV=development
PORT=3000
# Database
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=your_password
DB_NAME=aurora_mart
# Session
SESSION_SECRET=your_secret_key_here_change_in_productionImportant Notes:
NODE_ENVcan bedevelopment,production, ortestSESSION_SECRETshould be a strong, random string in production- All variables are validated on startup using Zod schema
npm run devThe server will start with hot-reload enabled on the port specified in .env
(default: 3000).
npm run build
npm startnpm run build
node dist/index.jsThe server will output:
PostgreSQL connected!
Welcome to Aurora Mart API!
Server running at http://localhost:3000
http://localhost:3000/api/v1
- Endpoint:
POST /auth/register - Authentication: None
- Request Body:
{ "name": "John Doe", "email": "john@example.com", "password": "SecurePass123!", "gender": "Male", "photoURL": "https://example.com/photo.jpg" } - Response (201):
{ "success": true, "message": "User created successfully!", "data": { "uid": "550e8400-e29b-41d4-a716-446655440000" } } - Validation Rules:
name: 3-150 charactersemail: Valid email format, 1-255 characterspassword: Min 6 chars, at least 1 uppercase, 1 lowercase, 1 number, 1 special charactergender: "Male" or "Female"photoURL: Valid URL (optional, defaults to example image)
- Endpoint:
POST /auth/login - Authentication: None
- Request Body:
{ "email": "john@example.com", "password": "SecurePass123!" } - Response (200):
{ "success": true, "message": "Login successful!" } - Sets: Secure session cookie (
aurora_sid) - Returns: 401 Unauthorized if credentials are invalid
- Endpoint:
GET /auth/profile - Authentication: Required (any logged-in user)
- Response (200):
{ "success": true, "message": "User profile fetched successfully!", "data": { "uid": "550e8400-e29b-41d4-a716-446655440000", "name": "John Doe", "email": "john@example.com", "gender": "Male", "role": "CUSTOMER", "photoURL": "https://example.com/photo.jpg", "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:00Z" } }
- Endpoint:
GET /auth/all-users - Authentication: None
- Response (200):
{ "success": true, "message": "All users fetched successfully!", "total": 5, "data": [ { "uid": "550e8400-e29b-41d4-a716-446655440000", "name": "John Doe", "email": "john@example.com", "gender": "Male", "role": "CUSTOMER", "photoURL": "https://example.com/photo.jpg", "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:00Z" } ] } - Sorting: By creation date (newest first), then by name
- Endpoint:
POST /auth/logout - Authentication: Required
- Response (200):
{ "success": true, "message": "Logout successful!" } - Effect: Destroys the user's session
- Endpoint:
GET / - Response (200):
{ "success": true, "message": "Welcome to Aurora Mart API!" }
The server uses Express Session with PostgreSQL backend for session management:
- Sessions are stored in the
user_sessiontable - Session cookies are HTTP-only and secure (in production)
- Session cookie name:
aurora_sid - Session max age: 30 days
- Automatic table creation on first run
// Without login - 403 Forbidden
GET /api/v1/auth/profile
// With login session - 200 OK
GET /api/v1/auth/profile
Cookie: aurora_sid=...PostgreSQL connection is managed through a connection pool with the following settings:
- Driver: pg (Node.js PostgreSQL client)
- Connection Pool: Automatic pooling
- Credentials: From
.envfile - Error Handling: Auto-reconnect on pool errors
CREATE TABLE users (
uid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(150) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
gender VARCHAR(10) NOT NULL,
role VARCHAR(20) DEFAULT 'CUSTOMER',
photoURL VARCHAR(255),
createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);Created automatically by connect-pg-simple:
CREATE TABLE user_session (
sid VARCHAR PRIMARY KEY,
sess JSONB NOT NULL,
expire TIMESTAMP NOT NULL
);npm run buildOutputs compiled files to dist/ directory with:
- JavaScript compilation (ESM modules)
- TypeScript declaration files
- Source maps
- Path alias resolution
The project is configured for Vercel deployment:
-
Push to GitHub
git push origin main
-
Deploy on Vercel
- Connect your GitHub repository to Vercel
- Vercel automatically detects
vercel.json - Environment variables are set in Vercel dashboard
- Build command:
npm run vercel-build - Start command:
node dist/index.js
-
Environment Variables on Vercel
Set the same
.envvariables in Vercel project settings:NODE_ENV=productionDB_HOST,DB_PORT,DB_USER,DB_PASSWORD,DB_NAMESESSION_SECRET(strong random value)
| Script | Description |
|---|---|
npm run dev |
Start development server with auto-reload |
npm run build |
Compile TypeScript to JavaScript |
npm run start |
Run compiled production build |
npm run clean |
Remove dist/ directory |
npm run vercel-build |
Build script for Vercel deployment |
β
Type-Safe: Full TypeScript implementation
β
Validated Input: Zod schema validation for all requests
β
Secure Passwords: bcryptjs hashing with salt rounds
β
Session Management: PostgreSQL-backed sessions
β
Error Handling: Centralized error middleware with custom error classes
β
CORS Enabled: Cross-origin requests supported
β
ESM Modules: Modern JavaScript module system
β
Production Ready: Configured for Vercel deployment
β
Auto-Generated Sessions: Tables created automatically on startup
- Check database connection credentials in
.env - Ensure PostgreSQL is running
- Verify database exists
- Ensure all required
.envvariables are set - Check
src/schemas/env.tsfor required fields - Verify variable format matches schema
- Ensure client domain is allowed in CORS configuration
- Default: All origins allowed in development
- Check PostgreSQL connection
- Verify
user_sessiontable exists - Ensure
SESSION_SECRETis set - Check browser cookie settings
For issues or questions, please create an issue in the repository.