Back to Documentation

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

KeyTypeDescriptionDefault
namestringProject name used for identificationmy-app
versionstringSemantic version of your application1.0.0
descriptionstringBrief description of your project
authorstringProject author or organization

ServCraft

ServCraft framework settings

KeyTypeDescriptionDefault
servcraft.versionstringSemver constraint for ServCraft version>=0.4.0
servcraft.languageenumProgramming language: typescript or javascripttypescript
servcraft.moduleSystemenum
esmcjs
ESM (ES Modules) or CommonJSesm
servcraft.validatorenum
zodjoiyup
Validation library for request schemaszod

Database

Database connection and ORM settings

KeyTypeDescriptionDefault
servcraft.database.providerenum
postgresqlmysqlsqlitemongodb
Database enginepostgresql
servcraft.database.schemastringPath to Prisma schema fileprisma/schema.prisma
servcraft.database.pool.minnumberMinimum connection pool size2
servcraft.database.pool.maxnumberMaximum connection pool size10

Authentication

Security and authentication settings

KeyTypeDescriptionDefault
servcraft.auth.jwt.accessTokenExpirystringAccess token lifetime15m
servcraft.auth.jwt.refreshTokenExpirystringRefresh token lifetime7d
servcraft.auth.jwt.algorithmstringJWT signing algorithmHS256
servcraft.auth.mfa.enabledbooleanEnable two-factor authenticationfalse
servcraft.auth.rateLimit.windowMsnumberRate limit time window in ms900000
servcraft.auth.rateLimit.maxnumberMax requests per window100

CORS

Cross-Origin Resource Sharing settings

KeyTypeDescriptionDefault
servcraft.cors.originstringAllowed origins (comma-separated or * for all)*
servcraft.cors.methodsarrayAllowed HTTP methods['GET','POST','PUT','DELETE','PATCH']
servcraft.cors.credentialsbooleanAllow credentials (cookies, auth headers)true
servcraft.cors.maxAgenumberPreflight cache duration in seconds86400

Logging

Application logging configuration

KeyTypeDescriptionDefault
servcraft.logging.levelenum
errorwarninfodebugtrace
Log verbosity levelinfo
servcraft.logging.prettyPrintbooleanColorized output in developmenttrue
servcraft.logging.timestampbooleanInclude timestamps in logstrue

Environment Variables

Store sensitive configuration and environment-specific values securely

.env.example
1# ===========================================
2# Server Configuration
3# ===========================================
4NODE_ENV=development
5PORT=3000
6API_PREFIX=/api
7API_VERSION=v1
8
9# ===========================================
10# Database Configuration
11# ===========================================
12DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
13
14# For SQLite (development)
15# DATABASE_URL="file:./dev.db"
16
17# For MongoDB
18# DATABASE_URL="mongodb://localhost:27017/mydb"
19
20# ===========================================
21# JWT Authentication
22# ===========================================
23JWT_ACCESS_SECRET=your-super-secret-access-key-change-in-production
24JWT_REFRESH_SECRET=your-super-secret-refresh-key-change-in-production
25JWT_ACCESS_EXPIRY=15m
26JWT_REFRESH_EXPIRY=7d
27
28# ===========================================
29# OAuth Providers (optional)
30# ===========================================
31GOOGLE_CLIENT_ID=your-google-client-id
32GOOGLE_CLIENT_SECRET=your-google-client-secret
33GOOGLE_CALLBACK_URL=http://localhost:3000/api/auth/oauth/callback/google
34
35GITHUB_CLIENT_ID=your-github-client-id
36GITHUB_CLIENT_SECRET=your-github-client-secret
37GITHUB_CALLBACK_URL=http://localhost:3000/api/auth/oauth/callback/github
38
39# ===========================================
40# Email Configuration (if using email module)
41# ===========================================
42SMTP_HOST=smtp.example.com
43SMTP_PORT=587
44SMTP_USER=your-email@example.com
45SMTP_PASS=your-email-password
46SMTP_FROM=noreply@myapp.com
47
48# ===========================================
49# Redis Configuration (if using cache module)
50# ===========================================
51REDIS_HOST=localhost
52REDIS_PORT=6379
53REDIS_PASSWORD=
54REDIS_DB=0
55
56# ===========================================
57# Rate Limiting
58# ===========================================
59RATE_LIMIT_WINDOW_MS=900000
60RATE_LIMIT_MAX_REQUESTS=100
61
62# ===========================================
63# Security
64# ===========================================
65BCRYPT_ROUNDS=12
66CORS_ORIGIN=http://localhost:3000
67CORS_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

src/utils/config.ts
1import { z } from "zod";
2import { readFileSync } from "fs";
3import { join } from "path";
4
5// Define schema for configuration validation
6const configSchema = z.object({
7 name: z.string().min(1),
8 version: z.string().regex(/^\d+\.\d+\.\d+$/),
9 servcraft: z.object({
10 version: z.string(),
11 language: z.enum(["typescript", "javascript"]),
12 modules: z.array(z.string()),
13 database: z.object({
14 provider: z.enum(["postgresql", "mysql", "sqlite", "mongodb"]),
15 schema: z.string(),
16 pool: z.object({
17 min: z.number().min(1),
18 max: z.number().min(1),
19 }).optional(),
20 }).optional(),
21 auth: z.object({
22 jwt: z.object({
23 accessTokenExpiry: z.string(),
24 refreshTokenExpiry: z.string(),
25 }),
26 }).optional(),
27 }).optional(),
28});
29
30// Load and parse config file
31function loadConfig() {
32 const configPath = join(process.cwd(), "servcraft.config.json");
33 const configFile = JSON.parse(readFileSync(configPath, "utf-8"));
34
35 // Validate configuration
36 const result = configSchema.safeParse(configFile);
37
38 if (!result.success) {
39 console.error("Invalid configuration:");
40 result.error.errors.forEach((err) => {
41 console.error(` ${err.path.join(".")}: ${err.message}`);
42 });
43 process.exit(1);
44 }
45
46 return result.data;
47}
48
49export const config = loadConfig();

Complete Example

A fully configured servcraft.config.json for a production application

servcraft.config.json
1{
2 "name": "my-api",
3 "version": "1.0.0",
4 "description": "Production-ready REST API with ServCraft",
5 "author": "Developer <dev@example.com>",
6
7 "servcraft": {
8 "version": ">=0.4.0",
9 "language": "typescript",
10 "modules": ["auth", "users", "email", "cache"],
11 "moduleSystem": "esm",
12
13 "database": {
14 "provider": "postgresql",
15 "schema": "prisma/schema.prisma",
16 "pool": {
17 "min": 2,
18 "max": 10,
19 "idleTimeoutMs": 30000,
20 "connectionTimeoutMs": 5000
21 }
22 },
23
24 "auth": {
25 "jwt": {
26 "accessTokenExpiry": "15m",
27 "refreshTokenExpiry": "7d",
28 "algorithm": "HS256"
29 },
30 "mfa": {
31 "enabled": true,
32 "issuer": "MyApp",
33 "window": 1
34 },
35 "oauth": {
36 "providers": ["google", "github", "discord"],
37 "callbackUrl": "http://localhost:3000/api/auth/oauth/callback"
38 },
39 "rateLimit": {
40 "windowMs": 900000,
41 "max": 100
42 }
43 },
44
45 "cors": {
46 "origin": ["http://localhost:3000", "https://myapp.com"],
47 "methods": ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
48 "credentials": true,
49 "maxAge": 86400
50 },
51
52 "logging": {
53 "level": "info",
54 "prettyPrint": true,
55 "timestamp": true
56 },
57
58 "email": {
59 "host": "smtp.example.com",
60 "port": 587,
61 "secure": false,
62 "from": "noreply@myapp.com"
63 }
64 },
65
66 "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 },
78
79 "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.