DEV Community

Cover image for Meet Megh: Build validated REST API in TypeScript in 5 minutes
Tareq Hossain
Tareq Hossain

Posted on

Meet Megh: Build validated REST API in TypeScript in 5 minutes

Most Node backends start the same way. You pick Express or Fastify, then
spend days choosing and wiring a validator, a DI approach, OpenAPI docs, an
error format and pagination. Or you pick NestJS and write modules, providers
and imports arrays before your first endpoint returns anything.

Megh(মেঘ, Cloud in Bengali) is a third option: a TypeScript-first framework on
Fastify that ships those parts in one install, without
the module system.

In this post we'll build a complete Todo REST API with Megh:

  • full CRUD plus filtering, search and pagination
  • request validation that rejects bad and unknown input
  • interactive API docs, generated for you
  • consistent 400 / 404 errors

We won't set up a database. Megh has a built-in in-memory store called
Collection, which is enough for prototypes, demos and tests. At the end
we'll look at how to move to a real database, and at when Megh is (and isn't)
the right choice.

Megh is pre-1.0 (0.6.x at the time of writing). The API is settling, but it
may still change. It's a good fit for side projects, internal tools and
evaluation.

1. Create the project

You need Node.js 22 or newer.

npx @meghjs/cli new todo-api
cd todo-api
npm run start:dev
Enter fullscreen mode Exit fullscreen mode

The CLI asks which package manager to use and which features to include.
Choose OpenAPI and skip the ORM for now. Then open
http://localhost:4000 and you'll see a hello-world response.

The parts of the generated project we care about:

todo-api/
├── src/
│   ├── controllers/   # HTTP layer
│   ├── services/      # business logic
│   ├── config/        # app configuration (OpenAPI lives here)
│   ├── app.ts         # app setup
│   └── serve.ts       # entry point
└── package.json
Enter fullscreen mode Exit fullscreen mode

We'll add four files: a model, the DTOs, a service and a controller.

2. The model

A todo is a plain TypeScript type. Megh doesn't need a base class or
decorators here. For advanced model see MeghORM

// src/models/todo.ts
export type Priority = 'low' | 'medium' | 'high';

export interface Todo {
  id: number;
  title: string;
  completed: boolean;
  priority: Priority;
  createdAt: string;
}
Enter fullscreen mode Exit fullscreen mode

3. DTOs: validation you declare once

A DTO (data transfer object) describes what a request may contain. Megh
validates the request against it before your handler runs.

// src/dtos/todo.dto.ts
import {
  IsBoolean,
  IsIn,
  IsInt,
  IsOptional,
  IsString,
  Max,
  MaxLength,
  Min,
  MinLength,
  PartialType,
  Transform,
  Type,
} from '@meghjs/core';
import type { Priority } from '../models/todo';

const PRIORITIES: Priority[] = ['low', 'medium', 'high'];

export class CreateTodoDto {
  @IsString()
  @MinLength(1)
  @MaxLength(200)
  title: string;

  @IsOptional()
  @IsBoolean()
  completed?: boolean;

  @IsOptional()
  @IsIn(PRIORITIES)
  priority?: Priority;
}

// Same rules, every field optional.
export class UpdateTodoDto extends PartialType(CreateTodoDto) {}

// GET /todos?page=1&perPage=10&completed=false&search=milk
export class ListTodosQuery {
  @IsOptional()
  @Type(() => Number)
  @IsInt()
  @Min(1)
  page?: number;

  @IsOptional()
  @Type(() => Number)
  @IsInt()
  @Min(1)
  @Max(100)
  perPage?: number;

  // Query strings are text, so turn "true"/"false" into a boolean.
  @IsOptional()
  @Transform(({ value }) => (value === 'true' ? true : value === 'false' ? false : value))
  @IsBoolean()
  completed?: boolean;

  @IsOptional()
  @IsString()
  search?: string;
}
Enter fullscreen mode Exit fullscreen mode

Things to notice:

  • The decorators come from @meghjs/core, not class-validator. They have the same names and messages, so they'll look familiar if you've used NestJS. They're also much faster; see below.
  • PartialType derives the update DTO from the create DTO, so the rules live in one place.
  • The same DTOs drive the API docs. You won't write any OpenAPI schema by hand.

Faster than class-validator

