---
url: /tutorial.md
description: >-
  Build a full KosmoJS application step by step - routing, validation,
  middleware, fetch clients, pages, SSR, and multi-folder architecture.
---

A step-by-step walkthrough covering everything KosmoJS provides.

## Create a Project

### Tutorial | Create a Project | npm

```sh
npm create kosmo
```

### Tutorial | Create a Project | pnpm

```sh
pnpm create kosmo
```

### Tutorial | Create a Project | yarn

```sh
yarn create kosmo
```

A short interactive setup creates the project together with your first source folder,
prompting for the name, frontend and backend.

Use `.` to bootstrap in the current directory:

```sh
npm create kosmo .
```

The first source folder is always `app`, serving pages at `/` and its API at `/api`.
Both `frontend` and `backend` can be further configured in folder's [kosmo.config.ts](/essentials/config.md).

Provide up front the `--name` and `--frontend`/`--backend` (or `--no-frontend`/`--no-backend` counterparts)
and no prompts appear:

### Tutorial | Create a Project | npm

```sh
# npm needs an extra -- to pass flags through
npm create kosmo -- --name demo --frontend solid --backend hono
```

### Tutorial | Create a Project | pnpm

```sh
pnpm create kosmo --name demo --frontend solid --backend hono
```

### Tutorial | Create a Project | yarn

```sh
yarn create kosmo --name demo --frontend solid --backend hono
```

Need no backend? Provide `--no-backend` flag: `--name demo --frontend solid --no-backend`

Same for the frontend, provide the `--no-frontend` flag to get a backend-only setup.

> **Worth Noting:** `--name` ignored when using `.` to bootstrap in current directory.

***

After bootstrap, `cd` into freshly created project (unless bootstrapped in the current folder):

```sh
cd ./demo
```

#### Install Dependencies

##### Tutorial | Install Dependencies | npm

```sh
npm install
```

##### Tutorial | Install Dependencies | pnpm

```sh
pnpm install
```

##### Tutorial | Install Dependencies | yarn

```sh
yarn install
```

The scaffold is complete, everything comes filled in.
What it doesn't have yet is routes, and that is what you add next.

## Start the dev server

The dev server watches your routes and recomputes as you work -
and seeds starter code into any route or page file you create empty:

### Tutorial | Start the dev server | npm

```sh
npm run dev
```

### Tutorial | Start the dev server | pnpm

```sh
pnpm dev
```

### Tutorial | Start the dev server | yarn

```sh
yarn dev
```

Your app is now running at `http://localhost:4556`.

## Create Your First API Route

Create `api/users/[id]/index.ts` - KosmoJS detects the file and seeds boilerplate:

### Tutorial | Create Your First API Route | Hono

```ts
// Hono: api/users/[id]/index.ts
import { defineRoute } from "_/api";

export default defineRoute<"users/[id]">(({ GET }) => [
  GET(async (ctx) => {
    return ctx.text("users/[id] route starts here - replace this response with real logic.");
  }),
]);
```

### Tutorial | Create Your First API Route | H3

```ts
// H3: api/users/[id]/index.ts
import { defineRoute } from "_/api";

export default defineRoute<"users/[id]">(({ GET }) => [
  GET(async (event) => {
    return "users/[id] route starts here - replace this response with real logic.";
  }),
]);
```

### Tutorial | Create Your First API Route | Koa

```ts
// Koa: api/users/[id]/index.ts
import { defineRoute } from "_/api";

export default defineRoute<"users/[id]">(({ GET }) => [
  GET(async (ctx) => {
    ctx.body = "users/[id] route starts here - replace this response with real logic.";
  }),
]);
```

> Some editors show seeded content immediately; others need a brief unfocus/refocus.

Replace with real logic:

### Tutorial | Create Your First API Route | Hono

```ts
// Hono: api/users/[id]/index.ts
import { defineRoute } from "_/api";

export default defineRoute<"users/[id]">(({ GET }) => [
  GET(async (ctx) => {
    const { id } = ctx.req.param();
    const user = { id, name: "Jane Smith", email: "jane@example.com" };
    return ctx.json(user);
  }),
]);
```

### Tutorial | Create Your First API Route | H3

