Version: 1.0.0
License: MIT
- Overview
- Why Use This Base?
- Documentation
- Features
- Installation
- Environment Variables
- Initial Setup & Tokens
- Middleware
- Routes & Validation
- Best Practices
- Response Format
- Logging
- Token Management
- Security
- Contributing
- License
This project is strict by design. If something feels “broken” (CORS, tokens, headers, validation), it is probably intentional.
👉 Read this before using or opening issues:
docs/why_is_api_strict.md
typescript-api-template is a robust and scalable API base build with Node.js, Typescript, and Express. Designed for production from day one, it includes:
- Token-based authentication with IP restrictions (
systemandpersonaltokens) - Rate limiting per token or IP
- Global request validation with Zod schemas
- Structured logging and modular middleware
- Configurable CORS and payload protection
- Security headers for XSS, clickjacking, HSTS, CSP
- IP guard and JSON/payload protection against malformed or oversized requests
- Automatic token caching and refresh
This base is ideal for internal tools, enterprise applications, or public APIs requiring strict security and maintainability.
- Production-ready: best practices for security, validation, and logging.
- Scalable: Modular design allows easy extension with new routes and middleware.
- Enterprise-grade: Standardized responses, error codes, and global middlewares.
- Safe & reliable: Gracefully handles malformed JSON, large payloads, and invalid requests.
- Easy configuration: Everything controlled via environment variables.
Start any Node.js/TypeScript project with security and maintainability out of the box.
For detailed internal docs, see:
- Routes – Route structure and Zod validation
- Security – Security model, threat mitigation, logging
- Architecture – Project layout, middleware flow, token refresh
- Configuration – All environment variables and defaults
Note
Tokens require at least one allowed IP; there is no default fallback token.
| Feature | Description |
|---|---|
| Authentication | Token-based, IP-bound, and with expiration checks. Configurable via .env. |
| Rate Limiting | Per-token/IP limits to prevent abuse. Fully configurable. |
| Validation | Automatic request validation using Zod for body, query, and params. |
| Logging | Detailed request and error logging with token context and duration. |
| CORS | Configurable allowed origins, methods, and credentials. |
| Security Headers | Helmet-powered headers including HSTS, frameguard, referrer policy, CSP |
| IP Guard | Limits requests per IP to prevent abuse and brute-force attacks. Configurable via .env |
| JSON & Payload Protection | Rejects malformed JSON, oversized requests (>10kb), and unexpected fields. Ensures server stability |
| Hot Token Reload | Tokens are refreshed every minute without server restart. |
| Modular Design | Routes, middleware, and services are separated for clarity and scalability. |
git clone https://github.com/ressiws/typescript-api-template.git
cd typescript-api-template
pnpm install
cp .env.example .env # Copy the .env file and configure your environment variables| Variable | Description | Default / Required |
|---|---|---|
NODE_ENV |
Environment mode (development, production) |
Required |
APP_NAME |
Application name | Required |
APP_PORT |
Port number | Required |
APP_VERSION |
Application version | Required |
TRUST_PROXY |
Trust reverse proxy for req.ip (true/false) |
false |
DB_HOST |
Database host | Required |
DB_USER |
Database username | Required |
DB_PASS |
Database password | Required |
DB_NAME |
Database name | Required |
AUTH_ENABLE |
Enable authentication middleware | true/false |
VALIDATE_ENABLE |
Enable request validation middleware (Zod) | true/false |
RATE_LIMIT_ENABLE |
Enable rate limiting | true/false |
RATE_LIMIT_WINDOW_MS |
Rate limit window (ms) | 60000 |
RATE_LIMIT_MAX_REQUESTS |
Max requests per window | 20 |
LOGGING_ENABLE |
Enable request/error logging | true/false |
CORS_ORIGIN |
Allowed origins (comma-separated). If empty or undefined, browser requests with an Origin header will be blocked. | Optional |
CORS_METHODS |
Allowed HTTP methods (comma-separated) | Optional |
CORS_CREDENTIALS |
Enable credentials (true/false) |
Required |
IPGUARD_ENABLE |
Enable IP-based guard | true/false |
IPGUARD_WINDOW_MS |
IP guard window (ms) | 60000 |
IPGUARD_MAX_REQUESTS |
Max requests per IP | 100 |
HEADERS_ENABLE |
Enable security headers | true/false |
[!IMPORTANT] If CORS_ORIGIN is defined, only those origins are allowed, If it is empty or undefined, browser requests with an Origin header will be blocked.
When you first start the API:
- Database tables are automatically created if they don't exist (currently only
auth_tokens). - If no tokens are found in the database, the API will:
- Automatically generate a secure token
- Insert it into the database
- Print the token to the console once
This guarantees the API is never exposed without authentication, while still being usable on first boot.
Warning
The generated token is shown only once on startup, Copy it immediately and store it securely.
Example console output:
[INFO] Initial token created: 8f3c1d9e6c1a9b4e...
You can later manage tokens directly in the database.
INSERT INTO auth_tokens
(token, name, type, allowed_ips, max_requests, created_at, expires_at)
VALUES
(
'YOUR_SECRET_TOKEN', -- token
'Admin token', -- token name
'personal', -- token type
-- Allowed IPs are stored in a dedicated table (`auth_token_ips`) with one IP per row
1000, -- max requests
UNIX_TIMESTAMP(),
NULL -- expiration date (uses Unix timestamp in seconds)
);created_atuses Unix timestamp in seconds.expires_atis optional; (NULL= no expiration)- Tokens are IP-bound, requests from unauthorized IPs will be rejected.
Your MySQL user must have access to this database.
Important
If this value does not match your actual database name, the server will fail at startup.
Note: IPs are stored in
auth_token_ipslinked bytoken_id.
pnpm run dev # Development
pnpm run build
pnpm run start # ProductionOn startup, the server will:
- Ensure required tables exist
- Create an initial token only if none exist
- Log the generated token to the console (once)
- Continue normally if tokens already exist
This ensures your API is secure by default:
- No open access
- No hardcoded tokens
- No silent misconfiguration
- Applied globally: Authentication, Rate Limiting, IP Guard, Validation, Logging, CORS, Compression, Security Headers, Error Handler.
- Routes are automatically registered from the
src/routesfolder. - Each route can define its own Zod schema for validation.
- Validation middleware is route-specific, ensuring only the routes that need it are validated.
- Example:
validate({ body: schema, query: schema, params: schema })per route.
// routes/test.ts
import { Router } from "express";
import { z } from "zod";
import { sendSuccess } from "../core/helpers/response.helper.js";
import { validate } from "../security/validate.middleware.js";
const router = Router();
router.post("/", validate({
body: z.object({
name: z.string().min(1, "Name is required"),
age: z.number().int().min(0, "Age must be a non-negative integer"),
}),
}), (req, res) => {
// If we reach here, validation passed
sendSuccess(res, "Validation passed.", {
body: req.body,
query: req.query,
});
});
export default router;- Routes without validation can be defined normally:
router.get("/health", (_req, res) => res.json({ status: "ok" }));- Validate and sanitize
body,query,params - Use
.transformor.refinefor trimming, escaping, or parsing - Reject invalid input early
- Never coerce in business logic
Success:
{
"status": "ok",
"message": "Health check passed.",
"data": { ... }
}Error:
{
"status": "error",
"code": "RATE_LIMIT",
"message": "Too many requests.",
"data": null
}- Logs requests, status codes, token info, duration
- Logs validation and token refresh events
- Tokens are loaded from the database into memory at startup.
- Refreshed every 60 seconds automatically.
- Supports
personalorsystemtokens with allowed IPs and optional max requests.
- Helmet headers for HSTS, X-Frame-Options, XSS protection, CSP.
- IP-bound tokens & IP guard.
- Validation prevents malformed/oversized requests.
- See CONTRIBUTING.md for code standards, commit messages, and PR workflow.
MIT License © 2025 Swisser