Views & Layouts
Put your React app in the Mountaineer project's views directory. It contains the frontend's package.json, tsconfig.json, and build configuration.
If you want the architectural rationale for this Python + React split, see Philosophy & Tradeoffs.
Name each controller's view page.tsx and export its React component as the default. Keep related components alongside it:
import React from "react";
const Home = () => {
return (
<div>
<h1>Home</h1>
<p>Welcome to the home page!</p>
</div>
);
}
export default Home;
Page components must be synchronous. Fetch their initial data in the Python controller's render() method.
For work that runs in the browser after hydration, use useEffect:
import React, { useEffect } from "react";
const Home = () => {
useEffect(() => {
console.log("The page has been hydrated with Javascript!");
}, []);
return (
<div>
<h1>Home</h1>
<p>Welcome to the home page!</p>
</div>
);
}
export default Home;
Controllers
A controller supplies one view with data and actions. Its render() method queries and prepares the data needed for the initial page. Sideeffect and passthrough actions handle later client requests.
from mountaineer import sideeffect, ControllerBase, RenderBase
from iceaxe import select, DBConnection
from iceaxe.mountaineer import DatabaseDependencies
from myapp.models import TodoItem
class HomeRender(RenderBase):
todos: list[TodoItem]
class HomeController(ControllerBase):
url = "/"
view_path = "/app/home/page.tsx"
async def render(
self,
session: DBConnection = Depends(DatabaseDependencies.get_db_connection)
) -> HomeRender:
todos = (await session.execute(select(TodoItem))).all()
return HomeRender(
todos=todos
)
Path Parameters
Declare path parameters in both the controller's URL and its render() signature. For URLs such as:
/details/a687566b-db3e-42e3-9053-4f679abe8277
/details/4a4c26bc-554a-40dd-aecd-916abd3bc475
Use an item_id parameter:
class DetailController(ControllerBase):
url = "/details/{item_id}"
view_path = "/app/details/page.tsx"
async def render(
self,
item_id: UUID,
) -> HomeRender:
...
Query Parameters
Query parameters support simple types (str, float, UUID, and others) and lists of those types. For example, these URLs provide a name and an optional list of costs:
/search?name=Apple&cost=30&cost=50
/search?name=Banana
Declare cost with Query() so repeated query values become a list:
from typing import Annotated
from fastapi import Query
class SearchController(ControllerBase):
url = "/search"
view_path = "/app/search/page.tsx"
async def render(
self,
name: str,
cost: Annotated[list[int] | None, Query()] = None,
) -> HomeRender:
...
Both path and query parameters are validated by FastAPI, so you can use the same validation techniques. For more details, see the FastAPI guide.
Layouts
A layout.tsx wraps pages in its directory and subdirectories, following the Next.js convention. Use it for shared elements such as headers and footers.
The nested page arrives through the children prop. Include it in the layout's output:
import React from "react";
const Layout = ({ children } : { children: React.ReactNode }) => {
return (
<div>
<header>
<h1>My Website</h1>
</header>
<main>
{children}
</main>
<footer>
<p>© My Website</p>
</footer>
</div>
);
}
export default Layout;
Nested layouts wrap a page from the outside in:
views/
└── app/
├── dashboard/
│ ├── layout.tsx
│ ├── home/
│ │ └── page.tsx
│ └── settings/
│ └── page.tsx
└── layout.tsx
Here, app/layout.tsx wraps the dashboard layout, which wraps dashboard/home/page.tsx. Mountaineer discovers these files during the build. Layouts used only for presentation need no Python controller.
For more advanced layout organization, including isolating layouts to specific sections of your application using the (root) folder pattern, see the Layout Organization guide.
Add a layout controller when the layout needs server data or actions.
Layout Controllers
Layouts support most of the same controller logic that regular pages do. They can specify their own actions, both sideeffects and passthroughs, which will re-render the layout as required.
from mountaineer import LayoutControllerBase, RenderBase
from mountaineer.actions import sideeffect
class RootLayoutRender(RenderBase):
layout_value: int
class RootLayoutController(LayoutControllerBase):
view_path = "/app/layout.tsx"
def __init__(self):
super().__init__()
self.layout_value = 0
def render(self) -> RootLayoutRender:
return RootLayoutRender(
layout_value=self.layout_value,
)
@sideeffect
async def increment_layout_value(self) -> None:
self.layout_value += 1
The layout's generated hook exposes its state, actions, and link generator:
import React, { ReactNode } from "react";
import { useServer } from "./_server";
const Layout = ({ children }: { children: ReactNode }) => {
const serverState = useServer();
return (
<div className="p-6">
<h1>Layout State: {serverState.layout_value}</h1>
<div>{children}</div>
<div>
<button
className="rounded-md bg-indigo-500 p-2 text-white"
onClick={async () => {
await serverState.increment_layout_value();
}}
>
Increase Ticker
</button>
</div>
</div>
);
};
export default Layout;
Register the layout controller with AppController, as you would a page controller:
app_controller = AppController(...)
app_controller.register(RootLayoutController())
Mountaineer merges the layout and page render() signatures. Parameters with the same name and type resolve to the same value; matching names with conflicting types raise a TypeError.
Layout and page dependencies also share a scope. If both use the same database dependency, they receive the same underlying transaction. Treat changes made through either controller as part of that shared transaction.
Typescript Configuration
Configure TypeScript in tsconfig.json. Start with the following settings, or consult TypeScript's full list of options:
{
"compilerOptions": {
"target": "es2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
},
"exclude": ["node_modules"]
}
To import @/components/myfile instead of ../../components/myfile, add a paths alias:
{
"compilerOptions": {
"target": "es2017",
...
"paths": {
"@/*": ["./*"]
}
},
"exclude": ["node_modules"]
}
Client-Only Modules
If a component depends on browser-only APIs or third-party libraries that cannot execute during SSR, add the exact directive below at the top of the file:
'use client';
During bundling, Mountaineer scans the import graph for 'use client'. The server bundle does not execute a marked module. During SSR, it renders the component's children or null; after hydration, the browser renders the client component. The surrounding tree still renders on the server.
The recommended pattern is to wrap browser-only libraries in a small local component marked with 'use client', then import that wrapper from your page or layout. Modules marked 'use client' should export React components rather than shared utilities.