Skip to content

CodeGuide-dev/codeguide-starter-expressjs

Repository files navigation

CodeGuide Starter Express.js

A production-ready Express.js starter kit with TypeScript, Drizzle ORM, Better Auth, and Docker. This starter kit follows modern best practices and provides a solid foundation for building scalable web applications.

πŸš€ Features

  • Express.js 4 - Fast, unopinionated, minimalist web framework
  • TypeScript - Type safety and enhanced developer experience
  • Drizzle ORM - Modern TypeScript ORM with automatic migrations
  • Better Auth - Complete authentication solution with OAuth support
  • PostgreSQL - Reliable and powerful database
  • Docker - Containerization for easy deployment
  • Security - Built-in security middleware and best practices
  • Testing - Jest testing framework with example tests
  • Logging - Structured logging with Winston
  • Validation - Request validation with Joi
  • Error Handling - Comprehensive error handling middleware
  • API Documentation - Interactive Swagger UI with OpenAPI 3.0 spec

πŸ“‹ Prerequisites

  • Node.js 18+
  • npm 8+ or yarn 1.22+
  • Docker and Docker Compose
  • PostgreSQL (if running locally without Docker)

πŸ› οΈ Quick Start

1. Clone the repository

git clone <repository-url>
cd codeguide-starter-expressjs

2. Install dependencies

npm install

3. Set up environment variables

cp .env.example .env

Edit the .env file with your configuration:

# Server Configuration
PORT=3000
NODE_ENV=development

# Database Configuration
DATABASE_URL=postgresql://postgres:password@localhost:5432/codeguide_starter

# Authentication Configuration
BETTER_AUTH_SECRET=your-super-secret-key-here
BETTER_AUTH_URL=http://localhost:3000

# Social Providers (Optional)
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret

# Security
CORS_ORIGIN=http://localhost:3000

4. Start the development server

Option A: With Docker (Recommended)

# Start PostgreSQL with Docker
docker-compose -f docker-compose.dev.yml up -d

# Run database migrations
npm run db:migrate

# Start the development server
npm run dev

Option B: Local PostgreSQL

# Make sure PostgreSQL is running and accessible
# Run database migrations
npm run db:migrate

# Start the development server
npm run dev

The application will be available at http://localhost:3000.

πŸ“ Project Structure

codeguide-starter-expressjs/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ controllers/          # Request handlers
β”‚   β”‚   β”œβ”€β”€ authController.ts
β”‚   β”‚   └── userController.ts
β”‚   β”œβ”€β”€ middleware/           # Custom middleware
β”‚   β”‚   β”œβ”€β”€ auth.ts
β”‚   β”‚   β”œβ”€β”€ cors.ts
β”‚   β”‚   β”œβ”€β”€ errorHandler.ts
β”‚   β”‚   β”œβ”€β”€ logger.ts
β”‚   β”‚   β”œβ”€β”€ security.ts
β”‚   β”‚   └── validation.ts
β”‚   β”œβ”€β”€ routes/              # Route definitions
β”‚   β”‚   β”œβ”€β”€ index.ts
β”‚   β”‚   β”œβ”€β”€ authRoutes.ts
β”‚   β”‚   └── userRoutes.ts
β”‚   β”œβ”€β”€ services/            # Business logic
β”‚   β”‚   └── userService.ts
β”‚   β”œβ”€β”€ models/              # Database models
β”‚   β”‚   β”œβ”€β”€ db.ts
β”‚   β”‚   └── schema.ts
β”‚   β”œβ”€β”€ types/               # TypeScript types
β”‚   β”‚   └── index.ts
β”‚   β”œβ”€β”€ config/              # Configuration files
β”‚   β”‚   β”œβ”€β”€ auth.ts
β”‚   β”‚   └── auth-client.ts
β”‚   β”œβ”€β”€ utils/               # Utility functions
β”‚   β”‚   β”œβ”€β”€ password.ts
β”‚   β”‚   └── response.ts
β”‚   β”œβ”€β”€ schemas/             # Validation schemas
β”‚   β”‚   └── userSchemas.ts
β”‚   β”œβ”€β”€ app.ts               # Express app setup
β”‚   └── healthcheck.ts       # Health check utility
β”œβ”€β”€ tests/                   # Test files
β”‚   β”œβ”€β”€ setup.ts
β”‚   β”œβ”€β”€ health.test.ts
β”‚   β”œβ”€β”€ auth.test.ts
β”‚   └── users.test.ts
β”œβ”€β”€ docker/                  # Docker configuration
β”‚   └── init.sql
β”œβ”€β”€ drizzle/                 # Drizzle migrations
β”‚   └── migrations/
β”œβ”€β”€ package.json
β”œβ”€β”€ tsconfig.json
β”œβ”€β”€ jest.config.js
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ docker-compose.dev.yml
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ drizzle.config.ts
β”œβ”€β”€ .env.example
└── README.md

πŸ—„οΈ Database Management

Drizzle ORM

This project uses Drizzle ORM for type-safe database operations.

Schema Management

The database schema is defined in src/models/schema.ts and includes:

  • Users - User accounts with roles and status
  • Sessions - Authentication sessions
  • Accounts - OAuth provider accounts
  • Verification Tokens - Email verification tokens

Development Database Setup

The project includes scripts to manage a PostgreSQL development container using environment variables from your .env file:

# Start PostgreSQL development container
npm run db:dev

# Show database connection information
npm run db:info

# Stop PostgreSQL development container
npm run db:dev:stop

Environment Variables Used:

  • DB_HOST - Database host (default: localhost)
  • DB_PORT - Database port (default: 5432)
  • DB_NAME - Database name (default: codeguide_starter)
  • DB_USER - Database user (default: postgres)
  • DB_PASSWORD - Database password (default: postgres)
  • CONTAINER_NAME - Docker container name (default: express-postgres-dev)

Database Commands

# Generate migration files from schema changes
npm run db:generate

# Run migrations
npm run db:migrate

# Push schema changes directly (development only)
npm run db:push

# Open Drizzle Studio for database management
npm run db:studio

πŸ“– API Documentation

This project includes comprehensive OpenAPI 3.0 documentation with an interactive Swagger UI.

Accessing Documentation

Important: API documentation is only available in development mode for security and performance reasons.

Once the development server is running (npm run dev), you can access:

  • Swagger UI: http://localhost:3000/api-docs - Interactive API documentation
  • OpenAPI Spec: http://localhost:3000/v3/api-docs - Raw API specification

In production mode, the documentation endpoints are disabled and will return 404.

Features

  • Interactive Testing: Test API endpoints directly from your browser
  • Authentication Support: Try protected endpoints with Google OAuth or session auth
  • Request/Response Examples: See example requests and responses
  • Schema Validation: Automatic request/response schema validation
  • Comprehensive Documentation: All endpoints are fully documented

Quick Start

# Start the development server (required for documentation)
npm run dev

# Or use the documentation script
npm run docs

Then visit http://localhost:3000/api-docs to explore the API.

Note: Documentation is only available when NODE_ENV=development (default for npm run dev).

For detailed information, see docs/API_DOCUMENTATION.md.

πŸ” Authentication

Better Auth provides a complete authentication solution with support for:

  • Email/password authentication
  • OAuth providers (GitHub, Google, etc.)
  • Session management
  • Email verification
  • Password reset

Authentication Endpoints

All Better Auth endpoints are available at /api/auth/*:

  • POST /api/auth/sign-up - Register new user
  • POST /api/auth/sign-in - Sign in with email/password
  • POST /api/auth/sign-out - Sign out
  • GET /api/auth/session - Get current session
  • POST /api/auth/reset-password - Request password reset
  • GET /api/auth/verify-email - Verify email address

Protected Routes

Use the authMiddleware to protect routes:

import { authMiddleware } from '@/middleware/auth';

router.get('/protected', authMiddleware, (req, res) => {
  // req.user is available here
  res.json({ user: req.user });
});

Admin Routes

Use the adminMiddleware for admin-only routes:

import { adminMiddleware } from '@/middleware/auth';

router.post('/admin-only', adminMiddleware, (req, res) => {
  // Only users with 'admin' role can access this
  res.json({ message: 'Admin access granted' });
});

πŸ“Š API Documentation

Health Check

  • GET /health - Application health status
  • GET /api - API information and endpoints

User Management

  • GET /api/users - Get paginated list of users (public)
  • GET /api/users/me - Get current user profile (protected)
  • GET /api/users/:id - Get user by ID (protected)
  • PUT /api/users/:id - Update user (protected)
  • DELETE /api/users/:id - Delete user (admin only)

Response Format

All API responses follow this format:

{
  "success": true,
  "message": "Operation successful",
  "data": {},
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 100,
    "totalPages": 10
  }
}

πŸ§ͺ Testing

The project includes a comprehensive test suite using Jest.

Running Tests

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

Test Structure

  • Unit tests for services and utilities
  • Integration tests for API endpoints
  • Authentication flow tests
  • Error handling tests

🐳 Docker Deployment

Development

# Start development environment with PostgreSQL
docker-compose -f docker-compose.dev.yml up -d

Production

# Build and start production containers
docker-compose up -d

Docker Commands

# Build the application image
docker build -t codeguide-starter .

# Run the container
docker run -p 3000:3000 codeguide-starter

πŸ”§ Development Scripts

# Development
npm run dev          # Start development server with hot reload
npm run build        # Build for production
npm run start        # Start production server

# Database
npm run db:dev       # Start development PostgreSQL container
npm run db:dev:stop  # Stop development PostgreSQL container
npm run db:info      # Show database connection information
npm run db:generate  # Generate migrations
npm run db:migrate   # Run migrations
npm run db:push      # Push schema changes
npm run db:studio    # Open Drizzle Studio

# Testing
npm test             # Run tests
npm run test:watch   # Watch mode
npm run test:coverage # Coverage report

# Code Quality
npm run lint         # Run ESLint
npm run lint:fix     # Fix linting issues
npm run format       # Format code with Prettier

# Documentation
npm run docs         # Start server with documentation
npm run docs:serve   # Show documentation access info

πŸ”’ Security Features

  • Helmet.js - Security headers
  • CORS - Cross-origin resource sharing configuration
  • Rate Limiting - Protection against brute force attacks
  • Input Validation - Request validation with Joi
  • Password Hashing - Secure password storage with bcrypt
  • Session Management - Secure session handling
  • Environment Variables - Secure configuration management

πŸš€ Deployment

Environment Variables

Make sure to set these environment variables in production:

NODE_ENV=production
DATABASE_URL=your-production-database-url
BETTER_AUTH_SECRET=your-production-secret
BETTER_AUTH_URL=https://your-domain.com
CORS_ORIGIN=https://your-frontend-domain.com

Production Deployment

  1. Build the application:

    npm run build
  2. Set up production database:

    npm run db:migrate
  3. Start the application:

    npm start

Using Docker

# Build production image
docker build -t codeguide-starter:latest .

# Run with environment variables
docker run -d \
  --name codeguide-app \
  -p 3000:3000 \
  -e NODE_ENV=production \
  -e DATABASE_URL=your-db-url \
  -e BETTER_AUTH_SECRET=your-secret \
  codeguide-starter:latest

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

πŸ“ž Support

If you have any questions or need help, please:

  1. Check the documentation
  2. Search existing issues
  3. Create a new issue

Built with ❀️ by the CodeGuide team

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published