```ts
// H3: api/users/[id]/index.ts
import { defineRoute } from "_/api";

export default defineRoute<"users/[id]">(({ GET }) => [
  GET(async (event) => {
    const { id } = event.context.params;
    const user = { id, name: "Jane Smith", email: "jane@example.com" };
    return user;
  }),
]);
```

### Tutorial | Create Your First API Route | Koa

```ts
// Koa: api/users/[id]/index.ts
import { defineRoute } from "_/api";

export default defineRoute<"users/[id]">(({ GET }) => [
  GET(async (ctx) => {
    const { id } = ctx.params;
    const user = { id, name: "Jane Smith", email: "jane@example.com" };
    ctx.body = user;
  }),
]);
```

With dev server running, visit `http://localhost:4556/api/users/123`:

[Details ›](/backend/intro.md)

## Add Validation

### Parameter Validation

Pass a tuple as the second type argument to refine params.
Each position maps to a route parameter in order.
Validation works identically across all frameworks, read validated params via `*.validated.params`:

```ts
type User = { id: number; name: string; email: string }

export default defineRoute<"users/[id]", [
  number // [!code hl]
]>(({ GET }) => [
  GET(async (ctx) => {
    const { id } = ctx.validated.params; // id is a validated number [!code hl]
    // ...
  }),
]);
```

Use `VRefine` for additional constraints (no import needed):

```ts
defineRoute<"users/[id]", [
  VRefine<number, { minimum: 1, multipleOf: 1 }> // positive integer
]>
```

Raw params still can be accessed via `ctx.req.param()`/`event.context.params`/`ctx.params`,
but they are untyped strings - prefer `ctx.validated.params`.

### Payload/Response Validation

The first type argument to each method handler defines validation targets.

Metadata targets (any method): `query` · `headers` · `cookies`

Body targets (mutually exclusive, POST/PUT/PATCH only): `json` · `form` · `raw`

#### Tutorial | Payload/Response Validation | Hono

```ts
// Hono: api/users/index.ts
import type { CreateUserPayload, User } from "./types";

export default defineRoute<"users">(({ POST }) => [
  POST<{
    json: CreateUserPayload, // [!code hl]
    response: [200, "json", User] // [!code hl]
  }>(async (ctx) => {
    const { name, email, age } = ctx.validated.json;
    return ctx.json({ id: 1, name, email, age });
  }),
]);
```

#### Tutorial | Payload/Response Validation | H3

```ts
// H3: api/users/index.ts
import type { CreateUserPayload, User } from "./types";

export default defineRoute<"users">(({ POST }) => [
  POST<{
    json: CreateUserPayload, // [!code hl]
    response: [200, "json", User] // [!code hl]
  }>(async (ctx) => {
    const { name, email, age } = ctx.validated.json;
    return { id: 1, name, email, age };
  }),
]);
```

#### Tutorial | Payload/Response Validation | Koa

```ts
// Koa: api/users/index.ts
import type { CreateUserPayload, User } from "./types";

export default defineRoute<"users">(({ POST }) => [
  POST<{
    json: CreateUserPayload, // [!code hl]
    response: [200, "json", User] // [!code hl]
  }>(async (ctx) => {
    const { name, email, age } = ctx.validated.json;
    ctx.body = { id: 1, name, email, age };
  }),
]);
```

```ts [./types.ts]
export type CreateUserPayload = {
  name: string;
  email: VRefine<string, { format: "email" }>;
  age?: number;
}

export type User = { id: number; name: string; email: string }
```

Payload is validated before your handler runs. Response is validated before it's sent.

[Details ›](/validation/intro.md)

## Add Middleware

For simple cases, wire middleware inline with `use`:

```ts
import { logRequest } from "~/middleware/logging";

export default defineRoute<"users/[id]">(({ use, GET }) => [
  use(logRequest),
  GET(async (ctx) => { /* ... */ }),
]);
```

For anything shared across routes, use cascading middleware instead.
Create `api/users/use.ts` - it wraps every route under `/api/users` automatically:

```ts [api/users/use.ts]
import { use } from "_/api";

export default [
  use(async (ctx, next) => {
    // runs for every route under /api/users
    return next();
  })
];
```

No imports in route files, no repetition. Parent `use.ts` files wrap child routes automatically.

[Details ›](/backend/middleware.md)

## Fetch Clients

Fetch clients are fully typed and validated client-side using the same high-performance
TypeBox validators as the server - identical results, no duplication, no drift.

Invalid requests are caught before they leave the browser:

### Tutorial | Fetch Clients | React

```tsx
// React: pages/users/[id]/index.tsx
import { useState, useEffect } from "react";
import { useParams } from "react-router";
import fetchClients from "_/fetch";

const { GET } = fetchClients["users/[id]"];

export default function UserPage() {
  const params = useParams();
  const [user, setUser] = useState(null);
  useEffect(() => { GET([params.id]).then(setUser); }, [params.id]);
  // ...
}
```

### Tutorial | Fetch Clients | Solid

```tsx
// Solid: pages/users/[id]/index.tsx
import { useParams, createAsync } from "@solidjs/router";
import fetchClients from "_/fetch";

const { GET } = fetchClients["users/[id]"];

export default function UserPage() {
  const params = useParams();
  const user = createAsync(() => GET([params.id]));
  // ...
}
```

### Tutorial | Fetch Clients | Vue

```vue
<!-- Vue: pages/users/[id]/index.vue -->
<script lang="ts">
import fetchClients from "_/fetch";

const { GET } = fetchClients["users/[id]"];

// a plain <script> block, since <script setup> cannot hold ES exports
export const loader = ({ params }) => GET([params.id]);
</script>

<script setup lang="ts">
import { useLoaderData } from "_/use";

const user = useLoaderData();
// ...
</script>
```

### Tutorial | Fetch Clients | Svelte

```svelte
<!-- Svelte: pages/users/[id]/index.svelte -->
<script module lang="ts">
import fetchClients from "_/fetch";

const { GET } = fetchClients["users/[id]"];

export const loader = ({ params }) => GET([params.id]);
</script>

<script lang="ts">
import { useLoaderData } from "_/use";

const user = useLoaderData();
// ...
</script>
```

### Tutorial | Fetch Clients | MDX

```mdx
{/* MDX: pages/users/[id]/index.mdx */}
import fetchClients from "_/fetch";
import { useLoaderData } from "_/use";

export const { GET } = fetchClients["users/[id]"];

export const loader = ({ params }) => GET([params.id]);

export const User = () => {
  const user = useLoaderData();
  // ...
};

<User />
```

Server-side validation still runs even when endpoints are called directly - client validation is additive, not a substitute.

[Details ›](/fetch/intro.md)

## Create Client Pages

Pages live in `pages/` and follow the same directory-based routing as API routes.
Create `pages/users/index.tsx` - KosmoJS seeds framework-specific boilerplate.

Add a layout for shared UI across route groups - create `pages/users/layout.tsx`:

```txt
pages/
└── users/
    ├── layout.tsx    ← wraps all pages under /users
    └── index.tsx
```

Layouts can be nested - deeper layouts wrap inner layouts, matching your route hierarchy.

[Details ›](/frontend/routing.md)

## Server-Side Rendering

Every folder has it on already. To turn it off, or back on, edit `kosmo.config.ts`:

```ts [kosmo.config.ts]
import { defineConfig } from "@kosmojs/dev";

export default defineConfig({
  frontend: {
    // ...
    ssr: true, // [!code hl]
  },
});
```

> Restart dev server after changing `kosmo.config.ts`.

KosmoJS seeds `entry/server.ts` - your SSR orchestration file.
Critical CSS is extracted and inlined automatically; remaining styles load asynchronously.

See it running - `pnpm preview` builds and serves the production output, and rebuilds whenever you save:

```sh
pnpm preview
```

For deployment, `pnpm build` writes `dist/run.js`, which serves every source folder from one process.
Folders are also bundled separately, so they can be deployed, scaled and run independently when that suits you better.

[Details ›](/frontend/server-side-render.md) ·
[Dev / Build / Run ›](/dev-build-run/building-for-production.md)

## Add More Source Folders

Your project starts with the source folder created at bootstrap.
As the app grows, add more - one per distinct concern (main app, admin panel, marketing site, etc.).

Each is independent with its own set of frameworks, config, base URL, etc.

### Tutorial | Add More Source Folders | npm

```sh
npm run folder
```

### Tutorial | Add More Source Folders | pnpm

```sh
pnpm folder
```

### Tutorial | Add More Source Folders | yarn

```sh
yarn folder
```

You'll be prompted for the folder name, frontend and backend.
The name gives the folder its prefixes: pages at `/<name>`, API at `/<name>/api`,
configurable later in folder's [kosmo.config.ts](/essentials/config.md).

Non-interactive mode is also supported; pass flags up front and no prompts appear:

* `--name` folder name, required
* `--frontend solid|react|vue|svelte|mdx` or `--no-frontend` (one required)
* `--backend hono|h3|koa` or `--no-backend` (one required)
* `--overwrite` to proceed into a non-empty directory

Everything else - SSR, SSG, TanStack Query - is a key in the folder's [kosmo.config.ts](/essentials/config.md),
not a flag at creation.

### Tutorial | Add More Source Folders | npm

```sh
npm run folder -- --name <name> --frontend solid --backend hono
```

### Tutorial | Add More Source Folders | pnpm

```sh
pnpm folder --name <name> --frontend solid --backend hono
```

### Tutorial | Add More Source Folders | yarn

```sh
yarn folder --name <name> --frontend solid --backend hono
```

Need no backend? Provide the `--no-backend` flag for a frontend-only folder (a static docs or marketing site).

Need no client? Provide the `--no-frontend` flag for a backend-only folder (an API service with no UI).

The choice is always explicit - a forgotten flag is an error, never a silent default:

### Tutorial | Add More Source Folders | npm

```sh
npm run folder -- --name api  --backend hono --no-frontend   # API only, no UI
npm run folder -- --name docs --frontend mdx --no-backend    # UI only, no backend
```

### Tutorial | Add More Source Folders | pnpm

```sh
pnpm folder --name api  --backend hono --no-frontend   # API only, no UI
pnpm folder --name docs --frontend mdx  --no-backend   # UI only, no backend
```

### Tutorial | Add More Source Folders | yarn

```sh
yarn folder --name api  --backend hono --no-frontend   # API only, no UI
yarn folder --name docs --frontend mdx  --no-backend   # UI only, no backend
```

Creating a source folder adds framework-specific dependencies. Install them:

### Tutorial | Add More Source Folders | npm

```sh
npm install
```

### Tutorial | Add More Source Folders | pnpm

```sh
pnpm install
```

### Tutorial | Add More Source Folders | yarn

```sh
yarn install
```

## Directory-Based Routing

Folder names become URL segments. Each route requires an `index` file:

```txt
api/
  users/
    index.ts          -> /api/users
    [id]/
      index.ts        -> /api/users/:id

pages/
  users/
    index.tsx         -> /users
    [id]/
      index.tsx       -> /users/:id
```

Parameters: `[id]` required · `{id}` optional · `{...path}` splat.
Same pattern for API and pages - learn once, use everywhere.

[Details ›](/routing/intro.md)

## Path Mappings

Your project starts with a minimal `tsconfig.json`:

```json [tsconfig.json]
{
  "extends": "./var/lib/tsconfig.json",
  "exclude": ["./dist/", "./src/", "./var/", "./public/"]
}
```

The extended config provides path mappings used throughout the framework.
You can add your own paths, but these prefixes are reserved:

* `@/*` - Root-level imports
* `~/*` - Source folder imports
* `_/*` - Derived code imports
* `#src/*` - Source folder imports for any folder, by name
* `#lib/*` - Derived code imports for any folder, by name

[Project Structure ›](/essentials/project-structure.md#path-mappings) walks the whole layout - what
lives in `src/` versus `var/lib/`, and what each alias resolves to.

***

### Next Steps

**Core patterns:** [Routing](/routing/intro.md) · [Validation](/validation/intro.md) · [Middleware](/backend/middleware.md) · [Layouts](/frontend/routing.md) · [Fetch Clients](/fetch/start.md)

**Advanced:** [VRefine](/validation/refine.md) · [OpenAPI](/openapi/intro.md) · [Production Builds](/dev-build-run/building-for-production.md)
