Project Configuration
Configure your ServCraft project for any environment
ServCraft uses a centralized configuration file (`servcraft.config.json`) and environment variables to manage all project settings. This guide covers all available configuration options and best practices.
Configuration Options
All available configuration options organized by category
Core
Essential project configuration
| Key | Type | Description | Default |
|---|---|---|---|
name | string | Project name used for identification | my-app |
version | string | Semantic version of your application | 1.0.0 |
description | string | Brief description of your project | |
author | string | Project author or organization | |
ServCraft
ServCraft framework settings
| Key | Type | Description | Default |
|---|---|---|---|
servcraft.version | string | Semver constraint for ServCraft version | >=0.4.0 |
servcraft.language | enum | Programming language: typescript or javascript | typescript |
servcraft.moduleSystem | enum esmcjs | ESM (ES Modules) or CommonJS | esm |
servcraft.validator | enum zodjoiyup | Validation library for request schemas | zod |
Database
Database connection and ORM settings
| Key | Type | Description | Default |
|---|---|---|---|
servcraft.database.provider | enum postgresqlmysqlsqlitemongodb | Database engine | postgresql |
servcraft.database.schema | string | Path to Prisma schema file | prisma/schema.prisma |
servcraft.database.pool.min | number | Minimum connection pool size | 2 |
servcraft.database.pool.max | number | Maximum connection pool size | 10 |
Authentication
Security and authentication settings
| Key | Type | Description | Default |
|---|---|---|---|
servcraft.auth.jwt.accessTokenExpiry | string | Access token lifetime | 15m |
servcraft.auth.jwt.refreshTokenExpiry | string | Refresh token lifetime | 7d |
servcraft.auth.jwt.algorithm | string | JWT signing algorithm | HS256 |
servcraft.auth.mfa.enabled | boolean | Enable two-factor authentication | false |
servcraft.auth.rateLimit.windowMs | number | Rate limit time window in ms | 900000 |
servcraft.auth.rateLimit.max | number | Max requests per window | 100 |
CORS
Cross-Origin Resource Sharing settings
| Key | Type | Description | Default |
|---|---|---|---|
servcraft.cors.origin | string | Allowed origins (comma-separated or * for all) | * |
servcraft.cors.methods | array | Allowed HTTP methods | ['GET','POST','PUT','DELETE','PATCH'] |
servcraft.cors.credentials | boolean | Allow credentials (cookies, auth headers) | true |
servcraft.cors.maxAge | number | Preflight cache duration in seconds | 86400 |
Logging
Application logging configuration
| Key | Type | Description | Default |
|---|---|---|---|
servcraft.logging.level | enum errorwarninfodebugtrace | Log verbosity level | info |
servcraft.logging.prettyPrint | boolean | Colorized output in development | true |
servcraft.logging.timestamp | boolean | Include timestamps in logs | true |
Environment Variables
Store sensitive configuration and environment-specific values securely
1# ===========================================2# Server Configuration3# ===========================================4NODE_ENV=development5PORT=30006API_PREFIX=/api7API_VERSION=v189# ===========================================10# Database Configuration11# ===========================================12DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"1314# For SQLite (development)15# DATABASE_URL="file:./dev.db"1617# For MongoDB18# DATABASE_URL="mongodb://localhost:27017/mydb"1920# ===========================================21# JWT Authentication22# ===========================================23JWT_ACCESS_SECRET=your-super-secret-access-key-change-in-production24JWT_REFRESH_SECRET=your-super-secret-refresh-key-change-in-production25JWT_ACCESS_EXPIRY=15m26JWT_REFRESH_EXPIRY=7d2728# ===========================================29# OAuth Providers (optional)30# ===========================================31GOOGLE_CLIENT_ID=your-google-client-id32GOOGLE_CLIENT_SECRET=your-google-client-secret33GOOGLE_CALLBACK_URL=http://localhost:3000/api/auth/oauth/callback/google3435GITHUB_CLIENT_ID=your-github-client-id36GITHUB_CLIENT_SECRET=your-github-client-secret37GITHUB_CALLBACK_URL=http://localhost:3000/api/auth/oauth/callback/github3839# ===========================================40# Email Configuration (if using email module)41# ===========================================42SMTP_HOST=smtp.example.com43SMTP_PORT=58744SMTP_USER=your-email@example.com45SMTP_PASS=your-email-password46SMTP_FROM=noreply@myapp.com4748# ===========================================49# Redis Configuration (if using cache module)50# ===========================================51REDIS_HOST=localhost52REDIS_PORT=637953REDIS_PASSWORD=54REDIS_DB=05556# ===========================================57# Rate Limiting58# ===========================================59RATE_LIMIT_WINDOW_MS=90000060RATE_LIMIT_MAX_REQUESTS=1006162# ===========================================63# Security64# ===========================================65BCRYPT_ROUNDS=1266CORS_ORIGIN=http://localhost:300067CORS_CREDENTIALS=true
Development
Use .env.local for local overrides
Staging
Use .env.staging for staging environment
Production
Use .env.production for production
Security
Never commit .env files to version control
Configuration Validation
Validate your configuration at startup to catch errors early
1import { z } from "zod";2import { readFileSync } from "fs";3import { join } from "path";45// Define schema for configuration validation6const configSchema = z.object({7name: z.string().min(1),8version: z.string().regex(/^\d+\.\d+\.\d+$/),9servcraft: z.object({10version: z.string(),11language: z.enum(["typescript", "javascript"]),12modules: z.array(z.string()),13database: z.object({14provider: z.enum(["postgresql", "mysql", "sqlite", "mongodb"]),15schema: z.string(),16pool: z.object({17min: z.number().min(1),18max: z.number().min(1),19}).optional(),20}).optional(),21auth: z.object({22jwt: z.object({23accessTokenExpiry: z.string(),24refreshTokenExpiry: z.string(),25}),26}).optional(),27}).optional(),28});2930// Load and parse config file31function loadConfig() {32const configPath = join(process.cwd(), "servcraft.config.json");33const configFile = JSON.parse(readFileSync(configPath, "utf-8"));3435// Validate configuration36const result = configSchema.safeParse(configFile);3738if (!result.success) {39console.error("Invalid configuration:");40result.error.errors.forEach((err) => {41console.error(` ${err.path.join(".")}: ${err.message}`);42});43process.exit(1);44}4546return result.data;47}4849export const config = loadConfig();
Complete Example
A fully configured servcraft.config.json for a production application
1{2"name": "my-api",3"version": "1.0.0",4"description": "Production-ready REST API with ServCraft",5"author": "Developer <dev@example.com>",67"servcraft": {8"version": ">=0.4.0",9"language": "typescript",10"modules": ["auth", "users", "email", "cache"],11"moduleSystem": "esm",1213"database": {14"provider": "postgresql",15"schema": "prisma/schema.prisma",16"pool": {17"min": 2,18"max": 10,19"idleTimeoutMs": 30000,20"connectionTimeoutMs": 500021}22},2324"auth": {25"jwt": {26"accessTokenExpiry": "15m",27"refreshTokenExpiry": "7d",28"algorithm": "HS256"29},30"mfa": {31"enabled": true,32"issuer": "MyApp",33"window": 134},35"oauth": {36"providers": ["google", "github", "discord"],37"callbackUrl": "http://localhost:3000/api/auth/oauth/callback"38},39"rateLimit": {40"windowMs": 900000,41"max": 10042}43},4445"cors": {46"origin": ["http://localhost:3000", "https://myapp.com"],47"methods": ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],48"credentials": true,49"maxAge": 8640050},5152"logging": {53"level": "info",54"prettyPrint": true,55"timestamp": true56},5758"email": {59"host": "smtp.example.com",60"port": 587,61"secure": false,62"from": "noreply@myapp.com"63}64},6566"scripts": {67"dev": "tsx watch src/server.ts",68"build": "tsc",69"start": "node dist/server.js",70"db:push": "prisma db push",71"db:migrate": "prisma migrate dev",72"db:seed": "tsx prisma/seed.ts",73"test": "vitest",74"test:coverage": "vitest --coverage",75"lint": "eslint src --ext .ts",76"format": "prettier --write src/"77},7879"keywords": ["api", "rest", "servcraft", "fastify", "typescript"],80"license": "MIT",81"repository": {82"type": "git",83"url": "https://github.com/username/my-api.git"84}85}
Best Practices
Keep Secrets Safe
Never commit secrets to version control. Use environment variables.
Validate Early
Validate configuration at startup to catch errors immediately.
Environment Profiles
Use different configs for dev, staging, and production.
Document Defaults
Use .env.example to document all required variables.