--- title: "Secure server function calls built directly into Elements" author: "@chris" author_url: https://elements.dev/u/@chris url: https://elements.dev/blog/secure-server-function-calls-built-directly-into-elements-ao26yr3u kind: post format: video video: https://elements.dev/blog/secure-server-function-calls-built-directly-into-elements-ao26yr3u/video.mp4 poster: https://elements.dev/blog/secure-server-function-calls-built-directly-into-elements-ao26yr3u/poster.jpg duration: "5:12" transcript_vtt: https://elements.dev/blog/secure-server-function-calls-built-directly-into-elements-ao26yr3u/transcript.vtt --- # Secure server function calls built directly into Elements by [@chris](https://elements.dev/u/@chris) ## Description In Elements, browser code calls a function on the server with a regular function call. The build type checks the call and adds async and await. The server calls only a function that has the @rpc build tag, and it reads the arguments as data. ## Notes ## A Function Call From the Browser to the Server Every developer and every coding agent knows how to call a function. We designed rpc in Elements so that browser code calls a function on the server with a regular function call, and the build type checks that call. Calling server code from the browser has to be engineered carefully: a request must not be able to choose which code the server runs. In December 2025, a bug in the way React handled remote procedure calls let an attacker run code on the server. The last three sections of this post describe that bug and the checks the Elements server makes on every request. ## The @rpc Build Tag The demo app has one page, `app/pages/home/template.ehtml`, a reactive HTML file. In a reactive HTML file, the TypeScript of a page is written above its `` tag. The page is a form with one message input. When you submit the form, the `onsubmit` function runs in the browser: ```ehtml app/pages/home/template.ehtml import "./style.css"; interface Form { id?: string; message: string; } function onsubmit(form: Form) { }
onsubmit(form)}>

Messages

