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