Chapter 40: .kng File Format in Kotlin

data() and template() functions for SSR. In this chapter, you will learn .kng file format in depth with Kotlin code examples, explanations, and best practices.

Overview

This chapter covers .kng file format for Kungfu.js developers using Kotlin. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.

Why This Matters

Understanding .kng file format is essential because it is a core part of building web applications. Every real-world app needs to handle data() and template() functions for ssr. Skipping this chapter would leave a gap in your knowledge that would cause problems later.

Code Example

Here is how frontend and SSR work in Kotlin:

// .kng file format (src/pages/index.kng)
export async function data(req) {
    return { user: { name: 'Bruce', role: 'master' } };
}

export function template({ user }) {
    return `<div class="flex p-4 text-xl">
        Hello, ` + user.name + `! You are a ` + user.role + `.
    </div>`;
}
---
<footer>Copyright 2026</footer>

How SSR Works

A .kng file exports two functions: data() and template(). When a request comes in, the server calls data() to fetch data, then calls template() with that data to generate HTML. The HTML is sent to the browser.

The browser also receives the data as a JSON object in window.__KUNGFU_DATA__. The hydration script picks this up and makes the page interactive without re-fetching the data.

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 .kng file format in Kotlin. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.

What is Next?

In chapter 41, we will cover Server-Side Rendering: Render pages on the server.