Skip to content

darthcav/ts-http-server

Repository files navigation

@darthcav/ts-http-server

Node Version CI Coverage

A TypeScript wrapper HTTP server for Node.js >= 25 based upon Fastify.

API Documentation

Features

  • Native TypeScript execution (Node.js type stripping, no transpiler needed at runtime)
  • Strict TypeScript configuration with isolated declarations
  • Content negotiation for error responses (HTML / JSON / plain-text)
  • Access logging via onResponse hook — info for 2xx/3xx, error for 4xx/5xx
  • Default plugin set: CORS, compression, ETag, Helmet CSP, EJS views, and static files
  • Returns a FastifyInstance for graceful shutdown via SIGINT/SIGTERM
  • Biome for linting and formatting
  • Built-in Node.js test runner
  • TypeDoc for API documentation
  • GitHub Actions CI/CD workflows

Installation

npm install @darthcav/ts-http-server

Usage

import { launcher, defaultPlugins, defaultRoutes } from "@darthcav/ts-http-server"
import { getConsoleLogger, main } from "@darthcav/ts-utils"
import process from "node:process"
import pkg from "./package.json" with { type: "json" }

const logger = await getConsoleLogger(pkg.name, "info")

main(pkg.name, logger, false, () => {
    const locals = { pkg }
    const plugins = defaultPlugins({ locals })
    const routes = defaultRoutes()

    const fastify = launcher({ logger, locals, plugins, routes })

    for (const signal of ["SIGINT", "SIGTERM"] as const) {
        process.on(signal, async (signal) =>
            fastify
                .close()
                .then(() => {
                    logger.error(`Server closed on ${signal}`)
                    process.exit(0)
                })
                .catch((error) => {
                    logger.error(`Shutdown error: ${error}`)
                    process.exit(1)
                }),
        )
    }
})

The defaultPlugins function accepts an optional baseDir to resolve the src/ folder (defaults to the parent of import.meta.dirname):

const plugins = defaultPlugins({ locals, baseDir: import.meta.dirname })

Getting Started

# Install dependencies
npm install

# Run once
npm start

# Type-check
npm run typecheck

# Build (compile to JavaScript)
npm run build

# Run tests
npm test

# Lint and format
npm run lint
npm run lint:fix

# Generate documentation
npm run doc

Project Structure

src/
  index.ts          # Library entry point
  start.ts          # Application entry point
  launcher.ts       # Application launcher (returns FastifyInstance)
  types.ts          # Shared type definitions
  defaults/         # Default Fastify options, plugins, routes, and error handler
  hooks/            # Fastify hooks (preHandler, onResponse)
  __tests__/        # Test files
dist/               # Compiled output (generated)
public/             # Documentation output (generated)

License

Apache-2.0

About

HTTP skeleton server based upon Fastify.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors