Getting Started

Project Structure

The files axil create generates in AxilJS 0.3.6: src/main.ts, modules, migrations, package.json, tsconfig.json, .env.example and template layouts.

6 min readUpdated DocumentationEdit this page
On this page9

This page describes exactly what axil create writes. There are two shapes: the Custom stack (a modular starter you grow with axil generate) and the templates (complete applications, see Templates). Both share the same package.json, tsconfig.json and .gitignore conventions.

Custom stack layout

Created when you pick Custom in the picker, or pass --db, --auth, --ai, --ws, --queue or --yes without --template:

Output
TXT
my-api/
├── src/
│   ├── main.ts                      # entry point
│   ├── config/
│   │   └── app.config.ts            # AppConfig for standalone scripts
│   ├── modules/
│   │   └── users/
│   │       ├── controllers/
│   │       │   └── users.controller.ts
│   │       └── services/
│   │           └── users.service.ts
│   ├── db/                          # only with a database
│   │   └── connection.ts
│   └── migrations/                  # only with a database
│       └── 001_create_users.ts
├── .env.example
├── .gitignore
├── package.json
├── package-lock.json                # written by npm install
├── README.md
└── tsconfig.json

Note

The structure is a starting point, not a rule. AxilJS has no module system or decorators you must use to register routes: a controller is a plain class with a register(app) method.

src/main.ts

The entry point loads .env, builds a typed config, creates the Application, registers routes and listens. For a Custom project with auth on and no database it looks like this:

TypeScript
TS
1import { Application, cors } from '@axiljs/core'
2import { loadEnv, defineConfig } from '@axiljs/config'
3import { JWT } from '@axiljs/auth'
4import { UsersController } from './modules/users/controllers/users.controller.js'
5
6loadEnv()
7
8const config = defineConfig({
9  PORT:     { type: 'number', default: 3000 },
10  HOST:     { type: 'string', default: '127.0.0.1' },
11  NODE_ENV: { type: 'string', default: 'development' },
12  JWT_SECRET: {
13    type: 'string',
14    default: 'change-this-secret-to-a-random-value-with-at-least-32-characters'
15  }
16})
17
18const app = new Application({
19  server: { port: config.PORT, host: config.HOST },
20  env: config.NODE_ENV
21})
22
23app.use(cors())
24
25const jwt = new JWT(config.JWT_SECRET)
26void jwt
27
28app.get('/health', (_req, res) => {
29  res.json({ status: 'ok', service: 'my-api', timestamp: new Date().toISOString() })
30})
31
32new UsersController().register(app)
33
34await app.listen()
35
36process.on('SIGINT', async () => { await app.close(); process.exit(0) })
37process.on('SIGTERM', async () => { await app.close(); process.exit(0) })

With a database, main.ts also calls await connectDB() from ./db/connection.js. With --ws it attaches a WSServer at /ws to the HTTP server; with --queue it starts a Queue and a Scheduler.

Projects are ESM ("type": "module", module: Node16), so relative imports end in .js even though the files are .ts, and top-level await works.

Modules

src/modules/<name>/ groups one feature:

PathResponsibility
controllers/<name>.controller.tsRoutes and HTTP handling; register(app) wires GET/POST /<name> and GET/PUT/DELETE /<name>/:id
services/<name>.service.tsBusiness logic; in memory without a database, SQL through getDB() with one
entities/<name>.entity.tsORM entity (created by axil g entity)

Controllers answer with the response envelope (res.success, res.created, res.noContent) and services throw NotFoundError and friends, which the framework turns into JSON errors. When auth is on, the list route is protected with authenticate().

Generate more with the CLI. Files are never overwritten unless you pass --force:

Terminal
❯axil generate module products # controller + service (+ migration with a database)
❯axil g controller orders
❯axil g service billing
❯axil g entity product
❯axil g migration add_price_to_products

Then register the new controller in src/main.ts:

TypeScript
TS
new ProductsController().register(app)

Database files

With --db sqlite|postgres|mysql:

  • src/db/connection.ts exports connectDB() and getDB(). SQLite reads DATABASE_FILENAME (default ./dev.db); Postgres and MySQL read DATABASE_URL.
  • src/migrations/001_create_users.ts is a Migration object with up(db) / down(db):
TypeScript
TS
1import type { Migration } from '@axiljs/orm'
2
3const migration: Migration = {
4  async up(db) {
5    await db.query(`
6      CREATE TABLE IF NOT EXISTS users (
7        id         INTEGER PRIMARY KEY AUTOINCREMENT,
8        name       VARCHAR(255) NOT NULL,
9        email      VARCHAR(255) NOT NULL UNIQUE,
10        created_at TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP
11      )
12    `)
13  },
14
15  async down(db) {
16    await db.query('DROP TABLE IF EXISTS users')
17  }
18}
19
20export default migration

The id column type follows the driver. Apply migrations with npm run migrate (which runs axil migrate); see Project Commands.

Template layout

Templates use a flatter layout built around an app factory, so tests can drive the app without opening a port. The Minimal API, for example:

Output
TXT
my-api/
├── src/
│   ├── main.ts                      # loadEnv, createApp(config), listen, graceful shutdown
│   ├── app.ts                       # createApp(config): routes, middleware, error handler
│   ├── app.test.ts                  # route tests (npm test)
│   ├── config.ts                    # typed config with defineConfig
│   └── middleware/
│       └── error-handler.ts         # one JSON error shape
├── .env.example
├── .gitignore
├── package.json
├── README.md
└── tsconfig.json

Larger templates add folders such as routes/, repositories/, models/, jobs/, webhooks/, ai/ or telemetry/, a public/ folder for browser clients, and in high-scale-api an axil.scaling.json at the root. Each template's README.md has its own project-structure section.

package.json

Custom projects get these scripts (templates add their own, such as migrate or send-test-webhook):

JSON
JSON
1{
2  "type": "module",
3  "scripts": {
4    "dev": "axil run",
5    "build": "tsc",
6    "start": "node dist/main.js",
7    "test": "axil test",
8    "migrate": "axil migrate"
9  }
10}

migrate is only present with a database. Dependencies are the @axiljs/* packages you chose on the ^0.3.0 range, plus the database driver (pg, mysql2 or better-sqlite3). devDependencies are always @axiljs/cli, @axiljs/studio (so axil run starts Studio), @axiljs/testing (used by axil test), typescript and @types/node.

tsconfig.json

Generated identically for every project:

JSON
JSON
1{
2  "compilerOptions": {
3    "target": "ES2023",
4    "module": "Node16",
5    "moduleResolution": "Node16",
6    "lib": ["ES2023"],
7    "types": ["node"],
8    "strict": true,
9    "esModuleInterop": true,
10    "skipLibCheck": true,
11    "forceConsistentCasingInFileNames": true,
12    "isolatedModules": true,
13    "rootDir": "./src",
14    "outDir": "./dist",
15    "incremental": true,
16    "tsBuildInfoFile": "./dist/.tsbuildinfo",
17    "experimentalDecorators": true,
18    "emitDecoratorMetadata": false,
19    "declaration": true,
20    "declarationMap": true,
21    "sourceMap": true
22  },
23  "include": ["src/**/*"],
24  "exclude": ["dist", "node_modules"]
25}

experimentalDecorators is required by the ORM's @Entity/@Column and the t* semantic decorators. axil run and axil test rely on outDir: they compile src/ to dist/ and run the compiled files.

Environment files

.env.example lists every variable the project reads. Copy it to .env before the first run (cp .env.example .env, or Copy-Item .env.example .env in PowerShell). A Custom project with auth and SQLite gets:

Terminal
# Server
PORT=3000
HOST=127.0.0.1
NODE_ENV=development
# Authentication
# Replace with a securely generated random string (32+ characters).
JWT_SECRET=change-this-secret-to-a-random-value-with-at-least-32-characters
# SQLite
# Path to the database file. Created automatically on first run.
DATABASE_FILENAME=./dev.db

axil run reads PORT from .env to know where the app listens and starts Studio on PORT + 1.

Warning

Never commit .env. The generated .gitignore already excludes node_modules/, dist/, .env, .env.local and *.log.

Next steps

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY