Chapter 10: Route Organization in TypeScript

Group and structure complex route tables. In this chapter, you will learn route organization in depth with TypeScript code examples, explanations, and best practices.

Overview

This chapter covers route organization for Kungfu.js developers using TypeScript. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.

Why This Matters

Understanding route organization is essential because it is a core part of building web applications. Every real-world app needs to handle group and structure complex route tables. Skipping this chapter would leave a gap in your knowledge that would cause problems later.

Code Example

This chapter covers route organization in TypeScript. Below is a practical code example you can copy, run, and modify to solidify your understanding.

// Route Organization in TypeScript
// This example demonstrates route organization with a runnable server.
const { Kungfu } = require('@kungfu/core');

const app = new Kungfu();

app.get('/', (req) => {
    return { status: 200, body: 'Kungfu.js is running. Try /hello or /api/health' };
});

app.get('/hello', (req) => {
    return {
        status: 200,
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ message: 'world' })
    };
});

app.get('/api/health', (req) => {
    return {
        status: 200,
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ status: 'ok', uptime_seconds: 0 })
    };
});

console.log('Server running on http://localhost:3000');
app.listen(3000);

Why This Matters

Every feature in Kungfu.js is designed to be predictable: the same input always produces the same output, the same route always hits the same handler, and the same middleware always runs in the same order. This predictability is what makes production apps maintainable. When something breaks at 3 AM, you need to reason about the request path quickly — and the onion-model middleware plus the trie router give you that mental model for free.

Common Mistakes

  • Not reading the documentation: Always check the API reference when something does not work as expected.
  • Skipping security: Never disable the default middleware unless you have a very good reason. Security is not optional.
  • Not testing: Write tests for your handlers. Kungfu.js makes this easy with the built-in test utilities.

Summary

In this chapter, you learned about route organization in TypeScript. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.

What is Next?

In chapter 11, we will cover Middleware Basics: What middleware is and why it matters.