Getting Started

Quick Start

Create and run a complete AxilJS backend — HTTP, security, auth, and validation — in under 2 minutes.

6 min readDocumentationEdit this page

Install the CLI#

Install the AxilJS CLI globally. This gives you the axil command for scaffolding, running, building, testing, and deploying projects.

bash
npm install -g @axiljs/cli

Tip

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.

bash
axil create my-api
cd my-api
npm install
axil run

Your 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#

typescript
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.json

Your first server#

Open src/main.ts. The CLI generates a working server — here's what a full setup looks like:

typescript
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#

bash
# 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:

json
{
  "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.

typescript
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.

typescript
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:

json
{
  "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.

typescript
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:

CommandDescription
axil create <name>Scaffold a new project with interactive setup
axil runStart dev server with hot reload
axil buildCompile TypeScript for production
axil testRun test files (*.test.ts, *.spec.ts)
axil deployGenerate Docker + Kubernetes manifests
axil doctorDiagnose project issues

What's included#

Every AxilJS project has access to the full ecosystem — 17 packages under @axiljs:

PackagePurpose
@axiljs/coreHTTP server, router, middleware, SSE, response manager
@axiljs/configEnvironment loading, typed config validation
@axiljs/securityHelmet, rate limiting, CSRF, input sanitization
@axiljs/authJWT, scrypt password hashing, RBAC middleware
@axiljs/validationSchema-based request validation
@axiljs/ormPostgreSQL, MySQL, SQLite, migrations, query builder
@axiljs/eventsIn-process event bus with wildcard support
@axiljs/websocketRFC 6455 WebSocket server with rooms
@axiljs/queueMessage queue, cron scheduler, retry with backoff
@axiljs/circuitCircuit breaker, retry, timeout, fallback
@axiljs/observabilityLogging, Prometheus metrics, W3C tracing
@axiljs/aiLLM abstraction, RAG pipeline, agents, MCP
@axiljs/cloudMulti-tenancy, audit logs, feature flags, Docker/K8s
@axiljs/memoryMemory leak detection, GC optimization
@axiljs/testingTest runner, assertions, HTTP test client
@axiljs/cliProject scaffolding, dev server, build, deploy
@axiljs/pmProcess manager, clustering, graceful restart

Next steps#

Now that you have a running server, explore the full platform:

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY