C
CanxJS
v1.6.2
  • Learn
  • Blog
  • Showcase
C
CanxJS

Ultra-fast async MVC backend framework for Bun. Build production-ready APIs with elegance and speed.

Resources

  • Documentation
  • Learn
  • Blog
  • Showcase

Documentation

  • Introduction
  • Installation
  • Core Concepts
  • CLI Commands
  • API Reference

Legal

  • Privacy Policy
  • Terms of Service

© 2026 CanxJS. All rights reserved.

Built with ❤️ for Candra Kirana

  • Routing
  • Controllers
  • API Resources
  • Dependency Injection
  • Service Providers
  • Middleware
  • Request & Response
  • Authentication
  • Validation
  • Session
  • I18n
  • Utilities
Utilities

API Resources

Transform your models and data objects into standardized JSON responses. Perfect for building consistent APIs.

Transformation

Transform your models into JSON responses.

Collections

Automatically handle arrays of resources.

Relationships

Embed nested resources easily.

Creating Resources

Extend `JsonResource` and define the `toArray` method to control the output format.

src/resources/UserResource.ts
1import { JsonResource } from "canxjs";
2
3export class UserResource extends JsonResource {
4 toArray(request) {
5 return {
6 id: this.id,
7 name: this.name,
8 email: this.email,
9 created_at: this.created_at,
10 // Computed or conditional attributes
11 is_admin: this.role === 'admin'
12 };
13 }
14}

Usage

Return resources directly from your controllers or route handlers. CanxJS handles the serialization.

src/controllers/UserController.ts
1import { UserResource } from "./resources/UserResource";
2
3app.get("/user/:id", async (req, res) => {
4 const user = await User.find(req.params.id);
5
6 // Return single resource
7 return new UserResource(user);
8});
9
10app.get("/users", async (req, res) => {
11 const users = await User.all();
12
13 // Return collection
14 return UserResource.collection(users);
15});

Relationships & Conditional Attributes

Include related resources or hide data based on conditions using helper methods.

src/resources/PostResource.ts
1// In PostResource.ts
2export class PostResource extends JsonResource {
3 toArray(request) {
4 return {
5 id: this.id,
6 title: this.title,
7 content: this.content,
8 // Nesting user resource
9 author: new UserResource(this.author),
10 // Conditional Relationship
11 comments: this.whenLoaded('comments', () => CommentResource.collection(this.comments)),
12 };
13 }
14}

Next Steps

Learn more about API versioning.