Megh's decorators look like class-validator's, but Megh compiles each DTO into
a single function the first time it's used, instead of interpreting the rules
on every request. On the CreateTodoDto above, with both libraries
reporting the same errors:

Time per validation (µs, lower is better)

Valid body
  class-validator  ███████████████          7.25
  Megh             █                        0.57   ~13× faster

Invalid body (3 errors)
  class-validator  ██████████████████████  11.06
  Megh             ██████                   2.96   ~4× faster
Enter fullscreen mode Exit fullscreen mode

Existing class-validator DTOs still work in Megh, and switching one is just an
import change. For how the compiler works and how to run the benchmark
yourself, see Why Megh has its own validator.

4. The service, backed by Collection

Collection is an in-memory list with a repository-like API: find,
findOne, add, updateBy, deleteBy, deleteAll, paginate, plus
aggregates such as max, sum and avg. It ships with @meghjs/core, so
there's nothing extra to install.

// src/services/todo.service.ts
import { AppService, Collection, HttpExceptions } from '@meghjs/core';
import type { CreateTodoDto, ListTodosQuery, UpdateTodoDto } from '../dtos/todo.dto';
import type { Todo } from '../models/todo';

@AppService
export class TodoService {
  private readonly todos = Collection.from<Todo>([]);
  private nextId = 1;

  list(query: ListTodosQuery) {
    const search = query.search?.toLowerCase();
    const matches = this.todos.find(
      (t) =>
        (query.completed === undefined || t.completed === query.completed) &&
        (!search || t.title.toLowerCase().includes(search)),
    );
    return Collection.from(matches).paginate(query);
  }

  findById(id: number): Todo {
    const todo = this.todos.findOne({ where: { id } });
    if (!todo) throw HttpExceptions.notFound(`Todo ${id} not found`);
    return todo;
  }

  create(input: CreateTodoDto): Todo {
    return this.todos.add({
      id: this.nextId++,
      title: input.title,
      completed: input.completed ?? false,
      priority: input.priority ?? 'medium',
      createdAt: new Date().toISOString(),
    });
  }

  update(id: number, changes: UpdateTodoDto): Todo {
    this.findById(id); // 404 if it doesn't exist
    // Fields the client didn't send arrive as undefined; drop them so they
    // don't overwrite stored values.
    const sent = Object.fromEntries(
      Object.entries(changes).filter(([, value]) => value !== undefined),
    ) as Partial<Todo>;
    this.todos.updateBy({ id }, sent);
    return this.findById(id);
  }

  remove(id: number): void {
    this.findById(id);
    this.todos.deleteBy({ id });
  }

  clearCompleted() {
    const removed = this.todos.find((t) => t.completed).length;
    this.todos.deleteAll((t) => t.completed);
    return { removed };
  }

  stats() {
    const total = this.todos.find().length;
    const completed = this.todos.find((t) => t.completed).length;
    const urgent = this.todos.find((t) => t.priority === 'high' && !t.completed).length;
    return { total, completed, open: total - completed, urgent };
  }
}
Enter fullscreen mode Exit fullscreen mode

A few details:

  • @AppService registers the class with Megh's DI container. You don't add it to any providers list.
  • findOne takes a predicate or a where object. The where form also supports $in, $or, $and and $not, so it reads much like a database query.
  • paginate() returns { data, meta }. Every Megh paginator uses this shape, including the ORM and query builder, so your clients won't need to change when you add a database.
  • HttpExceptions.notFound() turns into a 404 with Megh's standard error body. You don't need a try/catch in the controller.
  • updateBy replaces the stored object ({ ...old, ...changes }), so read the todo again after updating instead of holding on to the old reference.
  • The sent filter in update is there because, with the ES2022 target that new projects use, TypeScript creates a property for every field declared on the DTO. A PATCH that only sends completed arrives with title: undefined, and without the filter that undefined would overwrite the stored title.

5. The controller

// src/controllers/todo.controller.ts
import {
  ApiController,
  Body,
  Delete,
  Get,
  HttpCode,
  Param,
  Patch,
  Post,
  Query,
} from '@meghjs/core';
import { CreateTodoDto, ListTodosQuery, UpdateTodoDto } from '../dtos/todo.dto';
import { TodoService } from '../services/todo.service';

@ApiController('/todos')
export class TodoController {
  constructor(private readonly todos: TodoService) {}

  @Get()
  list(@Query() query: ListTodosQuery) {
    return this.todos.list(query);
  }

  @Get('/stats')
  stats() {
    return this.todos.stats();
  }

  @Get('/:id')
  findOne(@Param('id') id: number) {
    return this.todos.findById(id);
  }

  @Post()
  @HttpCode(201)
  create(@Body() body: CreateTodoDto) {
    return this.todos.create(body);
  }

  @Patch('/:id')
  update(@Param('id') id: number, @Body() body: UpdateTodoDto) {
    return this.todos.update(id, body);
  }

  @Delete('/completed')
  clearCompleted() {
    return this.todos.clearCompleted();
  }

  @Delete('/:id')
  @HttpCode(204)
  remove(@Param('id') id: number) {
    this.todos.remove(id);
  }
}
Enter fullscreen mode Exit fullscreen mode

The controller only handles HTTP:

  • TodoService is injected through the constructor. Megh resolves it from the parameter type.
  • @Param('id') id: number converts the value for you. /todos/2 gives you the number 2, and /todos/abc is rejected with a 400 before your code runs.
  • Return values become JSON. @HttpCode sets the success status.
  • Route order matters. /stats and /completed are declared before /:id, so they aren't matched as ids.

6. Register the controller

Open the generated src/app.ts and add TodoController to
useControllers:

// src/app.ts
import { Megh } from '@meghjs/core';
import { HomeController } from './controllers/home.controller';
import { TodoController } from './controllers/todo.controller';
import { OpenApiConfig } from './config/openapi.config';

const app = Megh.createApplication();

if (app.isDevelopment()) {
  app.useOpenApi(OpenApiConfig);
}

app.useControllers([HomeController, TodoController]);

export default app;
Enter fullscreen mode Exit fullscreen mode

That's all the wiring. There's no module, no providers array and no
imports.

7. Try it

With npm run start:dev still running (it hot-reloads), create a few todos:

curl -X POST localhost:4000/todos -H 'content-type: application/json' \
  -d '{"title":"Buy milk","priority":"high"}'
curl -X POST localhost:4000/todos -H 'content-type: application/json' \
  -d '{"title":"Walk the dog"}'
curl -X POST localhost:4000/todos -H 'content-type: application/json' \
  -d '{"title":"Buy bread","completed":true}'
Enter fullscreen mode Exit fullscreen mode
{"id":1,"title":"Buy milk","completed":false,"priority":"high","createdAt":"2026-11-19T22:10:08.284Z"}
Enter fullscreen mode Exit fullscreen mode

Search and paginate:

curl 'localhost:4000/todos?search=buy&perPage=1'
Enter fullscreen mode Exit fullscreen mode
{
  "data": [{ "id": 1, "title": "Buy milk", "completed": false, "priority": "high", "createdAt": "..." }],
  "meta": { "total": 2, "page": 1, "perPage": 1, "lastPage": 2, "next": 2, "prev": null }
}
Enter fullscreen mode Exit fullscreen mode

Update one field. The other fields keep their values:

curl -X PATCH localhost:4000/todos/2 -H 'content-type: application/json' \
  -d '{"completed":true}'
Enter fullscreen mode Exit fullscreen mode

Now send something invalid: an empty title, an unknown priority, and a field
that isn't on the DTO:

curl -X POST localhost:4000/todos -H 'content-type: application/json' \
  -d '{"title":"","priority":"urgent","isAdmin":true}'
Enter fullscreen mode Exit fullscreen mode
{
  "code": 400,
  "status": "Error",
  "message": "property isAdmin should not exist; title must be longer than or equal to 1 characters; priority must be one of the following values: low, medium, high",
  "errors": [
    { "path": "isAdmin", "constraints": { "whitelistValidation": "property isAdmin should not exist" } },
    { "path": "title", "constraints": { "minLength": "title must be longer than or equal to 1 characters" } },
    { "path": "priority", "constraints": { "isIn": "priority must be one of the following values: low, medium, high" } }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Megh reports every problem in one response, and rejects unknown properties
by default
. A client can't sneak isAdmin: true into your data (the "mass
assignment" bug), and you didn't write any code to prevent it.

A missing todo returns a 404:

curl -i localhost:4000/todos/99
# HTTP/1.1 404 Not Found
# {"code":404,"status":"Error","message":"Todo 99 not found", ...}
Enter fullscreen mode Exit fullscreen mode

Finally, open http://localhost:4000/docs. Every route is documented there,
with request and query schemas built from your DTOs, and you can call each
endpoint from the browser.

The finished API

Method Path What it does
GET /todos List with page, perPage (max 100), completed, search
GET /todos/stats Totals
GET /todos/:id One todo, or 404
POST /todos Create (201)
PATCH /todos/:id Partial update
DELETE /todos/completed Delete every completed todo
DELETE /todos/:id Delete one (204)

That's about 150 lines of code, and nearly all of it is your own logic.

8. When you need a real database

Collection resets when the server restarts. That's what you want for a demo
or a test, but not in production. When you're ready to persist data, Megh
includes MeghORM, with models, a typed query builder, migrations and
seeders, on Postgres, MySQL, SQLite or SQL Server:

const open = await Todo.where('completed', false)
  .orderBy('createdAt', 'desc')
  .paginate({ page: 1, perPage: 10 });
Enter fullscreen mode Exit fullscreen mode

Because paginate() returns the same { data, meta } shape there too, your
controller and your API clients don't change. You only rewrite the service.

Why choose Megh?

Here's what the walkthrough showed, and why it matters for a real project.

1. Structure without ceremony

You saw decorators, controllers and constructor injection, the parts of
NestJS people like. There were no modules and no providers, imports or
exports arrays
. A service is a class with @AppService, and a controller
is a class you register. As a project grows, that's less boilerplate in
every feature you add.

2. Everything a business API needs, in one install

Validation, OpenAPI docs, DI, a standard error format and pagination were all
already there. The same package also covers what comes next:

Area Built in
Data MeghORM (models, migrations, seeders, factories); TypeORM and Knex also supported
Auth Pluggable authentication with deny-by-default @Authorized routes, roles and permissions
Background work Typed events, BullMQ queues and workers, cron and interval scheduling
Infrastructure Caching (memory or Redis), pino logging, typed config, file uploads, mail, Socket.IO
Tooling A CLI with serve (SWC + hot reload), build, make:* generators and routes

Integrations such as database drivers, CORS and Swagger are optional peer
dependencies. If you use a feature without its package installed, Megh tells
you exactly what to install.

3. Safe defaults

Unknown fields are rejected, input is validated before your code runs,
protected routes are deny-by-default, and every error has the same shape. A
new teammate gets these right without having to know they exist.

4. Fastify speed

Megh runs on Fastify. In our benchmark, Megh kept about 90% of raw
Fastify's throughput on simple routes
, ran a little faster than NestJS on
the same Fastify adapter, and handled about 1.5× the requests of Express.
The benchmark is in the repo, so you can run it on your own hardware.

Validation is where most frameworks lose that speed. That's why Megh compiles
DTOs instead of interpreting them (see "Faster than class-validator" in
step 3).

5. Generators that write code you own

If you've used php artisan or rails generate, this will feel familiar:

npx megh make:resource Ticket --fields "title,body,status:in(open|closed)"
npx megh sc:auth --strategy jwt --roles multiple --permissions
npx megh sc:domain ecommerce --resource
Enter fullscreen mode Exit fullscreen mode

The output is plain TypeScript in your project, so you can read and edit it.
There are scaffolds for 11 business domains (e-commerce, POS, medical, CRM,
HR, logistics and more), which cover a lot of the repetitive first-month
work on business apps.

6. A smooth path from prototype to production

You can start with Collection and no database, as in this post. Later you
switch to MeghORM and keep the same { data, meta } pagination shape, so
your controllers and clients don't change.

When Megh is not the right choice

  • Edge or serverless-first apps. Megh targets long-running Node 22+ servers. For Cloudflare Workers or Bun, look at Hono or Elysia.
  • You need a large plugin ecosystem today. NestJS has years of community modules, GraphQL and microservice transports. Megh is young.
  • Critical production systems before 1.0. Breaking changes are still possible in 0.x releases.

Try it

npx @meghjs/cli new my-api
Enter fullscreen mode Exit fullscreen mode

Megh is still young and feedback from early users shapes what comes next. If something feels
heavier than it should, open an issue. And if you build something with it,
we'd love to see it.

Top comments (0)