``` We want to save the message in the database, and the database is on the server. We write a function named `saveForm` with one insert query, and we put the `@rpc` build tag on `saveForm`, in a comment on the line above the function. Rpc stands for remote procedure call: the browser sends a request over the network to call `saveForm` on the server. Then we call `saveForm` from `onsubmit` like any other function, clear the input when `saveForm` returns, and log the result: ```ehtml app/pages/home/template.ehtml import "./style.css"; import { db } from "@elements/app"; interface Form { id?: string; message: string; } /** @rpc */ function saveForm(form: Form): Form { return db.query` insert into messages (message) values (${form.message}) returning id, message `.firstOrThrow(); } function onsubmit(form: Form) { let result = saveForm(form); form.message = ""; console.log(result); } ``` We save the file. `elements start` is running in a terminal and builds the app each time a file is saved, and it prints `State: Ok`. In the browser we type "hello world" and click Send. The input clears, and the browser's console prints the object that `saveForm` returned, with the `id` and the `message` of the new row. In a second terminal, `elements db` opens a `psql` prompt on the app's database: ```bash Terminal elements db ``` At that prompt, `select * from messages;` prints the new row, with the `id` that the console printed. ## The Type Error When the Call Passes a String The call to `saveForm` goes over the network, and the build type checks it like any other function call. We pass a string where `saveForm` takes a `Form`: ```ts function onsubmit(form: Form) { let result = saveForm(form.message); form.message = ""; console.log(result); } ``` We save the file, and `elements start` prints the type error: ```text Terminal State: Error ERRORS: You have 1 error: 1. app/pages/home/template.ehtml:19:25 Argument of type 'string' is not assignable to parameter of type 'Form'. 18: function onsubmit(form: Form) { 19: let result = saveForm(form.message); 20: form.message = ""; [TS2345] ``` The build reports the mistake when the file is saved. Without the type check, the call would fail at runtime, in front of the people who use the app. We change the call back to `saveForm(form)`, and `elements start` prints `State: Ok`. ## The Security Error Without the @rpc Build Tag We delete the `/** @rpc */` comment above `saveForm` and save. The build fails with a security error: ```text Terminal State: Error ERRORS: You have 1 error: 1. app/pages/home/template.ehtml:10:10 Security error: cannot call server code from the browser without going through an rpc function. 9: function saveForm(form: Form): Form { 10: return db.query` 11: insert into messages (message) Call stack: 3. app/pages/home/template.ehtml:10:10 db.query 2. app/pages/home/template.ehtml:18:16 saveForm 1. app/pages/home/template.ehtml:26:23 onsubmit Try: - Put the server code inside a function with an @rpc build tag, then call that function. /** @rpc */ export function fn() {} [browser] [230001] ``` `db.query` is server code. The form's `onsubmit` event handler runs in the browser, and the call stack in the error goes from that event handler to `saveForm` to `db.query`. Browser code can call server code only through a function with the `@rpc` build tag. We put the `@rpc` build tag back on `saveForm`, and `elements start` prints `State: Ok`. ## The Two Versions the Build Writes The build writes two versions of every rpc function: one for the browser and one for the server. In the browser's version, the body of `saveForm` is replaced with one call: ```js /** @rpc */ async function saveForm(form) { return app.callAsync("app/pages/home/template.ehtml:saveForm", ...arguments); } ``` The string names the file and the function, and `...arguments` passes the arguments of the call. The server's version of `saveForm` has the insert query, and it runs on the server. The browser's JavaScript does not have the query, so it does not have the name of the `messages` table or the names of its columns. ## Async Await Added by the Build A call over the network is async, and we never wrote `await`. The build adds `async` to `saveForm`, to `onsubmit` and to the form's event handler, and adds `await` at each call. The browser's version of `onsubmit` is: ```js async function onsubmit(form) { let result = await (saveForm(form)); form.message = ""; console.log(result); } ``` The form's event handler becomes: ```js "onsubmit": async () => await (onsubmit(this.attrs.form)) ``` Because of the `await`, the line `form.message = "";` runs after `saveForm` has returned. If you write `async` and `await` yourself and forget the `await` at the call to `saveForm`, that line runs before `saveForm` has returned. In Elements the build adds every `await`, so no `await` is forgotten. To write `async` and `await` yourself, declare your rpc function `async`. The build then leaves the functions that call it as you wrote them, and you write `async`, `await` and the `Promise` return type: ```ts /** @rpc */ async function saveForm(form: Form): Promise
{ return db.query` insert into messages (message) values (${form.message}) returning id, message `.firstOrThrow(); } async function onsubmit(form: Form) { let result = await saveForm(form); form.message = ""; console.log(result); } ``` The video takes the hand-written `async` and `await` out again, and the rest of this post has the first version of `saveForm`. ## The WebSocket Request and Reply Every page keeps one WebSocket connection to the app server, and the connection stays open for as long as the page is open. A call to an rpc function sends one request over the WebSocket. The request has an `id`, the `method` and the arguments, as JSON: ```json { "kind": "rpc.request", "id": "01a24a5f-224a-7090-b877-733298cac8b6", "method": "app/pages/home/template.ehtml:saveForm", "args": [ { "message": "hello world" } ] } ``` The server calls `saveForm` and sends back one reply with the same `id` and the result: ```json { "kind": "rpc.response", "id": "01a24a5f-224a-7090-b877-733298cac8b6", "ok": true, "result": { "id": "01a24a5f-225b-7482-9aac-09e2196ac111", "message": "hello world" } } ``` In Chrome's developer tools, both messages are listed under Network, on the WebSocket's Messages tab. ## Elements JSON We add a `createdAt` date to `Form`, and add `createdAt` to the query's `returning` clause: ```ts interface Form { id?: string; message: string; createdAt?: Date; } /** @rpc */ function saveForm(form: Form): Form { return db.query` insert into messages (message) values (${form.message}) returning id, message, createdAt `.firstOrThrow(); } ``` Plain JSON has no date type, so in plain JSON `createdAt` would arrive in the browser as a string. The arguments and the return value of an rpc function are sent as Elements JSON, our extension of JSON. Elements JSON is valid JSON, and it records the type of a value such as a `Date`. In the reply, `createdAt` is: ```json { "$type": "Date", "$value": 1796511195189 } ``` We send a message, and the console prints the returned object. Its `createdAt` property is a `Date`. Elements JSON also records the class of an instance of your own class, when the class has the `@json` decorator. We make `Form` a class with a `toString` method and add the decorator. `saveForm` now returns an instance of `Form`, and the page's `form` attribute defaults to `new Form()`: ```ehtml app/pages/home/template.ehtml import "./style.css"; import { db, json } from "@elements/app"; @json class Form { id?: string; message: string = ""; createdAt?: Date; toString() { return `${this.message} at ${this.createdAt}`; } } /** @rpc */ function saveForm(form: Form): Form { let row = db.query` insert into messages (message) values (${form.message}) returning id, message, createdAt `.firstOrThrow(); return Object.assign(new Form(), row); } function onsubmit(form: Form) { let result = saveForm(form); form.message = ""; console.log(result); } ``` We send a message. The console prints a `Form`, and the prototype of that object has the `toString` method. The value that `saveForm` returns in the browser is an instance of `Form`, with its methods. ## Routes and Rpc Functions A route is a function that the server calls when the browser requests the page. The demo's route is `app/pages/home/index.ts`. The route passes data to the page, and the server returns the page's HTML with that data already in it. We create a `form` with a message and pass it to the page: ```ts app/pages/home/index.ts import { Request } from "@elements/app"; import html from "./template"; export default function route(req: Request) { let form = { message: "route data" }; return new html({ form }); } ``` We reload the page, and the input holds "route data". The HTML that the server sent has the value in the input: ```html ``` The browser draws the page from that HTML, so the user does not wait on a blank screen while JavaScript loads. A search engine can read the message in the HTML without loading JavaScript. An rpc function is typically called after the page has loaded, as `saveForm` is called when the form is submitted. A route can also call an rpc function like any other function, once the function is exported from the template and imported in the route. ## The Session, and Errors Over the Wire The session is available in routes and in rpc functions, with no setup. Before the query runs, we call `session.isLoggedInOrThrow()`. It throws an `AuthError` when the user is not logged in: ```ts import { db, json, session } from "@elements/app"; /** @rpc */ function saveForm(form: Form): Form { session.isLoggedInOrThrow(); let row = db.query` insert into messages (message) values (${form.message}) returning id, message, createdAt `.firstOrThrow(); return Object.assign(new Form(), row); } ``` When `saveForm` throws an error on the server, the server sends the error in its reply, and the same error is thrown in the browser at the call to `saveForm`. We catch the error in `onsubmit`: ```ts function onsubmit(form: Form) { try { let result = saveForm(form); form.message = ""; console.log(result); } catch (err) { console.log(err); } } ``` We are not logged in. We send a message, and the console prints the error that `onsubmit` caught: ```text Console AuthError: Not logged in ``` ## The React Bug of December 2025 On December 3, 2025, the React team published [Critical Security Vulnerability in React Server Components](https://react.dev/blog/2025/12/03/critical-security-vulnerability-in-react-server-components). The post describes an unauthenticated remote code execution vulnerability, rated CVSS 10.0. The [CVE record](https://www.cve.org/CVERecord?id=CVE-2025-55182) is CVE-2025-55182, and its score is 10.0, critical. Remote code execution means that an attacker could run his own code on the server. Amazon [reported](https://aws.amazon.com/blogs/security/china-nexus-cyber-threat-groups-rapidly-exploit-react2shell-vulnerability-cve-2025-55182/) that within hours of the disclosure, its threat intelligence teams observed active exploitation attempts by multiple China state-nexus threat groups. Cloudflare [reported](https://blog.cloudflare.com/5-december-2025-outage/) that a change it made to detect and mitigate the vulnerability caused an outage on December 5, 2025. The outage affected approximately 28% of all HTTP traffic served by Cloudflare. The React team wrote that the bug was "a flaw in how React decodes payloads sent to React Server Function endpoints". The [public proof of concept](https://github.com/lachlan2k/React2Shell-CVE-2025-55182-original-poc/blob/main/01-submitted-poc.js) is one request. One of its arguments refers to `constructor:constructor`, which reaches JavaScript's `Function` constructor, and another holds the code to run, `console.log(7*7+1)`. By changing the arguments of a request, an attacker controlled which code the server ran. ## How the Server Checks an Rpc Request We designed rpc in Elements so that a request can only name a file and a function in that file. The arguments and the return value are sent over the WebSocket as data, never as code to run. The server makes these checks on each request, in this order. The server refuses a path to a file outside the app's folder. We send a request whose `method` is `../release/app/pages/home/template.ehtml:saveForm`, and the server replies with a `NotFoundError`. For an rpc request, the server loads a file only when the file starts with a `"use rpc"` directive. The build writes that directive as the first line of every file that has rpc functions. The server's version of our template is `.elements/build/app/pages/home/template.ehtml.js`, and its first line is: ```js "use rpc"; ``` After the server loads the file, it calls the function only when the function has an `__rpc__` property set to `true`. The build writes that property, and only on functions with the `@rpc` build tag. Near the end of the same file: ```js saveForm.__rpc__ = true; exports.saveForm = saveForm; ``` A request holds JSON data, and nothing in a request can set a property on a function in the server's memory. The server reads the arguments as Elements JSON and passes them to `saveForm`. The arguments are data, so no part of an argument is run as code. ## A Function Without the @rpc Build Tag We add a second function to the template. It is exported, and it does not have the `@rpc` build tag: ```ts export function doNotCallMeFromTheBrowser() {} ``` We save, and `elements start` prints `State: Ok`. In the browser's console, we send a request that names the function: ```js Console await $client.callAsync("app/pages/home/template.ehtml:doNotCallMeFromTheBrowser") ``` The server refuses the request, and the console prints the error in red: ```text Console Uncaught NotFoundError: "app/pages/home/template.ehtml:doNotCallMeFromTheBrowser" not found ``` The server's version of the template has no `doNotCallMeFromTheBrowser.__rpc__` line, so the server does not call the function. The functions on your server that a browser can call are the functions with the `@rpc` build tag, and no others. In Elements, calling a function on the server from the browser is a regular function call. The build type checks the call and adds `async` and `await`, and the server checks each request before it calls the function. ## Transcript Every developer and every agent knows how to call a function. So we designed rpc in Elements to be a type checked function call from the browser to the server. But we have to do this carefully, to avoid major security issues like the one in 2025. At the end of this video, I'll explain that incident and how we prevent it. Say we want to save a message from this form in the database. When you submit it, the onsubmit function runs in the browser, but the database is on the server. So we write a function called saveForm, with one insert query, and we put the @rpc build tag on it. Rpc stands for remote procedure call, which means the browser sends a request over the network to call the saveForm function on the server. Then we call saveForm from onsubmit like any other function, clear the input when it returns, and log the result. When I send a message, the input clears, and I see the result in the console, and in a terminal, elements db shows the new row in the messages table. The call to saveForm goes over the network, but the build type checks it like any other function call. If I pass a string instead of the form, I get a type error as soon as I save the file. That's important because we catch the mistake at build time, and not at runtime, where the end users would see the error. When I pass the form again, the build is green. If I take the @rpc build tag off and save, I get a security error. A function that queries the database is server code, and browser code can't call it without going through an rpc function. With the @rpc build tag back on, the build is green. The build writes two versions of every rpc function, one for the browser and one for the server. In the browser's version, the body is replaced with one call, which names the file and the function and passes the arguments along. The query stays on the server, so you don't leak information about your database schema to the browser. A call over the network is async, but we never wrote await. That's because async await is handled automatically during the build, so the next line waits for saveForm to return automatically. Written by hand, the same code needs async on all three functions, and await at every call, and a Promise in the return type. If you forget the await, the next line runs before saveForm is returned. So Elements does the right thing by default. If you want to manage async await yourself, you can make your rpc function async, and then Elements won't automatically transform the call graph. Every page keeps one WebSocket connection to the server. WebSockets are cheap, so it stays open for as long as the page does. An rpc call sends one request over the WebSocket, with an id, the method, and the arguments as JSON, the server runs saveForm, and sends back one reply with the same id and the result. Back in the editor, we add a createdAt date to the form. Plain JSON has no Date type, so it would arrive in the browser as a string. Elements has its own extended JSON that handles advanced types, so createdAt arrives as a proper Date. Elements JSON works for your own classes too, if you add the @json decorator. So we make a Form class with a toString method, and add the decorator. Now saveForm returns an instance of Form in the browser, with its methods. How do rpc functions compare to routes? A route is a function that's called when the browser requests the page, so that's where we pass in the initial data, and the server returns complete HTML. That's important because the page is rendered immediately, and the user never waits on a blank screen. It's also important because search engines can read it without loading JavaScript, and that can only help your SEO score. In contrast, an rpc function is typically called after the page is loaded, like when we save our form. But we can also call it from the route, like any other function. The session is available automatically inside routes and rpc functions. So before we run the query, we call session.isLoggedInOrThrow, and if the user isn't logged in, we get an error. When saveForm throws an error, the error goes over the wire, and we can catch it right here in our event handler in the browser. I'm not logged in, so when I send a message, we catch an AuthError, and here it is, printed in the console. In December 2025, one security bug almost broke the entire internet. The bug was in the way React handled remote procedure calls. An attacker could run his own arbitrary code on the server. The React team rated it 10 out of 10 for severity. Within hours, Amazon saw Chinese state hackers trying to exploit it. 28% of Cloudflare's traffic went down because of a change they pushed out to block the attack. The bug was in how React read the arguments of a request. By changing them, an attacker could control which code the server ran. Calling server code from the browser is serious, and it takes careful engineering to keep it secure. We designed rpc in Elements so a request can only name a file and a function in that file, and the arguments and return value are sent over the wire as data, not executable code. If a bad guy sends a path to a file outside your app's folder, the server refuses it. For an rpc request, the server only loads a file that starts with a "use rpc" directive, and the build puts that directive in every file that has rpc functions. Once the file is loaded, the server will only invoke the function if it has an rpc property set to true. The build tool writes that property, only on functions with the @rpc build tag, and an attacker has no way to set it. So we have another exported function that we don't want accessible from the browser. If a bad guy tries to call it, the server refuses and throws a not found error. The only functions on your server that a browser can call are the ones you tagged with rpc. The server reads the arguments as Elements JSON and gives them to saveForm, so they're never run as code. In Elements, calling a function on the server from the browser is a regular function call. It's type checked, async await is handled automatically, and it's secure.