Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Logistics CMS Backend API

A high-performance, robust RESTful API built with Express.js (v5), TypeScript, and MongoDB (via Mongoose), optimized to run on the Bun runtime.


Key Features

  • Bun Runtime Integration: Super-fast execution, module resolution, and built-in hot reloading.
  • Premium Security: Protected by helmet, cors, and IP-based rate limiting via express-rate-limit.
  • Secure Authentication: Dual-token architecture (Access + Refresh JWT tokens via jose) with secure HTTP-only cookies.
  • Structural Validation: Request body validation using zod schemas prior to controller execution.
  • Database Seeds: Built-in seeding scripts for fast database initialization (services, leaders, page content, site settings).
  • Custom Logger: Automatic request logging with morgan and structured file/console logging with colorized severity highlights (chalk).
  • Containerization Ready: Complete Dockerfile and compose.yaml configuration for seamless local development and deployment.

Project Structure

backend/
├── src/
│   ├── server.ts                 # Application entrypoint & DB connection
│   ├── app.ts                    # Express application configuration & global middleware
│   └── app/
│       ├── config/               # DB connectivity & Environment configuration
│       ├── controllers/          # Request handlers & Business logic
│       ├── logs/                 # Persistent log files (app.log)
│       ├── middlewares/          # Custom middleware (auth validation, rate limiters)
│       ├── models/               # Mongoose schemas/models
│       ├── routes/               # API endpoint routing declarations
│       ├── schemas/              # Zod validation schemas
│       ├── seeds/                # Seed scripts for initial setup
│       ├── services/             # Core third-party integrations & operations
│       ├── types/                # Custom TypeScript type declarations
│       └── utils/                # Helper utilities (standard response wrappers, loggers)
├── dist/                         # Compiled JavaScript output
├── Dockerfile                    # Containerization setup
└── compose.yaml                  # Docker Compose configuration

Tech Stack & Dependencies

  • Runtime: Bun (v1.3.1 or higher)
  • Framework: Express (v5.x)
  • Language: TypeScript (target esnext, module nodenext)
  • Database: MongoDB (via Mongoose ODM)
  • Validation: Zod
  • Security & Utilities:
    • jose (JWT signing and verification)
    • bcryptjs (Password hashing)
    • cookie-parser (Cookie management)
    • cors & helmet (Security headers and CORS policy)
    • multer (File upload handling)
    • express-rate-limit (DDoS/Brute-force protection)
    • chalk & morgan (Rich logging)

Environment Variables

Copy the .env.example file to .env in the root of the backend folder and fill in the required details:

cp .env.example .env

Required Configuration Table

Variable Description Default / Example
NODE_ENV Runtime environment mode development
SAME_SITE Cookie SameSite attribute (lax, none, etc.) lax
PORT Listening port for the server 5000
CLIENT_URL Base URL of the client application http://localhost:3000
DB_USERNAME Database username your_username
DB_PASSWORD Database password your_password
DB_CLUSTER Database cluster domain cluster0.mongodb.net
DB_NAME Target MongoDB database name db_name
DB_APP_NAME MongoDB connection application name (appName) appname
ACCESS_TOKEN_SECRET Secret key for JWT Access Token generation Super secret key
ACCESS_TOKEN_EXPIRATION Expiry duration for Access Token 15m
REFRESH_TOKEN_SECRET Secret key for JWT Refresh Token generation Super secret key
REFRESH_TOKEN_EXPIRATION Expiry duration for Refresh Token 7d
HASH_SALT_ROUNDS Cryptographic salt rounds for password hashing 10

Getting Started

Prerequisites

  • Bun (Recommended) or Node.js (v18+):
    • Bun:
      • macOS/Linux: curl -fsSL https://bun.sh/install | bash
      • Windows (PowerShell): powershell -c "irm bun.sh/install.ps1 | iex"
    • Node.js:

Installation

  1. Navigate to the backend directory:
    cd backend
  2. Install dependencies:
    bun install
    # or
    npm install

Running the App

Development Mode

Runs the development server:

bun run dev
# or
npm run dev

Production Mode

Compiles/builds and starts the production server using Node.js:

npm run build
npm start

Database Seeding

To populate your database with initial mock data (Services, Leaders, Page Content, and Site Settings):

bun run seed
# or
npm run seed

Running with Docker

You can run the backend along with the entire environment using Docker:

  1. Start the Container:

    docker compose up --build

    This loads the .env file automatically and mounts the project workspace for active local development inside the container using bun dev.

  2. Stop the Container:

    docker compose down

API Endpoints Summary

All routes are prefixed with /api. Below are the primary endpoints and routing modules:

Authentication (/api/auth)

  • POST /api/auth/ — Verify active auth token
  • POST /api/auth/login — Login user (Zod validated; yields JWT HttpOnly cookie)
  • POST /api/auth/register — Register a new user (Zod validated)
  • POST /api/auth/logout — Logout user (Clears HttpOnly cookie)
  • POST /api/auth/refresh-access-token — Rotate Access/Refresh tokens

Users (/api/users)

  • Management endpoints for user profiles and roles.

Services (/api/services)

  • Operations related to the cargo shipping and logistics services provided by the Logistics Management System.

Site Settings (/api/site-settings)

  • Configuration routes for setting brand attributes like logo, headers, footer details, and social links.

Contacts & Quotes (/api/contact & /api/quote)

  • Submitting messages or request-for-quote operations for shipping and logistics services.

Page Content (/api/page-content)

  • Fetching and saving page sections (e.g., Privacy Policy, Terms, About page custom blocks).

Leaders (/api/leaders)

  • Operations to fetch and update details of company executive leaders.

Security & Performance Features

  • Rate Limiting: To prevent API abuse, individual endpoints restrict traffic to 10 requests per minute per IP under the current environment configuration.
  • CORS Handling: Cross-Origin Resource Sharing is configured to support requests from the environment-specified clientUrl and http://localhost:5173 (with support for credential transfer).
  • HTTP Security Headers: Powered by helmet to mitigate clickjacking, XSS, and MIME-sniffing vulnerabilities.
  • Global Error Handling: Unhandled routes and throw exceptions are caught gracefully, delivering structured error responses.

Custom Logging System

Logs are automatically categorized:

  • Development: Dev logs print directly to standard output with beautiful colors depending on the log severity.
  • Production: Combined requests are printed via morgan to standard output.
  • Log Files: All exceptions, errors, warnings, and success events are recorded in src/app/logs/app.log formatted with active ISO-8601 timestamps.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages