Controllers
Controllers are the heart of your API in Vercube. They organize your endpoints into logical groups, handle incoming requests, and return responses. Think of controllers as the "traffic directors" of your application - they receive requests, process them, and send back responses.
What is a Controller?
A controller is a class that groups related HTTP endpoints together. Instead of scattering your API endpoints across different files, you organize them by resource or feature. For example, all user-related operations go in UserController, all product operations go in ProductController, and so on.
The Problem Without Controllers
// ❌ Scattered endpoints - hard to maintain
app.get('/users', getUsersHandler);
app.post('/users', createUserHandler);
app.get('/users/:id', getUserHandler);
app.delete('/users/:id', deleteUserHandler);
app.put('/users/:id', updateUserHandler);
// ... hundreds of lines later
app.get('/products', getProductsHandler);
// ... where does one resource end and another begin?
The Solution With Controllers
// ✅ Organized, clean, maintainable
@Controller('/users')
export class UserController {
@Get('/')
getUsers() { }
@Post('/')
createUser() { }
@Get('/:id')
getUser() { }
@Put('/:id')
updateUser() { }
@Delete('/:id')
deleteUser() { }
}
How Controllers Work
Here's the complete flow from request to response:
Behind the Scenes
When you create a controller with decorators, Vercube automatically:
- Registers routes - Combines controller path with method paths
- Creates handlers - Wraps your methods in proper HTTP handlers
- Resolves parameters - Extracts data from URL, body, headers, etc.
- Handles responses - Serializes your return value to JSON
- Manages errors - Catches and formats errors appropriately
Creating Your First Controller
Create the controller class
import { Controller } from '@vercube/core';
@Controller('/users')
export class UserController {
// Your endpoints will go here
}
The @Controller('/users') decorator does two things:
- Marks this class as a controller
- Sets
/usersas the base path for all routes
Add route handlers
import { Controller, Get } from '@vercube/core';
@Controller('/users')
export class UserController {
@Get('/')
getAllUsers() {
return [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
}
}
This creates: GET /users/
Vercube automatically:
- Converts the return value to JSON
- Sets
Content-Type: application/json - Sends status code 200
Register the controller
import { type App } from '@vercube/core';
import { UserController } from './controllers/UserController';
export function setup(app: App): void {
app.useController(UserController);
}
That's it! Your API is ready to handle requests.
HTTP Methods
Vercube provides decorators for all standard HTTP methods:
import { Controller, Get, Post, Put, Patch, Delete } from '@vercube/core';
@Controller('/users')
export class UserController {
@Get('/')
list() {
// GET /users - List all users
}
@Get('/:id')
get() {
// GET /users/:id - Get specific user
}
@Post('/')
create() {
// POST /users - Create new user
}
@Put('/:id')
update() {
// PUT /users/:id - Replace user
}
@Patch('/:id')
modify() {
// PATCH /users/:id - Partially update user
}
@Delete('/:id')
remove() {
// DELETE /users/:id - Delete user
}
}
Path Parameters
Extract dynamic values from URLs using the @Param decorator:
import { Controller, Get, Param } from '@vercube/core';
@Controller('/users')
export class UserController {
@Get('/:id')
getUserById(@Param('id') id: string) {
return { id, name: 'User ' + id };
}
@Get('/:userId/posts/:postId')
getUserPost(
@Param('userId') userId: string,
@Param('postId') postId: string
) {
return { userId, postId, title: 'Post title' };
}
}
Pass an options object to validate and coerce a path parameter - see Validation:
@Get('/:id')
getUserById(
@Param({ name: 'id', validationSchema: z.coerce.number().int() }) id: number,
) {}
A @Param name that is not a parameter of the route path, such as @Param('nmae') on /:id, fails when the route is registered rather than resolving to undefined on every request.
Request Body
Access request body data with the @Body decorator:
import { Controller, Post, Body } from '@vercube/core';
interface CreateUserDto {
name: string;
email: string;
age: number;
}
@Controller('/users')
export class UserController {
@Post('/')
createUser(@Body() userData: CreateUserDto) {
// userData is automatically parsed from JSON
console.log(userData.name); // "Alice"
console.log(userData.email); // "[email protected]"
return { id: 1, ...userData };
}
}
# Client sends:
curl -X POST http://localhost:3000/users \
-H "Content-Type: application/json" \
-d '{"name":"Alice","email":"[email protected]","age":25}'
@Body() decorator automatically parses JSON request bodies. No manual JSON.parse() needed!@Body() picks the parser from the Content-Type header:
application/json, any+jsontype, or no content type: parsed JSONapplication/x-www-form-urlencoded: an object of fields, a repeated key becomes an array (a=1&a=2gives{ a: ['1', '2'] })text/*: the raw string
Any other content type is rejected with 415 Unsupported Media Type. A body larger than server.bodyLimit (1 MiB by default) is rejected with 413 Payload Too Large before it is read.
The body is read after the before middlewares run, so an auth middleware rejects a request with a 401 before its body is parsed. Validation middlewares run last, once the arguments are resolved.
import { z } from 'zod';
const CreateUserSchema = z.object({
name: z.string(),
email: z.string().email(),
age: z.number().min(18)
});
type CreateUserDto = z.infer<typeof CreateUserSchema>;
@Post('/')
createUser(@Body({ validationSchema: CreateUserSchema }) userData: CreateUserDto) {
// userData is validated and type-safe!
// If validation fails, automatic 400 Bad Request response
}
Query Parameters
Extract URL query parameters using @QueryParam or @QueryParams:
import { Controller, Get, QueryParam, QueryParams } from '@vercube/core';
@Controller('/users')
export class UserController {
@Get('/search')
searchUsers(
@QueryParam('name') name: string,
@QueryParam('minAge') minAge: string, // Always string!
@QueryParams() allParams: Record<string, string> // Always strings!
) {
// Convert to number if needed
const minAgeNumber = parseInt(minAge, 10);
return {
searching: { name, minAge: minAgeNumber },
allQueryParams: allParams
};
}
}
# Request:
GET /users/search?name=Alice&minAge=21&city=NYC
# Your method receives:
# name = "Alice" (string)
# minAge = "21" (string, not number!)
# allParams = { name: "Alice", minAge: "21", city: "NYC" } (all strings)
?age=25), you'll receive it as the string "25". You must manually convert to numbers, booleans, or other types:@Get('/search')
searchUsers(
@QueryParam('age') age: string,
@QueryParam('active') active: string
) {
const ageNumber = parseInt(age, 10); // "25" → 25
const isActive = active === 'true'; // "true" → true
}
import { z } from 'zod';
const SearchUsersSchema = z.object({
age: z.coerce.number().min(0), // Automatically converts string to number!
active: z.coerce.boolean(), // Automatically converts string to boolean!
name: z.string().optional()
});
type SearchUsersDto = z.infer<typeof SearchUsersSchema>;
@Get('/search')
searchUsers(
@QueryParams({ validationSchema: SearchUsersSchema }) query: SearchUsersDto,
) {
// query.age is now a number: 25
// query.active is now a boolean: true
// No manual conversion needed!
}
A parameter that appears more than once (?tag=a&tag=b) resolves to its first value, for @QueryParam and @QueryParams alike. Ask for every value with array: true on @QueryParam, or by listing the keys in arrays on @QueryParams:
@Get('/posts')
list(
// ['a', 'b'], [] when missing
@QueryParam({ name: 'tag', array: true }) tags: string[],
@QueryParams({
arrays: ['tag'],
validationSchema: z.object({ tag: z.array(z.string()) }),
})
query: { tag: string[] },
) {}
Headers
Access request headers with @Header or @Headers:
import { Controller, Get, Header, Headers } from '@vercube/core';
@Controller('/users')
export class UserController {
@Get('/')
getUsers(
@Header('Authorization') token: string,
@Header('X-API-Key') apiKey: string,
@Headers() allHeaders: Record<string, string>
) {
console.log('Token:', token);
console.log('API Key:', apiKey);
return { authenticated: !!token };
}
}
A missing header resolves to undefined, so a parameter default applies: @Header('X-Tenant') tenant = 'default'. @Headers() is a plain object with lowercase names, allHeaders['x-api-key'].
File Uploads
@MultipartFormData() parses a multipart/form-data body. Text fields are strings, uploads are Files and a repeated field becomes an array:
import { Controller, MultipartFormData, Post } from '@vercube/core';
@Controller('/files')
export class FileController {
@Post('/')
async upload(@MultipartFormData() form: { title: string; file: File }) {
return { title: form.title, size: (await form.file.arrayBuffer()).byteLength };
}
}
Another content type is rejected with 415, and a body over server.bodyLimit with 413.
Returning Responses
You have multiple ways to return responses from your controllers:
Simple Values (Auto JSON)
@Get('/')
getUser() {
// Automatically converted to JSON with status 200
return { id: 1, name: 'Alice' };
}
Custom Status Code
import { Status } from '@vercube/core';
@Post('/')
@Status(201)
createUser(@Body() data: any) {
// Returns status 201 Created
return { id: 1, ...data };
}
Custom Headers
import { SetHeader } from '@vercube/core';
@Get('/')
@SetHeader('X-Custom-Header', 'value')
@SetHeader('X-Rate-Limit', '1000')
getUsers() {
return [{ id: 1, name: 'Alice' }];
}
Redirects
import { Redirect } from '@vercube/core';
@Get('/old-endpoint')
@Redirect('/new-endpoint', 301)
oldEndpoint() {
// Automatically redirects to /new-endpoint
}
Manual Response Control
import { Response } from '@vercube/core';
@Get('/')
getUsers(@Response() res: Response) {
res.headers.set('X-Custom', 'value');
return new Response(
JSON.stringify({ data: [] }),
{
status: 200,
headers: { 'Content-Type': 'application/json' }
}
);
}
A returned Response keeps its status, body and headers, so @Status() does not change it, and additionally receives the headers that middlewares, @SetHeader() and @Response() set on the intermediate response - so CORS headers from a global middleware reach streamed and file responses too:
- A header the handler set itself always wins.
- Only headers that were actually set are copied - the default
Content-Type: application/jsonis not, so a file or stream returned without a type keeps having none. Headers describing the body (Content-Type,Content-Encoding, ...) set by a middleware are copied too, so only set them when they match the body the handler returns. Set-Cookieheaders from both sides are kept; when both set a cookie with the same name, the handler's one wins.Varyvalues from both sides are combined, so a CORSVary: Originsurvives a handler that varies onAccept-Encoding.- A response from
fetch()(a proxied response) loses itsContent-EncodingandContent-Length, asfetch()has already decoded the body. Locationfrom@Redirect()is only copied onto a redirect or a201.- To drop a header a middleware added, call
res.headers.delete(name)on the@Response()argument.
The same headers reach error responses and responses a middleware ends the request with, e.g. a 401 from an auth middleware, so the browser sees the error instead of a CORS failure. Headers describing the body (Content-Type, Content-Encoding, Content-Length, Content-Range, Content-Disposition) are not copied there, as those responses carry a body of their own. Neither are the headers that only describe a successful response (Cache-Control, ETag, Last-Modified, Expires, Location), so a CDN does not cache a 404 for as long as the page it replaced. Only headers set before the error are copied.
Server-Sent Events
@Sse() registers a GET route that streams text/event-stream. Return an async generator (or any AsyncIterable / Iterable) - every yielded value becomes one event:
import { Controller, Sse, type SseMessage } from '@vercube/core';
@Controller('/events')
export class EventsController {
@Sse('/clock', { heartbeat: 15_000 })
async *clock(): AsyncGenerator<SseMessage> {
try {
let id = 0;
while (true) {
yield { event: 'time', id: id++, data: { now: Date.now() } };
await new Promise((resolve) => setTimeout(resolve, 1000));
}
} finally {
// Runs when the client disconnects
}
}
}
datais sent as-is when it is a string and JSON-serialized otherwise; primitives can be yielded directly.event,idandretrymap to the matching SSE fields.- A yielded object may only contain
data,event,idandretry- anything else (or an array) throws, soyield userfails loudly instead of silently dropping fields. Useyield { data: user }. heartbeatsends a keep-alive comment every N ms so proxies do not close idle connections.- Returning a
Responsefrom a regular (non-generator) handler skips streaming and sends it unchanged. - The first event is pulled before the response is sent, so an error thrown before the first
yield(e.g.throw new UnauthorizedError()) becomes a regular error response, andEventSourcestops reconnecting. Headers are sent together with the first event - yield one early if the first real event may take a while. - An error thrown after the first event cannot change the status anymore: the stream is closed and the error is logged. The browser then reconnects; set
idon events to resume fromLast-Event-ID. - Returning from the generator closes the stream. Browsers reconnect automatically, so send
retryor close theEventSourceon the client for finite streams. - Use
createSseResponse(iterable)to build the same response manually. - Headers set by middlewares and
@SetHeader()(e.g. CORS) reach the stream and the error response of a failed start like any other returnedResponse- see above.
Cleaning up on disconnect
When the client disconnects, the generator is closed with return(). A generator can only be closed while it is paused at a yield, so if it is in the middle of an await the close waits until that await settles. For a timer that is at most one tick, but a generator awaiting external events (a queue, pub/sub, an event emitter) may wait forever - its finally never runs and the subscription leaks with every closed tab.
Pass the request's AbortSignal to whatever you await. It is aborted as soon as the client disconnects, which rejects the pending await and lets finally run right away:
import { on } from 'node:events';
import { Controller, Request, Sse, type SseMessage } from '@vercube/core';
@Controller('/events')
export class NotificationsController {
@Sse('/notifications')
async *notifications(@Request() req: Request): AsyncGenerator<SseMessage> {
try {
for await (const [message] of on(bus, 'notification', {
signal: req.signal,
})) {
yield { event: 'notification', data: message };
}
} finally {
// Runs immediately on disconnect
}
}
}
An AbortError thrown by the generator closes the stream quietly instead of being logged as a failure.
Working with Services
Controllers should be thin - they coordinate but don't contain business logic. Use dependency injection to access services:
import { Controller, Get, Inject } from '@vercube/core';
import { UserService } from '../services/UserService';
@Controller('/users')
export class UserController {
@Inject(UserService)
private userService!: UserService;
@Get('/')
async getAllUsers() {
// Business logic is in the service
return await this.userService.findAll();
}
@Get('/:id')
async getUserById(@Param('id') id: string) {
return await this.userService.findById(id);
}
@Post('/')
async createUser(@Body() data: CreateUserDto) {
return await this.userService.create(data);
}
}
Async Handlers
Controllers fully support async/await:
@Controller('/users')
export class UserController {
@Inject(UserService)
private userService!: UserService;
@Get('/:id')
async getUser(@Param('id') id: string) {
// Await is handled automatically
const user = await this.userService.findById(id);
if (!user) {
throw new NotFoundException('User not found');
}
return user;
}
@Post('/')
async createUser(@Body() data: CreateUserDto) {
// Multiple awaits work perfectly
await this.userService.validateEmail(data.email);
const user = await this.userService.create(data);
await this.userService.sendWelcomeEmail(user);
return user;
}
}
Error Handling
Throw an HttpError and Vercube answers with its status. @vercube/core exports one per common status: BadRequestError (400), UnauthorizedError (401), ForbiddenError (403), NotFoundError (404), MethodNotAllowedError (405), NotAcceptableError (406), PayloadTooLargeError (413), UnsupportedMediaTypeError (415) and InternalServerError (500).
import { Controller, Get, NotFoundError, Param } from '@vercube/core';
@Controller('/users')
export class UserController {
@Get('/:id')
async getUser(@Param('id') id: string) {
const user = await this.userService.findById(id);
if (!user) {
throw new NotFoundError('User not found');
}
return user;
}
}
The body is the error's own enumerable fields as JSON. message is only there when the error was created with one. The stack trace is not enumerable on a built-in error, so it is left out; a custom error that sets an enumerable stack field would send it:
{ "status": 404, "name": "NotFoundError", "message": "User not found" }
Any other error is logged and answered with its status when that is an integer from 400 to 599 (an error from another library carrying status: 429 gives a 429), and with a 500 otherwise.
Custom errors
Extend HttpError for a status Vercube has no class for. Give the class a static status, so @Throws() can read it without creating an error. Every field you set ends up in the body:
import { HttpError } from '@vercube/core';
export class ConflictError extends HttpError {
static readonly status = 409;
override name = 'ConflictError' as const;
constructor(public readonly existingId: string) {
super(409, 'Already exists');
}
}
// Response body:
// {
// "status": 409,
// "name": "ConflictError",
// "message": "Already exists",
// "existingId": "7"
// }
Declaring errors with @Throws
@Throws() lists the errors a route can answer with. The client types them and the OpenAPI document lists them as responses. It does not change what the route does: an error you did not declare still reaches the caller.
import {
Body,
Controller,
ForbiddenError,
Get,
NotFoundError,
Param,
Put,
Throws,
} from '@vercube/core';
import { ConflictError } from './Errors';
@Controller('/users')
@Throws(ForbiddenError) // every route in the controller
export class UserController {
@Get('/:id')
@Throws(NotFoundError)
async getUser(@Param('id') id: string): Promise<User> {
return this.users.find(id);
}
@Put('/:id/email')
@Throws(NotFoundError, ConflictError)
async changeEmail(
@Param('id') id: string,
@Body() body: { email: string },
): Promise<User> {
return this.users.changeEmail(id, body.email);
}
}
Stack it or pass several classes. A class without a static status takes the status first, @Throws(409, ConflictError); with neither, the decorator throws when the class is loaded.
Some errors need no declaration, because the framework throws them itself: a 400 on a route that reads @Body() or @MultipartFormData() or validates an argument, and a 401 and a 403 on a route guarded by @Auth(). A 500 is never added this way, since every route can answer with one; it is only listed when a route declares it, @Throws(InternalServerError).
Middleware Integration
Apply middleware to controllers or specific routes:
import { Controller, Get, Middleware } from '@vercube/core';
import { AuthMiddleware, LoggingMiddleware } from '../middlewares';
// Applies to ALL routes in this controller
@Controller('/users')
@Middleware(AuthMiddleware)
export class UserController {
@Get('/')
getUsers() {
// Protected by AuthMiddleware
}
// Additional middleware for this route only
@Get('/:id')
@Middleware(LoggingMiddleware)
getUserById() {
// Protected by AuthMiddleware + LoggingMiddleware
}
}
Organizing Controllers
By Resource (Recommended)
- controllers
- UserController.tsAll user operations
- ProductController.tsAll product operations
- OrderController.tsAll order operations
- AuthController.tsAll auth operations
By Feature
- features
- users
- UserController.ts
- UserService.ts
- User.model.ts
- products
- ProductController.ts
- ProductService.ts
- Product.model.ts
Best Practices
Keep controllers thin - Business logic belongs in services
// ❌ Bad - logic in controller
@Get('/:id')
async getUser(@Param('id') id: string) {
const user = await db.query('SELECT * FROM users WHERE id = ?', [id]);
delete user.password;
user.fullName = user.firstName + ' ' + user.lastName;
return user;
}
// ✅ Good - logic in service
@Get('/:id')
async getUser(@Param('id') id: string) {
return await this.userService.findById(id);
}
Use DTOs for request validation - Type your inputs
// ✅ Good
interface CreateUserDto {
name: string;
email: string;
age: number;
}
@Post('/')
createUser(@Body() data: CreateUserDto) {
// TypeScript ensures data structure
}
One responsibility per controller - Don't mix concerns
// ❌ Bad - mixed concerns
@Controller('/api')
export class ApiController {
@Get('/users') getUsers() { }
@Get('/products') getProducts() { }
@Get('/orders') getOrders() { }
}
// ✅ Good - focused controllers
@Controller('/users')
export class UserController { }
@Controller('/products')
export class ProductController { }
Use meaningful route names - Be clear about what each endpoint does
// ❌ Unclear
@Get('/data')
getData() { }
// ✅ Clear
@Get('/users')
getAllUsers() { }
Common Patterns
CRUD Controller Template
@Controller('/users')
export class UserController {
@Inject(UserService)
private userService!: UserService;
@Get('/')
async findAll() {
return await this.userService.findAll();
}
@Get('/:id')
async findOne(@Param('id') id: string) {
return await this.userService.findById(id);
}
@Post('/')
@Status(201)
async create(@Body() data: CreateUserDto) {
return await this.userService.create(data);
}
@Put('/:id')
async update(
@Param('id') id: string,
@Body() data: UpdateUserDto
) {
return await this.userService.update(id, data);
}
@Delete('/:id')
@Status(204)
async remove(@Param('id') id: string) {
await this.userService.remove(id);
}
}
Nested Resources
@Controller('/users/:userId/posts')
export class UserPostController {
@Get('/')
getUserPosts(@Param('userId') userId: string) {
// GET /users/123/posts
}
@Post('/')
createUserPost(
@Param('userId') userId: string,
@Body() data: CreatePostDto
) {
// POST /users/123/posts
}
}