Skip to content

ToniR7/express-typescript-starter

Repository files navigation

Express Typescript Starter Logo

A production-ready Express.js boilerplate built with TypeScript, designed to provide a robust, scalable, and secure foundation for your next Node.js API project. This template comes with essential features like strong security, high code quality, and developer-friendly tools, enabling you to focus on building your application while ensuring maintainability and performance right from the start.

🌟 Key Features

πŸ›  Core Functionality

  • Web framework: Fast and minimalist web application framework using express
  • Logging: Advanced logging with winston and morgan
  • Schema validation: Ensure the integrity of incoming requests (query params, body) using zod
  • Environment Variable Management: Ensures all required environment variables are present and properly validated using zod
  • Error handling: Comprehensive error management system
  • Signal handling: Gracefully handles OS signals like SIGTERM and SIGINT to ensure proper cleanup and shutdown of the application
  • API Documentation: Automatic OpenAPI/Swagger documentation generation using zod-openapi, seamlessly integrated with Zod schemas to provide always up-to-date API documentation

πŸ”’ Security Features

  • CORS protection: Manage cross-origin requests with cors
  • Helmet: Help secure Express apps by setting HTTP response headers with helmet
  • Rate limiting: Safeguard the API against excessive requests and potential DDoS attacks with efficient middleware provided by express-rate-limit
  • Secure authentication: Robust JWT-based authentication implemented using jsonwebtoken, jwks-rsa and jwt-decode. Public keys are fetched from Microsoft’s identity platform, tokens are decoded and verified, and user informations (like username and groups) are extracted. Tokens are validated against audience and issuer claims to ensure only authorized clients can access the API.

πŸ’» Code Quality

  • Code formatting: Consistent code style with oxfmt
  • Linting: Enforce best practices and maintainable code with oxlint
  • Git Hooks with Husky: Automated quality gates using husky to enforce standards on every commit:
    • Pre-commit hook β€” Runs the following checks before allowing a commit:

      • Unit tests to prevent commits that would break the test suite
      • Lint and format staged files via lint-staged (oxlint auto-fix + oxfmt)
        {
          "*.{js,jsx,ts,tsx}": ["npm run lint:fix"],
          "*.{js,jsx,ts,tsx,md,html,css}": ["npm run format"]
        }
      • npm audit to check for known vulnerabilities
      • TypeScript type checking to catch type errors
    • Commit-msg hook β€” Enforces Conventional Commits format using commitlint

πŸ“– API Documentation

This boilerplate includes automatic OpenAPI/Swagger documentation generation that keeps your API docs always in sync with your code.

Features

  • Automatic Generation: Documentation is automatically generated from your Zod schemas using zod-openapi
  • Type Safety: Leverages TypeScript and Zod for type-safe API definitions
  • Multiple Formats: Generates both JSON and YAML formats for maximum compatibility
  • Rich Descriptions: Supports detailed descriptions, examples, and metadata for each endpoint

Usage

  1. Generate Documentation: Run npm run openapi to generate the latest API documentation
  2. View Documentation: The generated files are saved in the docs/ directory:
    • docs/openapi.json - JSON format for programmatic use
    • docs/openapi.yaml - YAML format for human readability
  3. Schema Definitions: API schemas are defined in src/models/ with OpenAPI extensions
  4. Route Definitions: OpenAPI route configurations are in src/openapi/routes/

Example Schema Definition

import { z } from 'zod'

export const userSchema = z
  .strictObject({
    id: z.string().uuid(),
    name: z.string().min(1).max(100),
    email: z.string().email(),
  })
  .meta({
    description: 'User object with basic information',
    id: 'User'
    example: {
      id: '123e4567-e89b-12d3-a456-426614174000',
      name: 'John Doe',
      email: 'john.doe@example.com',
    },
  })

The documentation can be viewed using any OpenAPI/Swagger UI tool or integrated into your API gateway.

πŸ§ͺ Testing and Coverage

  • Unit testing: Powered by vitest and supertest

  • Code coverage: Ensure high code quality and test coverage with Vitest’s built-in coverage reporting

⚑ Performance Optimization

  • Hot-reload: Streamline development with automatic server reload using Node's native --watch

πŸ”‘ Secrets Management

🐳 Deployment

  • Docker support: Containerization for easy deployment

πŸ“š Additional Libraries

πŸš€ Getting Started

  1. Clone the repository
    git clone https://github.com/ToniR7/express-typescript-starter.git
    cd express-typescript-starter
  2. Install dependecies: npm install
  3. Set up your environment variables (you can use the .env.test file as a reference to create your own .env file)
  4. Run the development server: npm run dev

πŸ“¦ Project Structure

project-name/
β”‚
β”œβ”€β”€ .github/                  # GitHub configuration
β”‚   └── workflows/            # GitHub Actions workflow definitions
β”‚       └── ci.yml            # CI pipeline (lint, security scan, typecheck, test)
β”‚
β”œβ”€β”€ .husky/                   # Git hooks managed by Husky
β”‚   β”œβ”€β”€ pre-commit            # Pre-commit hook (tests, linting, audit, typecheck)
β”‚   └── commit-msg            # Commit message linting with commitlint
β”‚
β”œβ”€β”€ docs/                     # Generated documentation
β”‚   β”œβ”€β”€ openapi.json          # OpenAPI specification in JSON format
β”‚   └── openapi.yaml          # OpenAPI specification in YAML format
β”œβ”€β”€ node_modules/             # Installed dependencies
β”‚
β”œβ”€β”€ src/                      # Source code
β”‚   β”œβ”€β”€ apis/                 # Request handlers for different routes
β”‚   β”œβ”€β”€ environment/          # Configuration and environment variable management
β”‚   β”œβ”€β”€ errors/               # Custom errors definition
β”‚   β”œβ”€β”€ logger/               # Logging utilities (Winston and Morgan)
β”‚   β”œβ”€β”€ middlewares/          # Express middleware functions (authentication, validation, error handling, rate limit)
β”‚   β”œβ”€β”€ models/               # Schemas definition (Zod schemas with OpenAPI extensions)
β”‚   β”œβ”€β”€ openapi/              # OpenAPI documentation generation
β”‚   β”œβ”€β”€ routes/               # API route definitions
β”‚   β”œβ”€β”€ typings/              # TypeScript type definitions and interfaces
β”‚   β”œβ”€β”€ utils/                # Utility functions and helper modules
β”‚   └── app.ts                # Entry point of the application, initializes the server
β”‚
β”œβ”€β”€ .commitlintrc             # Commitlint configuration (Conventional Commits)
β”œβ”€β”€ .dockerignore             # Files and directories to exclude from Docker builds
β”œβ”€β”€ .env                      # Environment variables (local development)
β”œβ”€β”€ .env.test                 # Example environment variables file (for documentation)
β”œβ”€β”€ .gitignore                # Files and directories to ignore in Git
β”œβ”€β”€ .lintstagedrc             # Configuration for lint-staged to run linting and formatting on staged files
β”œβ”€β”€ .npmrc                    # npm configuration
β”œβ”€β”€ .nvmrc                    # Specifies the Node.js version to use (for nvm compatibility)
β”œβ”€β”€ .oxfmtrc.json             # Oxfmt configuration file for code formatting
β”œβ”€β”€ .oxlintrc.json            # Oxlint configuration for linting the codebase
β”œβ”€β”€ Dockerfile                # Instructions to build a Docker image of the project
β”œβ”€β”€ LICENSE                   # Project license
β”œβ”€β”€ package-lock.json         # Lockfile for package versions
β”œβ”€β”€ package.json              # Project metadata, dependencies, and scripts
β”œβ”€β”€ README.md                 # Project documentation and setup instructions
β”œβ”€β”€ tsconfig.json             # TypeScript configuration for development and tooling
β”œβ”€β”€ vitest.config.ts          # Vitest configuration for running tests

🧩 Scripts

Test

  • npm run test: Runs Vitest tests. It will execute all the test cases written in the project without coverage reporting.
  • npm run test:coverage: Runs Vitest tests with coverage reporting. It generates a code coverage report showing which parts of the code are covered by tests.
  • npm run test:watch: Runs Vitest tests in watch mode. It watches for changes in the codebase and automatically reruns tests when files are modified.

Update

  • npm run updates: Runs npm-check-updates, a tool that checks for the latest versions of dependencies in the package.json and shows which packages can be updated.
  • npm run updates:interactive: Runs npm-check-updates in interactive mode, allowing you to select which packages to update.
  • npm run updates:upgrade: Automatically update the versions of dependencies in the package.json to the latest versions.

Dependencies

  • npm run depcheck: Runs depcheck, a tool that checks how each dependency is used, which dependencies are useless, and which dependencies are missing from package.json

Documentation

  • npm run openapi: Generates OpenAPI/Swagger documentation from Zod schemas. Creates openapi.json and openapi.yaml files containing the complete API specification that can be used with Swagger UI or other OpenAPI tools.

Linting and Formatting

  • npm run lint: Runs oxlint to check for issues in the code. It will output warnings and errors according to the rules defined in the oxlint configuration.
  • npm run lint:fix: Runs oxlint with the --fix flag, which automatically fixes any issues it can. It’s useful for cleaning up common problems.
  • npm run format: Runs oxfmt to format the code. It will rewrite the code to follow a consistent style, ensuring things like indentation and line breaks are uniform across the codebase.
  • npm run format:check: Runs oxfmt in check mode. It verifies that files conform to the formatting rules without modifying them, returning a non-zero exit code if differences are found (useful for CI pipelines).
  • npm run lint-staged: Runs lint-staged, which executes oxlint and oxfmt only on staged files according to the configuration in .lintstagedrc. This allows for faster pre-commit checks by only processing files that are about to be committed rather than the entire codebase.

Development

  • npm run dev: Runs the development server. This tool watches for changes in TypeScript files and automatically restarts the server.
  • npm run debug: Runs the server in debugging mode using the --inspect flag. This allows to attach a debugger to the Node.js process, enabling step-through debugging.

Type Checking

  • npm run typecheck: Runs the TypeScript compiler with --noEmit to check for type errors without producing output files.

Production

  • npm run prod: Runs the application directly with Node.js (using native TypeScript support). This script is for running the app in production.

Husky Prepare

  • npm run prepare: Runs the Husky setup. It prepares the Git hooks (like pre-commit and commit-msg hooks) by setting up the necessary files. This is typically used after installing or updating Husky.

πŸ”„ GitHub Workflows

This project includes a CI Pipeline (.github/workflows/ci.yml) that runs automatically on:

  • Push to main or develop branches
  • Pull requests targeting main or develop (on open and synchronize events)

Jobs

Job Description
lint Installs dependencies and runs npm run lint to check code quality with oxlint
security-scan Runs CodeQL static analysis for TypeScript to detect security vulnerabilities
typecheck Runs npm typecheck to ensure the codebase has no TypeScript type errors
test Runs npm test to execute the full test suite with Vitest

All four jobs run in parallel since they have no dependencies on each other, providing fast feedback on pull requests.

πŸ‘ŠπŸ» Contributing

I welcome contributions through:

  • πŸ› Bug Reports
  • πŸ’‘ Feature Requests
  • πŸ“š Documentation Improvements
  • πŸ› οΈ Code Contributions

About

Production-ready Node.js boilerplate built with TypeScript 6 and Express 5

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors