Chapter 42: Client-Side Hydration in Lua
Make SSR pages interactive. In this chapter, you will learn client-side hydration in depth with Lua code examples, explanations, and best practices.
Overview
This chapter covers client-side hydration for Kungfu.js developers using Lua. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.
Why This Matters
Understanding client-side hydration is essential because it is a core part of building web applications. Every real-world app needs to handle make ssr pages interactive. 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 Lua:
// .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 client-side hydration in Lua. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.
What is Next?
In chapter 43, we will cover File-Based Routing: Auto-register pages from file structure.