Getting Started

Quick Start

Build and run your first AxilJS backend with HTTP, security, authentication, validation, and database support.

8 min readDocumentationEdit this page

Create your first AxilJS application

This guide takes you from an empty directory to a running AxilJS backend.

By the end, you will have:

  • A TypeScript HTTP server
  • Security middleware
  • Structured API responses
  • JWT authentication
  • Request validation
  • Database connectivity
  • Hot reload during development

Install the CLI

Install the AxilJS CLI globally:

Terminal
npm install -g @axiljs/cli

Verify the installation:

Terminal
axil --version

Tip

You can also create a project without installing the CLI globally: npx @axiljs/cli create my-api

Create a project

Create a new AxilJS application:

Terminal
axil create my-api
cd my-api
npm install

Then start the development server:

Terminal
axil run

Your application is available at:

text
http://localhost:3000

ORM Studio starts alongside the application by default:

text
http://localhost:3001

Info

axil run watches your source files, recompiles changes, and restarts the application automatically during development.

Project structure

The generated project provides a standard starting structure:

text
my-api/
├── src/
│   ├── config/
│   │   └── app.config.ts
│   ├── modules/
│   │   └── users/
│   │       ├── controllers/
│   │       ├── services/
│   │       └── users.test.ts
│   ├── migrations/
│   └── main.ts
├── .env.example
├── package.json
├── tsconfig.json
└── axil.lock

You can adapt this structure as your application grows. AxilJS supports modular applications, MVC, monoliths, and distributed architectures.

Build your first server

Open src/main.ts and create the application:

typescript
import { Application, cors } from '@axiljs/core'
import { loadEnv, defineConfig } from '@axiljs/config'
import { helmet, rateLimit } from '@axiljs/security'
 
loadEnv()
 
const config = defineConfig({
  PORT: {
    type: 'number',
    default: 3000
  },
 
  HOST: {
    type: 'string',
    default: '127.0.0.1'
  }
})
 
const app = new Application({
  server: {
    port: config.PORT,
    host: config.HOST
  }
})
 
app.use(helmet())
app.use(cors())
app.use(
  rateLimit({
    max: 100,
    windowMs: 60_000
  })
)
 
app.get('/health', (_req, res) => {
  res.success(
    {
      status: 'ok',
      uptime: process.uptime(),
      timestamp: new Date().toISOString()
    },
    'Server is healthy'
  )
})
 
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'
  )
})
 
app.listen()

Save the file. axil run watches the source tree and restarts the server when the file changes.

Built-in response manager

AxilJS provides structured response methods directly on the response object.

typescript
res.success(data, message)
res.created(data, message)
res.paginated(items, total, page, limit, message)
 
res.badRequest(message)
res.unauthorized(message)
res.forbidden(message)
res.notFound(message)
res.conflict(message)
res.validationError(message)
 
res.serverError(message)
res.tooManyRequests()
res.serviceUnavailable()
typescript
res.HTTP_200_OK(users, 'Users fetched');
 
res.HTTP_201_CREATED(user, 'User created');
 
res.HTTP_400_BAD_REQUEST('Invalid request');
 
res.HTTP_401_UNAUTHORIZED('Invalid token');
 
res.HTTP_403_FORBIDDEN('Permission denied');
 
res.HTTP_404_NOT_FOUND('User not found');
 
res.HTTP_409_CONFLICT('Email already exists');
 
res.HTTP_500_INTERNAL_SERVER_ERROR('Database error');
 
res.HTTP_503_SERVICE_UNAVAILABLE('Service unavailable');
 
res.HTTP_204_NO_CONTENT();
 
res.HTTP_405_METHOD_NOT_ALLOWED();
 
res.HTTP_406_NOT_ACCEPTABLE();
 
res.HTTP_415_UNSUPPORTED_MEDIA_TYPE();
 
res.HTTP_429_TOO_MANY_REQUESTS();
 
res.HTTP_422_UNPROCESSABLE_ENTITY();

For example:

typescript
app.get('/users/:id', (req, res) => {
  res.success(
    {
      id: req.params.id
    },
    'User retrieved'
  )
})

A successful response follows a consistent structure:

json
{
  "status": 200,
  "code": "HTTP_200_OK",
  "message": "User retrieved",
  "data": {
    "id": "42"
  }
}

Paginated responses also include pagination metadata.

Tip

The response manager is built into AxilJS. You do not need to import a separate response-formatting package.

Test your API

With the server running, test the health endpoint:

Terminal
curl http://localhost:3000/health

Test the user endpoint:

Terminal
curl http://localhost:3000/users/42

Create a user:

Terminal
curl -X POST http://localhost:3000/users ^
-H "Content-Type: application/json" ^
-d "{\"name\":\"Tariq\",\"email\":\"tariq@axiljs.dev\"}"

On Unix-like systems, the equivalent command is:

Terminal
curl -X POST http://localhost:3000/users \
-H "Content-Type: application/json" \
-d '{"name":"Tariq","email":"tariq@axiljs.dev"}'

A successful creation response looks like:

json
{
  "status": 201,
  "code": "HTTP_201_CREATED",
  "message": "User created",
  "data": {
    "name": "Tariq",
    "email": "tariq@axiljs.dev"
  }
}

Add authentication

AxilJS provides JWT authentication and role-based access control through @axiljs/auth.

Install the package if it is not already present:

Terminal
npm install @axiljs/auth

Then create a JWT instance:

typescript
import {
  JWT,
  authenticate,
  requireRole
} from '@axiljs/auth'
 
const jwt = new JWT(
  process.env.JWT_SECRET!
)

Protect a route:

typescript
app.get(
  '/profile',
  authenticate(jwt),
  (req, res) => {
    res.success(
      {
        user: req.locals.user
      },
      'Profile retrieved'
    )
  }
)

Require a specific role:

typescript
app.delete(
  '/users/:id',
  authenticate(jwt),
  requireRole('admin'),
  (req, res) => {
    res.success(
      {
        deleted: req.params.id
      },
      'User deleted'
    )
  }
)

Tip

AxilJS authentication includes password hashing and RBAC middleware. See the Authentication docs for login, registration, token, and role-management examples.

Add request validation

Use @axiljs/validation to validate request bodies before your handlers execute.

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 input produces a structured validation response:

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
  • SQLite
  • Class-based models
  • Decorators
  • Query builders
  • Repositories
  • Database migrations

Install the ORM:

Terminal
npm install @axiljs/orm

Create a database connection:

typescript
import {
  createConnection,
  BaseModel,
  Entity,
  PrimaryKey,
  Column
} from '@axiljs/orm'
 
const db = await createConnection({
  driver: 'postgres',
  url: process.env.DATABASE_URL!
})

Define a model:

typescript
@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 the database driver:

typescript
BaseModel.setDriver(
  db.getDriver(),
  'postgres'
)

You can then work with the model:

typescript
const users = await User.all()
 
const user = await User.create({
  name: 'Tariq',
  email: 'tariq@axiljs.dev'
})
 
const found = await User.find(1)

Tip

See the ORM documentation for database connections, entities, repositories, query building, and migrations.

Explore ORM Studio

When you run:

Terminal
axil run

AxilJS starts ORM Studio alongside your development server.

Open:

text
http://localhost:3001

Studio provides:

  • API Explorer
  • Try It Out
  • Database Browser
  • SQL Query Editor
  • Realtime Monitor
  • API collection export
  • QR code access

This gives you a visual development interface without requiring a separate API client for basic exploration.

CLI workflow

The axil CLI covers the main application lifecycle:

CommandDescription
axil create <name>Create a new AxilJS project
axil runStart the development server with hot reload
axil buildCompile the application for production
axil test [pattern]Run matching test files
axil deployGenerate Docker and Kubernetes deployment files
axil install [package]Install an AxilJS package
axil install -D [package]Install a development dependency
axil doctorDiagnose project issues
axil --versionDisplay the CLI version

What's included?

The AxilJS ecosystem is organized under the @axiljs scope.

PackagePurpose
@axiljs/coreHTTP server, router, middleware, SSE, static files, response manager
@axiljs/configEnvironment loading and typed configuration
@axiljs/securityHelmet, rate limiting, CSRF, and sanitization
@axiljs/authJWT, password hashing, authentication, and RBAC
@axiljs/validationSchema-based request validation
@axiljs/ormPostgreSQL, MySQL, SQLite, and migrations
@axiljs/testingTest runner, assertions, and HTTP test client
@axiljs/eventsIn-process event bus and pub/sub
@axiljs/websocketWebSocket server and rooms
@axiljs/queueMessage queue, scheduler, retries, and delayed jobs
@axiljs/circuitCircuit breaker, retry, timeout, and fallback
@axiljs/observabilityLogging, metrics, tracing, and health checks
@axiljs/aiAI providers, RAG, agents, vector storage, and MCP
@axiljs/cloudMulti-tenancy, audit logs, feature flags, and deployment
@axiljs/memoryMemory monitoring, leak detection, GC, and optimization
@axiljs/pmAxilJS package and process-management capabilities
@axiljs/studioBrowser-based developer dashboard
@axiljs/cliProject scaffolding and development lifecycle commands

Next steps

You now have the foundation for a complete AxilJS backend.

Continue with the part of the platform you need:

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY