Skip to content

ligerzero459/web-service-template

Repository files navigation

Web Service Backend Template

A production-ready Node.js/TypeScript web service backend template featuring user management, authentication, and session handling.

Features

  • Fastify - High-performance web framework
  • TypeScript - Type-safe development
  • Prisma - Database ORM with PostgreSQL
  • Redis - Session management with ephemeral tokens
  • BetterAuth - Authentication configuration
  • Joi - Request validation
  • Pino - High-performance logging
  • Jest - Testing framework with integration tests
  • Docker Compose - Development and test environments

Tech Stack

Component Technology
Web Framework Fastify
Language TypeScript
Database PostgreSQL
ORM Prisma
Cache/Sessions Redis
Authentication BetterAuth + Custom Session
Validation Joi
Logging Pino
Testing Jest
Containerization Docker

Prerequisites

  • Node.js 20.x or higher
  • Docker and Docker Compose
  • npm or yarn

Quick Start

1. Clone and Install

git clone <repository-url>
cd web-service-template
npm install

2. Environment Setup

Copy the example environment file and configure it:

cp .env.example .env

Edit .env with your settings:

NODE_ENV=development
PORT=3000
HOST=0.0.0.0
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/webservice? schema=public
REDIS_URL=redis://localhost:6379
AUTH_SECRET=your-super-secret-key-change-in-production
SESSION_TTL_MINUTES=60
LOG_LEVEL=info

3. Start Development Services

npm run start: dev

This command will:

  1. Start PostgreSQL and Redis containers
  2. Run database migrations
  3. Start the development server with hot reload

4. Stop Development Services

npm run stop:dev

Project Structure

project-root/
├── compose/
│   ├── docker-compose.dev.yml      # Development services
│   └── docker-compose.test.yml     # Test services + runner
├── src/
│   ├── config/
│   │   ├── index.ts                # Configuration loader
│   │   ├── database.ts             # Prisma client setup
│   │   ├── redis.ts                # Redis client setup
│   │   └── auth.ts                 # BetterAuth configuration
│   ├── middleware/
│   │   └── auth.ts                 # Authentication middleware
│   ├── routes/
│   │   ├── index.ts                # Route registration
│   │   ├── auth.routes.ts          # Auth routes
│   │   ├── user.routes.ts          # User management routes
│   │   └── health.routes.ts        # Health check routes
│   ├── schemas/
│   │   ├── auth.schema.ts          # Auth validation schemas
│   │   └── user.schema.ts          # User validation schemas
│   ├── services/
│   │   ├── auth.service.ts         # Authentication logic
│   │   ├── user.service.ts         # User management logic
│   │   └── session.service.ts      # Session management
│   ├── types/
│   │   └── index.ts                # TypeScript definitions
│   ├── utils/
│   │   └── logger.ts               # Pino logger setup
│   ├── app.ts                      # Fastify app setup
│   └── server. ts                   # Server entry point
├── prisma/
│   └── schema.prisma               # Database schema
├── tests/
│   ├── setup.ts                    # Jest setup
│   ├── helpers/
│   │   └── test-utils.ts           # Test utilities
│   └── integration/
│       ├── auth.test.ts            # Auth tests
│       ├── user. test.ts            # User tests
│       └── health.test.ts          # Health tests
├── .env.example                    # Environment template
├── .env.test                       # Test environment
├── Dockerfile                      # Multi-stage Dockerfile
├── package.json
├── tsconfig.json
└── README.md

API Reference

Health Endpoints

Method Endpoint Description
GET /health Basic health check
GET /health/ready Readiness probe (checks DB & Redis)
GET /health/live Liveness probe

Authentication Endpoints

Method Endpoint Auth Required Description
POST /auth/register No Register new user
POST /auth/login No Login user
POST /auth/logout Yes Logout current session
POST /auth/logout-all Yes Logout all sessions
POST /auth/change-password Yes Change password
GET /auth/me Yes Get current user

User Endpoints

Method Endpoint Auth Required Admin Only Description
GET /users/profile Yes No Get user profile
PUT /users/profile Yes No Update user profile
DELETE /users/profile Yes No Delete user account
GET /users Yes Yes List all users (paginated)
GET /users/:id Yes Yes Get user by ID
DELETE /users/:id Yes Yes Delete user by ID

