Server rendering and server functions
A page project is a static site by default: the browser downloads a script that draws the page. With server rendering the server sends the finished HTML for the route that was asked for, the visitor sees it at once, and the script then takes over. This lesson shows the commands, how the browser takes the page over, and how a page calls a backend through a server func without a secret ever reaching the browser.
Static or rendered
The default build, salam page build, writes files that any web host can serve. Use it when the pages do not depend on the visitor. Server rendering is opt in and needs a program that runs: it answers each request with HTML built from the route, the guards and the state, so a page with a path like /users/7 has real content the moment it arrives. The project is the same one the web projects lesson describes: a main.salam, a pages/ folder for the routes and a components/ folder for the shared pub components. Nothing in the source changes.
Building the server
salam page build --ssr # into dist
salam page build --ssr=out . # into out, project in the current folder
PORT=8080 dist/server
The command builds the project twice. The first run is the normal web build and goes to dist/public: the script, the style sheet, your public/ folder and a copy of every page that needs no parameter and has no guard. The second run turns the same pages into a native program, dist/server, that holds the router, the guards, the layouts and the page code. Copy the two to a machine and run the program; it needs nothing else.
PORTis the port (8080 when it is not set,0picks a free one) andHOSTthe address (127.0.0.1when it is not set). The server printslistening on http://HOST:PORTand is meant to sit behind a reverse proxy such as Caddy or nginx, which handles HTTPS.- For each request the server finds the route, checks the guards, builds the layouts and the page into HTML and sends it. A page whose guard fails is skipped like an unknown path, and an unknown path gets status 404 with your
_404.salampage. - Files in
dist/publicare served first, withETagand cache headers. The prerendered copies of the pages are there for a CDN; the server still renders every page itself. - Text that comes from the address (a path parameter, the query) is escaped in the HTML and in the state block below, so a visitor cannot inject markup.
- A project with
mode = hashis refused, because a hash route never reaches the server, and so is a project that writes its ownmainfunction. - Addresses and secrets the server needs are read from the environment, never written into the build.
Developing with salam serve --render
salam serve --render
salam serve --render shop --port=3000 --host=0.0.0.0
This builds into a scratch folder, runs the server, and when you save a file builds again and swaps the server for the new one. The browser is not reloaded for you: refresh it. Without --render, salam serve page.salam is the static development server described in the serve lesson.
Hydration: the browser takes over
The HTML the server sends is already complete, so the first paint needs no script. When the script has loaded it starts the page itself, a step called hydration. It does not throw the server HTML away and draw again:
- Every part of the page that can change when a variable changes is wrapped in a pair of comments,
<!--salam:3-->and<!--/salam:3-->, in the server HTML and in the browser render alike. The script finds each part by its marker and fills it from the state, patching the nodes that are already there. No element is removed, so a focused field, a scroll position and a selection survive. - Event handlers are already in the server HTML, so a button works the moment the script runs.
- The server also writes
<script type="application/json" id="__salam">with the path, the matched pattern, the status and the answers of server functions the page called, so the browser does not ask for them again. Every<inside it is escaped, so no value can close the tag. - Variable values are not sent. The browser computes them again from the route and the initial values, so an initial value that depends on the time or on randomness would make the two renders differ.
- If a part of the browser render differs from the server HTML, the console prints
salam: hydration mismatch in region N, it is rendered again from the stateand that part is replaced; nothing else throws. A part the server could not draw, such as the rows of aneachthat keep their own state, is simply filled when the script loads, without a warning.
Server functions
A front project holds pages and no business logic: no database, no file store, no rules. The data lives in a backend, written in Salam or in anything else, that the front reaches over HTTP. A server func is the place where the front calls it. It is an ordinary function with a marker, and it runs only on the front server.
import env
import net.http
import encoding.json
struct Product:
pub id: int = 0
pub name: str = ""
pub price: int = 0
end
server func GetProduct(id: int): Product:
mut headers := http.NewHeaders()
headers.Insert("Authorization", "Bearer " + env.Get("SHOP_TOKEN"))
r := http.GetWith(env.Get("SHOP_API") + "/products/" + str.FromInt(id as i64), headers)
mut p := Product {}
try:
json.Unmarshal(r.body, p)
catch e:
println "bad product body:", e.message
end
ret p
end
pub component ProductPage(id: int):
p := GetProduct(id)
heading: content = p.name end
paragraph: content = "Price: " + p.price end
end
serveris a contextual word beforefunc, so it stays a legal name elsewhere. It sits last among the modifiers:pub server func. The Persian spelling isسرور تابع.- The function body never reaches the browser script or a native app. Only the signature does.
- Call it from a component body, a handler or another server function. The call looks the same everywhere. On the server it is a direct call; in the browser and in a native app it is a generated stub that asks the server (see below).
- A failure, such as a network error, a bad status or a body that does not decode, is a
throw: declare the functionthrowand handle it withtryandcatchat the caller. A throw nobody catches while a page is rendered gives a 500 page. Over the wire the browser receives only a generic message; the real text is printed on the server.
Which types can cross
Parameters and the result travel as JSON, so they must be wire types: int, float, bool, str, enums (as their member name), structs and Vectors of wire types, and an optional T?. Pointers, references and closures cannot cross: E285 names the parameter. HashMap and arrays are not wire types yet. The rest of the rules are checked at compile time:
| code | meaning |
|---|---|
| E285 | a parameter or result type cannot cross the network |
| E286 | code that runs in the browser uses something that only exists on the server, such as env |
| E287 | a server func that is a method or is not at the top level |
| E288 | two server functions have the same name (the wire name is the function name, so overloads are not allowed) |
| E289 | a static build can reach a server function, see below |
| W280 | the body looks like backend code |
Secrets stay on the server
Read addresses, tokens and keys with env.Get("NAME") inside a server function and set them in the environment of dist/server. env does not exist in the browser bundle: a function that is reachable from browser code and uses it is error E286, and it names the member. A helper that both sides share is fine until it touches a server only name. Methods of your own structs are not trimmed away, so a method that uses env is an error whenever its type is declared in the page program; put such code in a package the page does not import.
Keeping it a thin layer
A server function is a window, not a backend. If its body imports or calls db, fs, os, exec, process, the database drivers (sqlite, postgres, mysql, redis), a router or the server types of net.http, the compiler warns with W280, once per package per function: this looks like backend code; call your API from here instead. A project that really wants it writes this in a salam.cfg next to the entry file or in one of its three parent folders:
allow_backend = true
To call a backend from Salam use net.http. ssr.OutboundGet and ssr.OutboundPost from net.ssr do the same with safe defaults: a 10 second timeout, a response cap of 8 MB and at most 5 redirects. Inside a server function and while a page renders, ssr.Request() gives the current request, with its method, path, headers, cookies and client address. Forward a session cookie or a token to the backend with it.
In the browser and in a native app
The same source gives three outputs, and the call site never changes:
- Server (
--ssr): the function is unchanged, and the server registers it. The browser calls it withPOST /_salam/fn/Nameand a JSON body{"args":{"id":3}}; the answer is{"ok":true,"value":...}or{"ok":false,"error":"..."}. Only functions markedserver funcare registered. The request must be same origin and carry a session token that the rendered page embeds. - Web: the function keeps its signature and its body becomes a stub that posts to the server. A function declared
throwthrows the server's error text; any other returns the zero value. The stub waits for the answer, so a handler that calls one blocks until it arrives: keep server functions fast and do not call one per keystroke. A page rendered by the server already has its answers in the state block, so those calls do not go to the network again. - Native: there is no rendering and no server inside the app. The stub sends the same request to the front server, which the page names with the
serversetting, or theSALAM_SERVERenvironment variable when there is none. No secret is in the binary.
page:
server = "https://front.example.com"
ProductPage: id = 3 end
end
A plain static build (salam page build without --ssr) has no server to answer the calls, so a page that can reach a server function is error E289, unless the page sets server to a front server that does. The package that answers, with its tokens and the checks it makes, is net.ssr.
What is not there yet
- No streaming and no incremental regeneration: every request renders its page.
- Rows of an
eachwith their own state, and values that only the browser has (the window size, the pointer), are filled by the script after the first paint.
The package behind the endpoints, the tokens and the page hook is net.ssr. You do not call it for an ordinary project: the generated server does.