Skip to main content

Prerequisites

Before you begin, ensure you have the following installed on your system:

Node.js 18+

JavaScript runtime

PostgreSQL 16+

Relational database

Docker (Optional)

For containerized PostgreSQL
1

Clone the Repository

First, clone the Platform API repository to your local machine:
git clone https://github.com/LeonardoCaero/platform-api.git
cd platform-api
2

Install Dependencies

Install all required npm packages:
npm install
This will install the following key dependencies:
  • Express.js 5.2 - Web framework
  • Prisma 7.2 - Database ORM
  • TypeScript 5.9 - Type-safe development
  • Zod 4.2 - Schema validation
  • jsonwebtoken 9.0 - JWT authentication
  • bcryptjs 3.0 - Password hashing
  • Winston 3.19 - Logging
3

Configure Environment Variables

Copy the example environment file and configure it:
cp .env.example .env
Open .env and update the configuration:
.env
# PostgreSQL Configuration
POSTGRES_USER=caero
POSTGRES_PASSWORD=change_me_strong_password
POSTGRES_DB=caero_db

# API Configuration
NODE_ENV=development
PORT=4000

# JWT Secrets (generate with: openssl rand -base64 48)
JWT_SECRET=change_me_jwt_secret_min_32_chars
JWT_EXPIRES_IN=15m
REFRESH_TOKEN_SECRET=change_me_refresh_secret_min_32_chars
REFRESH_TOKEN_EXPIRES_IN=7d

# Invite Expiry Settings
COMPANY_INVITE_EXPIRY_HOURS=72
MEMBER_INVITE_EXPIRY_HOURS=168

# Frontend API URL (optional)
VITE_API_URL=http://localhost:4000/api
Security: Always generate strong, unique secrets for production environments. Never commit your .env file to version control.
Generate secure random secrets using:
openssl rand -base64 48
4

Start PostgreSQL Database

You can start PostgreSQL using Docker or your local installation:If you have Docker installed, start PostgreSQL with:
docker-compose up -d
This will start a PostgreSQL container with the credentials from your .env file.

Using Local PostgreSQL

If you have PostgreSQL installed locally, ensure it’s running and create a database:
# Connect to PostgreSQL
psql -U postgres

# Create database
CREATE DATABASE caero_db;

# Grant privileges
GRANT ALL PRIVILEGES ON DATABASE caero_db TO caero;
Make sure the database credentials in your .env file match your PostgreSQL setup.
5

Initialize Database

Run the database migrations and seed initial data:
npm run db:rebuild
This command performs the following actions:
  1. Drops all existing tables (force reset)
  2. Pushes the Prisma schema to the database
  3. Runs the seed script to populate initial data
db:rebuild will delete all existing data. Use this only for initial setup or when you want a fresh database.

Alternative: Non-destructive Migration

For production or when preserving data, use:
npx prisma db push
6

Start the Development Server

Launch the API server with hot reload:
npm run dev
The server will start on the configured port (default: http://localhost:4000).You should see output similar to:
Server is running on port 4000
Database connected successfully
The development server uses tsx watch which automatically restarts when you make changes to the code.
7

Verify Health Check

Test that the API is running correctly:
curl http://localhost:4000/health
You should receive a response indicating the API is healthy:
{
  "status": "ok",
  "timestamp": "2024-03-04T10:30:00.000Z"
}
8

Make Your First API Call

Let’s register a new user account:
curl -X POST http://localhost:4000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "fullName": "John Doe",
    "password": "SecurePass123",
    "phone": "+1234567890"
  }'
Success response:
{
  "success": true,
  "data": {
    "user": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "email": "[email protected]",
      "fullName": "John Doe",
      "phone": "+1234567890",
      "avatar": null,
      "emailVerified": false,
      "createdAt": "2024-03-04T10:30:00.000Z"
    },
    "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refreshToken": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6..."
  }
}
Save the accessToken and refreshToken for subsequent API calls.

Available Scripts

The Platform API includes several npm scripts for development and deployment:
# Start development server with hot reload
npm run dev

Testing Your Setup

Now that your API is running, let’s test the complete authentication flow:

1. Register a User

curl -X POST http://localhost:4000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "fullName": "Test User",
    "password": "TestPassword123"
  }'

2. Login

curl -X POST http://localhost:4000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "TestPassword123"
  }'

3. Get User Profile

Using the access token from registration or login:
curl http://localhost:4000/api/auth/me \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

4. Refresh Token

curl -X POST http://localhost:4000/api/auth/refresh \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -d '{
    "refreshToken": "YOUR_REFRESH_TOKEN"
  }'

5. Logout

curl -X POST http://localhost:4000/api/auth/logout \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -d '{
    "refreshToken": "YOUR_REFRESH_TOKEN"
  }'

Project Structure

Understanding the project structure will help you navigate the codebase:
platform-api/
├── src/
│   ├── app.ts                 # Express app configuration
│   ├── main.ts                # Server bootstrap and startup
│   ├── routes.ts              # Main route registry
│   ├── common/                # Shared utilities and middleware
│   │   ├── errors/            # Custom error classes
│   │   ├── logger/            # Winston logger configuration
│   │   ├── middlewares/       # Auth and validation middleware
│   │   └── utils/             # Helper functions (JWT, tokens, async)
│   ├── config/                # Environment configuration
│   ├── db/                    # Prisma client instance
│   └── modules/               # Feature modules
│       └── auth/              # Authentication module
│           ├── controllers/   # Request handlers
│           ├── services/      # Business logic
│           ├── schemas/       # Zod validation schemas
│           └── routes/        # Route definitions
├── prisma/
│   ├── schema.prisma          # Database schema
│   └── seed.ts                # Database seed script
├── .env.example               # Environment variables template
├── package.json               # Project dependencies
├── tsconfig.json              # TypeScript configuration
└── docker-compose.yml         # Docker services configuration

Common Issues

If port 4000 is already in use, change the PORT variable in your .env file:
.env
PORT=3000
Then restart the server.
Verify that:
  1. PostgreSQL is running: docker ps (for Docker) or pg_isready (for local)
  2. Database credentials in .env are correct
  3. Database exists: psql -U postgres -l
  4. Network connectivity: telnet localhost 5432
If you encounter Prisma schema errors:
# Generate Prisma Client
npx prisma generate

# Format schema
npx prisma format

# Validate schema
npx prisma validate
Ensure your JWT_SECRET and REFRESH_TOKEN_SECRET are at least 32 characters long. Generate new secrets:
openssl rand -base64 48

Next Steps

Authentication Guide

Learn about JWT authentication, refresh tokens, and security best practices

API Reference

Explore all available endpoints and their parameters

Database Schema

Deep dive into the database structure and relationships

Deployment

Deploy your Platform API to production

Build docs developers (and LLMs) love