Authentication

Session Tokens

  • Sessions are stored in Redis with a 60-minute TTL
  • Tokens are renewed automatically on each authenticated request
  • Pass the token in the Authorization header:
Authorization: Bearer <session-token>

Request Examples

Register

curl -X POST http://localhost:3000/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "securepassword123",
    "name": "John Doe"
  }'

Response:

{
  "success": true,
  "data": {
    "user": {
      "id": "uuid",
      "email": "user@example.com",
      "name": "John Doe",
      "role": "USER"
    },
    "token": "session-token"
  },
  "message": "User registered successfully"
}

Login

curl -X POST http://localhost:3000/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password":  "securepassword123"
  }'

Access Protected Route

curl -X GET http://localhost:3000/users/profile \
  -H "Authorization: Bearer <session-token>"

Update Profile

curl -X PUT http://localhost:3000/users/profile \
  -H "Authorization: Bearer <session-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Jane Doe"
  }'

Scripts

Script Description
npm run start:dev Start development environment
npm run stop:dev Stop development services
npm run build Build TypeScript to JavaScript
npm start Run production server
npm test Run tests in Docker
npm run test:local Run tests locally
npm run prisma:generate Generate Prisma client
npm run prisma:migrate Run database migrations
npm run lint Run ESLint
npm run clean Remove build artifacts

Testing

Run All Tests

npm test

This will:

  1. Start test PostgreSQL and Redis containers
  2. Run database migrations
  3. Execute Jest integration tests
  4. Clean up containers

Run Tests Locally

If you have services running locally:

npm run test:local

Test Coverage

Tests cover:

  • All authentication routes (register, login, logout, password change)
  • All user management routes (profile CRUD, admin operations)
  • All health check endpoints
  • Authorization middleware
  • Input validation
  • Error handling

Database

Schema

The database includes a User model with:

Field Type Description
id UUID Primary key
email String Unique email address
emailVerified Boolean Email verification status
passwordHash String Hashed password
name String? Optional display name
image String? Optional profile image URL
role Enum USER or ADMIN
createdAt DateTime Creation timestamp
updatedAt DateTime Last update timestamp

Migrations

Create a new migration:

npm run prisma:migrate -- --name <migration-name>

Apply migrations:

npm run prisma:migrate:deploy

Configuration

Environment Variables

Variable Description Default
NODE_ENV Environment mode development
PORT Server port 3000
HOST Server host 0.0.0.0
DATABASE_URL PostgreSQL connection string -
REDIS_URL Redis connection string redis://localhost:6379
AUTH_SECRET Secret key for authentication -
SESSION_TTL_MINUTES Session timeout in minutes 60
LOG_LEVEL Pino log level info

Production Deployment

Build

npm run build

Docker Production Image

docker build --target production -t web-service: latest .

Run Production Container

docker run -p 3000:3000 \
  -e DATABASE_URL=<your-database-url> \
  -e REDIS_URL=<your-redis-url> \
  -e AUTH_SECRET=<your-secret> \
  web-service:latest

Security Considerations

  1. Password Hashing: Passwords are hashed using SHA-256 with a random salt
  2. Timing-Safe Comparison: Password verification uses timing-safe comparison
  3. Session Management: Ephemeral sessions with automatic expiration
  4. Input Validation: All inputs validated with Joi schemas
  5. CORS: Configurable CORS settings
  6. Error Handling: Sanitized error messages in production

Production Checklist

  • Change AUTH_SECRET to a strong, unique value
  • Configure proper CORS origins
  • Enable HTTPS/TLS
  • Set NODE_ENV=production
  • Configure rate limiting
  • Set up monitoring and alerting
  • Enable email verification for registration
  • Review and adjust session TTL

Extending the Template

Adding New Routes

  1. Create route file in src/routes/
  2. Create validation schema in src/schemas/
  3. Create service in src/services/
  4. Register routes in src/routes/index.ts
  5. Add tests in tests/integration/

Adding New Models

  1. Update prisma/schema.prisma
  2. Run npm run prisma:migrate
  3. Create corresponding service and routes

License

MIT License

About

Fun LLM project to code basic user service with Postgres, Redis

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages