npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

express-ts-api-starter

v1.3.2

Published

Production-ready Express.js + TypeScript boilerplate with MVC architecture, JWT auth, MongoDB, security, validation, and testing—build scalable REST APIs fast

Downloads

419

Maintainers

nikhilpktcrnikhilpktcr

Keywords

expressexpress.jsexpressjstypescripttsnodejsnode.jsnodeboilerplatestarterstarter-templatetemplatescaffoldmvcmvc-architecturerest-apirestapirestfulrestful-apibackendbackend-templatebackend-starterserverweb-serverhttp-serverapi-servernode-serverauthenticationjwtjson-web-tokenjwt-authjwt-authenticationauthauthorizationmongodbmongoosemongodatabasenosqlsecurityhelmetcorsvalidationinput-validationdata-validationmiddlewareproduction-readyproductionscalableenterpriseenterprise-readytestingjesttestunit-testunit-testingerror-handlingerror-middlewareloggingloggermorganrequest-loggingbcryptjsbcryptpassword-hashingpassword-encryptionexpress-validatorapi-developmentrest-api-developmentweb-developmentfull-stacktypescript-boilerplateexpress-boilerplatenodejs-boilerplatenode-boilerplaterate-limitingrate-limitthrottlefile-uploadmulteruploadgraceful-shutdownrequest-trackingrequest-idcorrelation-idmodular-architecturefeature-basedmonolithicservice-patternfunctional-programmingasync-awaitpromiseslogging-middlewareauth-middlewarevalidation-middlewarebase-projectstarter-projectdev-toolsdevelopment-toolseslintprettiercode-qualitylintingformattingtypescript-starterexpress-typescriptexpress-tstypescript-apitypescript-backendnode-apinode-backendapi-templatebackend-templatemicroservicemicroservicesmicroservice-templatecrudcrud-apirestful-api-templateapi-boilerplatebackend-boilerplateserver-boilerplatetypescript-servertypescript-expressexpress-typescript-starterexpress-typescript-boilerplatenode-typescriptnode-typescript-apinode-typescript-startertypescript-rest-apitypescript-backend-startersecure-apisecure-backendproduction-apienterprise-apiscalable-apiscalable-backendbest-practicesbest-practices-boilerplateindustry-standardprofessionalprofessional-boilerplatemodernmodern-stackmodern-backendmodern-apihot-reloadnodemondevelopment-serverdev-servertypescript-configtsconfigtype-safetype-safetystrict-modestrict-typescriptmvc-patterncontrollerservice-layerrepository-patterndependency-injectionclean-architectureseparation-of-concernsmodularmodular-designmaintainablemaintainable-codetestabletestable-architecturewell-structuredorganizedclean-codecode-organizationproject-structurefolder-structureapi-structurebackend-structureenvenvironment-variablesdotenvconfigurationconfigsettingsstandardized-responsesapi-responsesresponse-formatconsistent-apiapi-versioningversioningapi-v1endpointsroutesroutingroute-handlinghttphttpshttp-serverweb-frameworknode-frameworkserver-frameworkapi-frameworkbackend-frameworktypescript-frameworkexpress-frameworkquick-startfast-setupzero-configzero-configurationready-to-useout-of-the-boxpre-configuredpreconfiguredbatteries-includedcomplete-solutionfull-featuredfeature-completecomprehensiveall-in-oneone-stopturnkeyready-madepre-builtpremadeinstantimmediaterapidfastquickefficienttime-savingproductivitydeveloper-productivitydeveloper-experiencedxdeveloper-friendlyeasy-to-useuser-friendlybeginner-friendlylearningtutorialexampleexamplessamplesamplesdemoreferencereference-implementationreference-architecturepatternpatternsdesign-patternsarchitecture-patternsbest-practices-patternsindustry-patternsproven-patternstested-patternsbattle-testedproduction-testedreal-worldreal-world-readypracticalpragmaticpragmatic-approachpragmatic-architecturesimplesimplicitycleanelegantminimalminimalistlightweightfastperformancehigh-performanceoptimizedoptimizationefficientefficiencyspeedfast-apifast-backendfast-serverlow-latencyresponsivereliablereliabilitystablestabilityrobustrobustnesssolidsolid-architecturewell-architectedwell-designedthoughtfulcarefulmeticulousattention-to-detaildetail-orientedcomprehensivethoroughcompletefullextensivewidebroadversatileflexibleadaptablecustomizableextensibleextendableexpandablescalable-architecturescalable-designscalable-structuregrowth-readyfuture-prooffuture-readyforward-compatibleupgradeableupgradablemaintainable-architecturemaintainable-designmaintainable-structurelong-termsustainablesustainabilitydurabledurabilitylastingenduringpersistentpersistenceconsistentconsistencyuniformuniformitystandardizedstandardizationstandardstandardsindustry-standardsbest-practicesindustry-best-practicesproven-practicestested-practicesestablished-practicescommon-practicesrecommended-practicessuggested-practicesguidelinesconventionsconventionsstyle-guidecoding-standardscode-standardsquality-standardsqualityhigh-qualityquality-codequality-architectureprofessional-qualityenterprise-qualityproduction-qualitycommercial-qualitycommercial-gradeenterprise-gradeproduction-gradeindustrial-gradeprofessional-gradeprofessionalprofessional-developmentprofessional-codeprofessional-architectureenterpriseenterprise-developmententerprise-codeenterprise-architectureenterprise-solutionenterprise-readyenterprise-gradeenterprise-levelenterprise-scalelarge-scalescalescalinghorizontal-scalingvertical-scalingload-handlinghigh-loadhigh-traffichigh-concurrencyconcurrentconcurrencyparallelparallelismasyncasynchronousasynchronous-programmingasync-programmingpromise-basedpromiseasync-awaitasync-await-patterncallbackcallbacksevent-drivenevent-driven-architectureevent-loopnon-blockingnon-blocking-ionon-blocking-i-ononblockingnonblocking-iononblocking-i-oioi-oinput-outputfile-ionetwork-iodatabase-iodb-iomongodb-iomongo-iomongoose-iodatabase-operationsdb-operationsmongodb-operationsmongo-operationsmongoose-operationscrud-operationsdatabase-cruddb-crudmongodb-crudmongo-crudmongoose-cruddata-persistencepersistencedata-storagestoragedata-managementmanagementdata-accessaccessdata-layerdata-access-layerdalrepositoryrepositoriesrepository-patterndata-repositorymodelmodelsdata-modeldata-modelsschemaschemasdatabase-schemadb-schemamongodb-schemamongo-schemamongoose-schemamongoose-modelmongoose-modelsodmobject-document-mapperobject-document-mappingdocument-mapperdocument-mappingdocument-modeldocument-modelsdocument-orienteddocument-databasedocument-storedocument-storagenosql-databasenosql-dbnosql-storenosql-storage

Readme

🏗️ EXPRESS-TS-API-STARTER

npm version npm downloads License: MIT TypeScript Express.js Node.js

Opinionated Express + TypeScript starter with JWT authentication, MongoDB integration, comprehensive security middleware, input validation, error handling, and production-ready architecture—get your REST API running in minutes, not hours.


📌 Quick Demo

Create a new project in seconds:

npx express-ts-api-starter my-api
cd my-api
npm install
npm run dev

Your API is ready with authentication, validation, and error handling out of the box!


🚀 Quick Start

Option 1: Using CLI (Recommended)

Create a new project with a single command:

npx express-ts-api-starter my-api

This will:

  • ✅ Create a new project directory
  • ✅ Copy all template files and folder structure
  • ✅ Set up configuration files
  • ✅ Create .env file from .env.example

Then:

cd my-api
npm install
npm run dev

Option 2: Manual Installation

# Clone the repository
git clone https://github.com/nikhilpktcr/express-ts-api-starter.git my-api
cd my-api

# Install dependencies
npm install

# Copy environment variables
cp .env.example .env

# Start development server (hot reload enabled)
npm run dev

That's it! Your server is running at http://localhost:5000 with:

  • ✅ JWT authentication ready
  • ✅ MongoDB connection configured
  • ✅ Security middleware active
  • ✅ Request logging enabled
  • ✅ Error handling in place

⚡ Why Choose This Over Others?

vs. Bare Express Setup

| Feature | Bare Express | express-ts-api-starter | |---------|-------------|------------------------| | Setup Time | 2-4 hours | 2 minutes ⚡ | | TypeScript | Manual config | ✅ Pre-configured | | Authentication | Build from scratch | ✅ JWT + bcryptjs ready | | Error Handling | Manual try-catch | ✅ Global middleware | | Request Logging | Manual setup | ✅ Morgan with request IDs | | Input Validation | Manual validation | ✅ express-validator integrated | | Security | Manual headers | ✅ Helmet + CORS configured | | Database | Manual connection | ✅ MongoDB/Mongoose ready | | Testing | Manual Jest setup | ✅ Jest configured with examples | | Code Quality | No linting | ✅ ESLint + Prettier ready | | Graceful Shutdown | Not included | ✅ Production-ready |

vs. Other Starters

| Feature | Other Starters | express-ts-api-starter | |---------|---------------|------------------------| | Architecture | Varies | ✅ MVC with functional services (clean, testable) | | Request Tracking | Rare | ✅ Unique request IDs (debugging made easy) | | Error Handling | Basic | ✅ Comprehensive with graceful shutdown | | Validation | Optional | ✅ Built-in express-validator | | Logging | Basic | ✅ Morgan with request ID correlation | | TypeScript | Sometimes | ✅ 100% TypeScript with strict mode | | Documentation | Minimal | ✅ Well-documented with examples | | Testing | Sometimes | ✅ Jest with test examples included | | CLI Tool | Sometimes | ✅ Built-in CLI generator |

vs. NestJS

| Feature | NestJS | express-ts-api-starter | |---------|--------|------------------------| | Setup Time | 10-15 minutes | ⚡ 2 minutes | | Learning Curve | High (new framework) | ✅ Low (Express knowledge) | | Bundle Size | ~200KB+ | ✅ ~50KB (lightweight) | | Flexibility | Framework-driven | ✅ High (minimal abstraction) | | Request Tracking | Manual setup | ✅ Built-in request IDs | | Security (Out of Box) | Manual config | ✅ Pre-configured |

📖 See detailed NestJS comparison →


🎯 Key Strengths

🔐 Authentication & Security

  • JWT-based authentication with secure token generation
  • bcryptjs password hashing (industry standard)
  • Helmet.js for HTTP security headers
  • CORS configured for cross-origin requests
  • Rate limiting ready to prevent DDoS attacks
  • Request ID tracking for security auditing

📝 Input Validation

  • express-validator middleware pre-configured
  • Type-safe validation with TypeScript
  • Reusable validation rules in dedicated validators folder
  • Automatic error responses for invalid inputs

🛡️ Error Handling

  • Global error middleware catches all errors
  • Standardized error responses across all endpoints
  • Request ID included in error responses for debugging
  • Graceful shutdown handles SIGTERM/SIGINT properly
  • Uncaught exception handling prevents crashes

📊 Logging & Monitoring

  • Morgan logging with custom format
  • Request ID correlation for tracking requests across services
  • Structured logging ready for production monitoring
  • Error logging with stack traces

🏗️ Architecture

  • MVC pattern with clear separation of concerns
  • Functional service layer (easier to test than classes)
  • Modular structure - each feature is self-contained
  • Scalable design - grow from startup to enterprise

📦 What's Included

Core Features

  • Express.js v5 - Latest framework version
  • TypeScript 5.8 - Full type safety with strict mode
  • MongoDB + Mongoose - Database integration ready
  • JWT Authentication - Secure token-based auth
  • bcryptjs - Password hashing
  • express-validator - Input validation
  • Helmet - Security headers
  • CORS - Cross-origin resource sharing
  • Morgan - HTTP request logging
  • Multer - File upload support
  • express-rate-limit - Rate limiting
  • Jest - Testing framework with examples
  • ESLint + Prettier - Code quality tools

Developer Experience

  • CLI Tool - Generate projects with one command
  • Hot reload - See changes instantly
  • TypeScript declarations - Full IntelliSense support
  • Pre-configured scripts - dev, build, test, lint
  • Example code - User module with CRUD operations
  • Test examples - Learn testing patterns
  • Well-documented - Clear code structure

📁 Project Structure

