Quick Start
Create and run a complete AxilJS backend — HTTP, security, auth, and validation — in under 2 minutes.
Install the CLI#
Install the AxilJS CLI globally. This gives you the axil command for scaffolding, running, building, testing, and deploying projects.
npm install -g @axiljs/cliTip
You can also use npx @axiljs/cli create my-api without installing globally.
Create a project#
The CLI scaffolds a complete TypeScript project with all 17 packages pre-configured — zero manual setup.
axil create my-api
cd my-api
npm install
axil runYour server is now running at http://localhost:3000.
The axil run command uses incremental TypeScript compilation with hot reload. File changes trigger restarts in under 300ms.
Project structure#
my-api/
├── src/
│ ├── config/
│ │ └── app.config.ts # Typed configuration
│ ├── modules/
│ │ └── users/
│ │ ├── controllers/ # Route handlers
│ │ └── services/ # Business logic
│ ├── db/ # Database connection (if selected)
│ ├── migrations/ # Schema migrations (if selected)
│ └── main.ts # Application entry point
├── .env.example
├── package.json
└── tsconfig.jsonYour first server#
Open src/main.ts. The CLI generates a working server — here's what a full setup looks like:
import { Application, cors } from '@axiljs/core'
import { loadEnv, defineConfig } from '@axiljs/config'
import { helmet, rateLimit } from '@axiljs/security'
// Load and validate environment variables
loadEnv()
const config = defineConfig({
PORT: { type: 'number', default: 3000 },
HOST: { type: 'string', default: '127.0.0.1' }
})
// Create the application
const app = new Application({
server: { port: config.PORT, host: config.HOST }
})
// Security — applied globally in three lines
app.use(helmet())
app.use(cors())
app.use(rateLimit({ max: 100, windowMs: 60_000 }))
// Health check
app.get('/health', (_req, res) => {
res.success({
status: 'ok',
uptime: process.uptime(),
timestamp: new Date().toISOString()
}, 'Server is healthy')
})
// REST endpoints
app.get('/users/:id', (req, res) => {
res.success({ id: req.params.id }, 'User retrieved')
})
app.post('/users', (req, res) => {
const body = req.body as Record<string, unknown>
res.created(body, 'User created')
})
// Start
app.listen()
// Graceful shutdown
process.on('SIGINT', async () => { await app.close(); process.exit(0) })
process.on('SIGTERM', async () => { await app.close(); process.exit(0) })Save the file — the server restarts automatically.
Tip
Notice res.success() and res.created() — these are the built-in SyntaxilitY Response Manager methods. Every response is automatically formatted with consistent JSON structure including status codes, messages, and pagination metadata. No imports needed.
Test your API#
# Health check
curl http://localhost:3000/health
# Get user
curl http://localhost:3000/users/42
# Create user
curl -X POST http://localhost:3000/users \
-H "Content-Type: application/json" \
-d '{"name": "Tariq", "email": "tariq@axiljs.dev"}'Expected response from POST /users:
{
"status": 201,
"code": "HTTP_201_CREATED",
"message": "User created",
"data": {
"name": "Tariq",
"email": "tariq@axiljs.dev"
}
}Add authentication#
AxilJS includes JWT authentication with role-based access control — no third-party packages.
import { JWT, authenticate, requireRole } from '@axiljs/auth'
// Create JWT instance (uses HMAC-SHA256)
const jwt = new JWT(process.env.JWT_SECRET!)
// Protected route — requires valid token
app.get('/profile',
authenticate(jwt),
(req, res) => {
res.success({ user: req.locals.user }, 'Profile retrieved')
}
)
// Admin-only route — requires valid token + admin role
app.delete('/users/:id',
authenticate(jwt),
requireRole('admin'),
(req, res) => {
res.success({ deleted: req.params.id }, 'User deleted')
}
)Tip
Password hashing uses scrypt (Node.js native) — no bcrypt dependency needed. See Authentication docs for login/register examples.
Add validation#
Schema-based request validation with typed error responses — built into the ecosystem.
import { v, validate } from '@axiljs/validation'
app.post('/users',
validate({
body: v.object({
name: v.string().min(2).max(100),
email: v.string().email(),
role: v.enum(['admin', 'user']).optional()
})
}),
(req, res) => {
res.created(req.body, 'User created')
}
)Invalid requests automatically return structured errors:
{
"status": 422,
"code": "HTTP_422_UNPROCESSABLE_ENTITY",
"message": "Validation failed",
"errors": {
"email": "Must be a valid email address",
"name": "Minimum 2 characters required"
}
}Add a database#
AxilJS ORM supports PostgreSQL, MySQL, and SQLite with automatic migrations.
import { createConnection, BaseModel, Entity, PrimaryKey, Column } from '@axiljs/orm'
// Connect
const db = await createConnection({
driver: 'postgres',
url: process.env.DATABASE_URL!
})
// Define a model
@Entity('users')
class User extends BaseModel {
@PrimaryKey({ autoIncrement: true })
id!: number
@Column({ type: 'string', length: 255 })
name!: string
@Column({ type: 'string', unique: true })
email!: string
}
// Register driver
BaseModel.setDriver(db.getDriver(), 'postgres')
// Use it
const users = await User.all()
const user = await User.create({ name: 'Tariq', email: 'tariq@axiljs.dev' })
const found = await User.find(1)Tip
The ORM uses class-based models with decorators, a fluent QueryBuilder, and driver-aware migrations that auto-detect PostgreSQL, MySQL, or SQLite syntax. See ORM docs.
CLI commands#
The axil CLI covers the full development lifecycle:
| Command | Description |
|---|---|
axil create <name> | Scaffold a new project with interactive setup |
axil run | Start dev server with hot reload |
axil build | Compile TypeScript for production |
axil test | Run test files (*.test.ts, *.spec.ts) |
axil deploy | Generate Docker + Kubernetes manifests |
axil doctor | Diagnose project issues |
What's included#
Every AxilJS project has access to the full ecosystem — 17 packages under @axiljs:
| Package | Purpose |
|---|---|
@axiljs/core | HTTP server, router, middleware, SSE, response manager |
@axiljs/config | Environment loading, typed config validation |
@axiljs/security | Helmet, rate limiting, CSRF, input sanitization |
@axiljs/auth | JWT, scrypt password hashing, RBAC middleware |
@axiljs/validation | Schema-based request validation |
@axiljs/orm | PostgreSQL, MySQL, SQLite, migrations, query builder |
@axiljs/events | In-process event bus with wildcard support |
@axiljs/websocket | RFC 6455 WebSocket server with rooms |
@axiljs/queue | Message queue, cron scheduler, retry with backoff |
@axiljs/circuit | Circuit breaker, retry, timeout, fallback |
@axiljs/observability | Logging, Prometheus metrics, W3C tracing |
@axiljs/ai | LLM abstraction, RAG pipeline, agents, MCP |
@axiljs/cloud | Multi-tenancy, audit logs, feature flags, Docker/K8s |
@axiljs/memory | Memory leak detection, GC optimization |
@axiljs/testing | Test runner, assertions, HTTP test client |
@axiljs/cli | Project scaffolding, dev server, build, deploy |
@axiljs/pm | Process manager, clustering, graceful restart |
Next steps#
Now that you have a running server, explore the full platform:
- HTTP Server — Routing, middleware, static files, SSE
- Response Manager — Built-in JSON response formatting
- Authentication — JWT, RBAC, password hashing, login/register
- Validation — Request schemas, typed errors
- Database & ORM — Models, migrations, query builder
- AI Platform — LLM providers, RAG pipeline, agents
- Security — Helmet, rate limiting, CSRF, XSS
- WebSockets — Real-time with rooms and broadcast
- Queue & Scheduler — Background jobs, cron, retry
- Observability — Logging, metrics, distributed tracing
- Cloud Deploy — Docker, Kubernetes, multi-tenancy