src/
├── modules/              # Feature modules (MVC pattern)
│   └── users/
│       ├── userController.ts    # HTTP request handlers
│       ├── userService.ts       # Business logic
│       ├── userMessage.ts       # Constants/messages
│       └── tests/               # Unit tests
├── routes/               # API route definitions
├── middleware/          # Express middleware
│   ├── auth.ts          # JWT authentication
│   ├── errorMiddleware.ts
│   ├── validatorMiddleware.ts
│   └── requestIdMiddleware.ts
├── config/              # Configuration files
│   ├── dbConfig.ts      # MongoDB connection
│   ├── envConfig.ts     # Environment variables
│   └── rateLimitConfig.ts
├── models/              # Mongoose schemas
├── validators/          # Input validation rules
├── utils/               # Utility functions
├── types/               # TypeScript type definitions
└── app.ts               # Express app setup

🔧 Available Commands

# Development
npm run dev          # Start dev server with hot reload

# Production
npm run build        # Compile TypeScript to JavaScript
npm start            # Start production server

# Testing
npm test             # Run test suite
npm test -- --watch  # Run tests in watch mode
npm test -- --coverage  # Run with coverage report

# Code Quality
npm run lint         # Check for linting errors
npm run lint:fix     # Auto-fix linting errors

📝 Configuration

Environment Variables

Create a .env file:

# Server
NODE_ENV=development
PORT=5000
BASIC_API_URL=/api/v1

# Database
DB_CONNECTION=mongodb://localhost:27017/
DB_NAME=testDB

# Authentication
JWT_SECRET=your-super-secret-jwt-key-change-in-production

See .env.example for all available options.


🧪 Testing

# Run all tests
npm test

# Watch mode
npm test -- --watch

# Coverage report
npm test -- --coverage

Example test included in src/modules/users/tests/userController.test.ts


📋 Standardized API Responses

All responses follow a consistent format:

Success:

{
  "success": true,
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "message": "Operation successful",
  "response": { "data": "..." }
}

Error:

{
  "success": false,
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "error": "Error message"
}

🔐 Security Features

  • Helmet - Sets secure HTTP headers
  • CORS - Configurable cross-origin requests
  • JWT - Secure token-based authentication
  • bcryptjs - Password hashing (10 rounds)
  • Rate Limiting - DDoS protection ready
  • Input Validation - Prevents injection attacks
  • Request ID Tracking - Security audit trail

🚦 Production Ready

  • Graceful shutdown - Handles SIGTERM/SIGINT
  • Error handling - Global error middleware
  • Logging - Request tracking with unique IDs
  • Type safety - Full TypeScript coverage
  • Testing - Jest framework configured
  • Code quality - ESLint + Prettier

🎯 Perfect For

  • 🚀 REST APIs - Full-featured API servers
  • 🔧 Microservices - Scalable service architecture
  • 🏢 Enterprise Apps - Production-ready foundation
  • 🎓 Learning - Best practices and patterns
  • MVPs - Quick prototype development
  • 📱 Backend Services - Complex business logic

🔧 Tech Stack

  • Runtime: Node.js v20+
  • Framework: Express.js v5
  • Language: TypeScript 5.8
  • Database: MongoDB with Mongoose
  • Security: Helmet, CORS, JWT, bcryptjs
  • Validation: express-validator
  • Logging: Morgan
  • Testing: Jest
  • Linting: ESLint + Prettier

🤝 Contributing

Contributions welcome! Please:

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

📄 License

MIT License - see LICENSE file for details.

Free for personal and commercial use! ✨


💬 Support


🌟 Show Your Support

If this boilerplate helps your project:

  • Star the repository on GitHub
  • 📦 Use the npm package in your projects
  • 🐛 Report issues you encounter
  • 💡 Suggest features and improvements
  • 🔄 Share with other developers

🎯 Roadmap

  • [ ] API Documentation (Swagger/OpenAPI)
  • [ ] Health check endpoint
  • [ ] Pagination utility
  • [ ] Redis caching layer
  • [ ] Docker & Docker Compose
  • [ ] CI/CD pipeline examples
  • [ ] More comprehensive test suite

Ready to build? Start your next API project in minutes:

npx express-ts-api-starter my-api

Happy coding! 🎉