Landing page backend (dynamic handlers)
Besides its static files, an uploaded landing page can have a real backend — small JavaScript handlers tied to individual addresses. Each handler is bound to a path and an HTTP method; when a visitor opens that address, Qubix runs the handler and returns whatever it builds — a page, a JSON answer, a redirect, a status code.
Use it when a page must do something on the server rather than just show static content: accept a lead via a POST request, answer a specific path with generated HTML, or send a redirect depending on the request. For ordinary whitepages and landings you don't need this — leave the Backend tab empty and the landing page is served as plain files.
Open the Backend tab
A landing page card lists its sections in the sidebar on the left of the window; Backend is in the Landing page group, next to Files and Live. The open section is saved in the address bar, so you can copy a link straight to it.
- Open the Landing pages section and click the landing page you need.
- Click Backend in the sidebar.
If the landing page has no handlers yet, the list shows a hint that the + new button creates a handler from a template.
The Backend tab is only needed when the page must process something on the server. A purely static page works without any handlers.
Create a handler
- On the Backend tab, click + new in the top-left, above the handler list. A new handler is created from a ready-made template in the
handle(req, res)form and opens in the editor. - In the row above the editor, in the route (path pattern) field, set the address the handler answers on. A route starts with
/; the server won't accept an empty or invalid route on save and will name the reason. The field accepts a template with variable parts (for example,/users/:id)::name— captures one path segment (for example,:idin/users/:idmatches/users/42);*— captures the rest of the path across several segments;**— matches the rest of the path without capturing it.
- Pick the method —
GET,POST,PUT,DELETE,PATCH,HEAD,OPTIONS, or ANY (answers any method). - Keep the On switch on so the handler works on the live landing page. Turn it off to keep the handler saved but inactive. On a landing page you do not own, only the landing page's owner or an administrator can turn a handler on when it carries real code — its code runs with the owner's rights; an empty handler has no such restriction.
- In the central editor, write the handler code (see The handler code below).
- Click Save (or Cmd+S, on Windows — Ctrl+S).
In the list on the left, each handler is shown as its method and path (a handler with no method set is shown as ANY); a disabled one carries the Off mark underneath.
If more than one handler could answer the same address, Qubix picks the most specific one — a handler with an exact path wins over one with a variable part or an asterisk. So you can keep a precise handler next to a broad catch-all without them clashing.
The handler code
A handler is a JavaScript function named strictly handle. The engine looks the function
up by that name in your code and calls it on every request. There are two ways to write it,
and both work:
function handle(req, res)— the form for new handlers. The names are the same as in Node and Express, so the body of a handler from an Express example usually carries over with no changes or almost none — what is not supported here is named in the reference below;function handle(r)— the older njs-style form with a single object. Handlers already written this way keep working exactly as before; nothing needs rewriting.
Which form you get is decided by the second parameter of your function. Declare one and
the handler is called with req and res; declare none and it is called with the single r.
A second parameter with a default value (req, res = null) and a rest parameter (...args)
both count as declared. When your handler is called with req and res, the run log says so
and names the number of declared parameters; if the declaration can't be read unambiguously,
the log warns you which way the handler was called.
AI mode
You are already in the right window: the landing page card, the Backend tab, the handler open in the editor. Call the AI assistant right in this window and describe in plain words what should happen:
- "Accept POST /lead with JSON, check the email field and pass the lead on to https://crm.example.com/leads";
- "Redirect /go to the thank-you page";
- "Why does my handler answer an empty 200? Here is my code: …".
The assistant writes the code with the correct handle entry point.
Manual mode
A complete minimal handler:
function handle(req, res) {
res.json({ ok: true, path: req.path })
}
The same handler in the older form — this is what handlers written before look like, and they work without changes:
function handle(r) {
r.headersOut['Content-Type'] = 'application/json'
r.return(200, JSON.stringify({ ok: true, path: r.uri }))
}
A function under any other name (main, onRequest, handler) is not called at all. The
program still runs without errors — just "idle" — and the visitor gets the default answer:
200 with an empty body. The test run says so in a line above the response body —
Handler not called: the code has no function named handle. — and lists the functions it did find in your
code, so a misspelled name is visible right away. If your handler answers with an instant empty
200 — check the function name first.
A handle that was called but returned without answering is a different case: the visitor
still gets an empty 200, and the test run shows Handler did not respond: handle finished without a response — the visitor gets an empty page with status 200.
With the handle(req, res) form, the run log also gets an error line saying there was no answer.
There is also a top-level program with no function at all: the code that runs top to bottom
calls r.return(...) itself. It is enough for the simplest cases, but the main form is the one
with the handle function.
The editor is a full code editor with syntax highlighting. The fields of req, res and the
older r are listed in the reference below: the editor does not suggest them by itself, because
the parameters of your handle function are not typed.
A complete example: accepting a lead from the landing
POST /lead takes a JSON with an email, validates it, passes the lead to an outside CRM and
answers the page:
function handle(req, res) {
if (req.method !== 'POST') {
res.status(405).json({ error: 'method not allowed' })
return
}
// JSON arrives already parsed; form fields arrive as an object in exactly the same way
const data = req.body || {}
if (!data.email) {
res.status(400).json({ error: 'email required' })
return
}
// pass the lead to your CRM together with the click context
const answer = fetch('https://crm.example.com/leads', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: data.email,
click_id: req.variables.click_id,
geo: req.variables.geo,
}),
})
if (!answer.ok) {
console.error('CRM answered ' + answer.status)
res.status(502).json({ error: 'crm unavailable' })
return
}
res.json({ ok: true })
}
Two more everyday moves:
// a redirect
function handle(req, res) {
res.redirect('https://example.com/thanks')
}
// remember the visitor and answer
function handle(req, res) {
req.session.set('lead', req.body.email)
res.cookie('seen', '1', { maxAge: 86400000, httpOnly: true })
res.send('ok')
}
You answer with the res object: res.status(code) sets the status code, res.send(body) and
res.json(value) send the body, res.redirect(url) sends a redirect. The calls chain, so
res.status(201).send('created') is one line. In the older form the same job is done by a
single r.return(status, body, location). Both forms build exactly the same answer — the full
breakdown of the fields is in the tables below.
Inside a handler you have the same read-only database queries (sql) and the same state
between calls (ctx.state) as in Scripts. But the outbound HTTP request
here is the global fetch(...) function, not ctx.fetch(...): in handlers ctx carries
only the state, and an example with ctx.fetch copied from the Scripts article word for word
will not work. The fetch
settings are the same: addresses only from the administrator's allowlist, a proxy via the
proxy field, and a wait ceiling via timeout_ms in the call options. An sql query runs with
the rights of the landing page's owner; which tables and columns it can reach is in
Tables for sql queries. QubApp.mcp — the tools of this Qubix
installation — works here with the landing page owner's rights too, for every visitor of the page:
one method per tool, QubApp.mcp.tools() lists them, and a failed call throws an McpError
whose delivery field tells whether the call reached the tool —
Qubix tools from code. QubApp.notify writes to people of the panel with the
same rights — tgBot through the Qubix notification bot, qchat into the «Qubix» channel of TeleQube, email from the address for notifications —
signed with the site's name, and answers who got it (sent) and who did not (undelivered). QubixApp is the former name of
the same object: code written with it works as before.
State between requests: ctx.state
ctx.state is the handler's own store: get(key), set(key, value), delete(key), and
keys(). It is one for all requests to this handler, from all visitors, and it survives a
server restart. Keep what belongs to a single visitor in that visitor's session — req.session.
You can store a value that fits into JSON: numbers, strings, true/false, null, arrays,
and plain objects. NaN, Infinity, a function, a date outside the years 0–9999, an object that
refers to itself, and nesting deeper than 10,000 levels can't be stored: ctx.state.set() then
throws an error right away, and the previously stored value stays. Uncaught, this error fails the
request like any other (more in the "When the handler fails" section below); if the answer must go
out no matter what, wrap the call in try…catch.
What is written to ctx.state is saved when the handler finishes its work — even if it failed
with an error. It is not saved only for a handler that didn't stop even after its allotted time.
Your own databases: Qubix.db
A handler can read and write your own database — with the same Qubix.db that scripts use; which
databases it connects to is listed in Which databases.
Qubix.db.connect(...) with a connection string or the name of a saved connection opens a connection; then query returns rows, and
exec returns the number of changed rows. Values go separately from the query text — each
database marks their place its own way, $1, $2 in PostgreSQL:
function handle(req, res) {
const db = Qubix.db.connect('postgres://user:[email protected]:5432/crm');
const rows = db.query('SELECT id, email FROM customers WHERE id = $1', [Number(req.query.id)]);
db.close();
res.json(rows);
}
The database host must be in the Database hosts for scripts list (Qubix settings → JavaScript) — one list for scripts and handlers; an empty list turns connections off. A name in the list opens internet addresses only; a database on an internal network is listed by its address or network. Every page request opens its own connections, and whatever the handler leaves open is closed when it finishes its work.
A saved name is looked up among the Mine connections of the landing page's owner on a live visit, of whoever pressed Run on a test run, and then among the Shared ones — see Saved connections. The Secrets panel opens with the button with a database icon in the top row of the open handler, next to Save.
Handlers have their own limits, and they apply to a single page request. They are in the
Landing page handlers (Locations) block of the same tab: Databases: max connections per page request,
Databases: max queries per page request, Databases: max rows per query,
Databases: max response size, and Databases: query timeout.
Rows beyond the limit are not read, and the test run's log says so. Database queries from the
test run are real: exec in it changes rows just as on the live landing page.
Qubix.db is covered in detail in the database reference.
Report a conversion: Qubix.conversion
When the handler itself accepts a registration or a payment, it reports the conversion with one call. Qubix knows the visitor of the request, so you pass no click identifier and need no outbound request:
function handle(req, res) {
// the registration is accepted
Qubix.conversion('reg');
// a payment
Qubix.conversion('dep', { payout: '50', currency: 'USD', txid: 'order-123' });
res.json({ ok: true });
}
The names and fields are the same as on the page — reg, dep or trash and the postback's
field names, see Report a registration or a deposit. Another
name stops the handler with an error. In the test run the name is checked the same way, and no
conversion is recorded.
One page request reports at most as many conversions as the Qubix.conversion: max calls per request
setting allows (Qubix settings → JavaScript, 5 by default); the call over it
stops the handler with an error. The conversions of one visitor address are also counted per minute, under the same
ceiling as the page's own events. A field value is cut to 512 characters, and only a string, a number or true/false
is taken as a value — an object is skipped. When the server is processing too many conversions at once, the call
stops the handler with an error: report the conversion again on the next request. In the landing page's preview in the panel
the call is checked the same way as in the test run, and no conversion is recorded.
Three places — three entry points
There are three places in Qubix where you write JavaScript, and each has its own entry point and its own name for the outbound request. Copying an example from one article into another editor, check against this table:
| Entry point | Outbound request | Written for | |
|---|---|---|---|
| Scripts | function main() | ctx.fetch(...) | ad automation on a schedule |
| Landing page handlers — this article | function handle(req, res), or the older function handle(r) | fetch(...) — global | server logic of an uploaded landing page |
| Britva rules | function checkAd(ad) | fetch(...) — global | per-ad condition → action |
The req and res reference
The main form. Everything the handler reads from the request, and everything it uses to build the answer.
Reading the request — req:
| Field | What it is |
|---|---|
req.method | The request's HTTP method (GET, POST, …) |
req.path | The address the handler answered on (for example, /promo/123) |
req.originalUrl | The request path as it arrived, without the address parameters: when the landing page is opened at its direct address — with the /_w/… service prefix; when it is opened via a campaign — the path on the campaign's domain. In the test run — with the prefix |
req.query | The address parameters only — form fields never land here |
req.body | The parsed body: JSON becomes an object, a form — both a plain one and a multipart one (multipart/form-data) — becomes an object of fields, with the file parts skipped; anything else stays a string. A body that couldn't be parsed also arrives as a string, and the run log warns about it |
req.rawBody | The request body as a string, exactly as it arrived |
req.params | Values captured from the path template (for example, id from /users/:id) |
req.headers | The request headers, names in lower case |
req.get(name) | One request header, regardless of the case you ask in |
req.cookies | The visitor's cookies as an object, decoded the way Express's cookie-parser does it; an object stored by res.cookie comes back parsed |
req.ip | The visitor's address. In the test run there is no visitor, so there it is the address of whoever clicked Run |
req.variables | The click context: geo, click_id, sub1, sub2, sub3, sub4, sub5, lang |
req.session | The visitor session: get(key), set(key, value), delete(key) |
Building the answer — res:
| Method | Action |
|---|---|
res.status(code) | Set the status code; returns res, so the calls chain |
res.send(body) | Send the body; an object or an array goes out as JSON. No value — an empty body |
res.json(value) | Send the value as JSON and set the matching content type |
res.redirect(url) / res.redirect(status, url) | Send a redirect; the status defaults to 302 |
res.set(name, value) | Set a response header |
res.cookie(name, value, options) | Set a cookie on the visitor. Several cookies in one answer all arrive |
res.cookie writes the value the way Express does: an object or an array is stored as JSON with
the j: prefix, and the value is encoded with encodeURIComponent. So
res.cookie('cart', { items: [1, 2] }) and res.cookie('name', 'Иван') arrive intact, and
req.cookies gives them back decoded, with the object already parsed.
The options, all of them optional, carry Express's names and units: path (defaults to /),
domain, expires (a Date), maxAge (the lifetime in milliseconds, as in Express; it wins
over expires), httpOnly, secure, sameSite (lax, strict, none, or true for
strict), partitioned (only together with secure) and encode (your own function instead of
encodeURIComponent). Signed cookies (signed: true) are not supported, and priority is
dropped. A cookie that cannot be set — with a name the Set-Cookie header does not accept, with
the name of the session cookie of any landing page on this server, with an option of a wrong value — the
engine does not set; everything not applied is named in the run log.
The Cookie header your handler sees has no session cookies of this server's landing pages and no panel
sign-in cookie: read the visitor's session through req.session (r.session in the older
form). A Set-Cookie with such a name, without a name at all, or with a control character is not
sent, whichever way you set it — res.cookie, res.set or r.headersOut — and neither is
Clear-Site-Data (on this server it would clear other landing pages' cookies too). The run log names the
reason.
The body is collected whole and goes to the visitor after your handler returns, so there is no
res.write and no res.end: there is nothing to close. An answer with no body is
res.status(204).send(). If you answer twice, the last state wins, and the run log warns you
about it.
The run log
console.log(...), console.info(...), console.debug(...), console.warn(...) and
console.error(...) write to the run log — the same one the test run shows below the
editor. In the older form the same lines are written by r.log, r.warn and r.error.
The run log is visible only in the test run: for a live visitor's request it isn't saved anywhere, and only the reason for a failed request gets into the server log (see the next section). The log is limited both in the number of records and in the length of each one: a full log says so in its last line, and a record that is too long is cut off with a mark.
When the handler fails
An error your handler does not catch fails the request, wherever it was thrown: directly, after
an await, inside a .then with no .catch, or in an async function handle that throws before
its first await. The visitor gets an error code with an empty body — even if the handler had
already answered with res.send or r.return before the error: that answer is not sent.
| What happened | What the visitor gets |
|---|---|
The handler asks for or holds more memory than allowed, including after an await | 503 with an empty body |
| The handler didn't finish within its allotted time | 500 with an empty body |
| The handler didn't stop even after its allotted time | 503 with an empty body |
Any other error the handler did not catch, including one after an await | 500 with an empty body |
One exception: if a memory refusal is left unhandled and the handler then catches a later one, the
earlier refusal is counted as an ordinary error — 500.
The memory limit is set by the Memory per script setting, and the time by Max handler runtime; both are in Qubix settings → JavaScript.
In a handler, a ctx.state.set() refusal is an ordinary handler error: if it is not caught, the
visitor gets an empty 500 response and the reason goes to the server log.
A rejected promise that gets its .catch later in the same run is not an error: what counts is
whether the refusal is still unhandled when the run ends.
The visitor never sees the reason; the server log gets a line naming the landing page and the reason. To see it next to the handler's own log, repeat the request in the Test runner panel: a failed run shows the error with its reason and, below it, the console — everything the handler managed to log before it failed. The test run executes the request you fill in, not the visitor's, so a failure that depends on what the visitor sent may not repeat there.
The r object reference
The older form, kept for handlers already written this way.
Everything the handler reads from the request and uses to build the response.
Reading the request:
| Field | What it is |
|---|---|
r.method | The request's HTTP method (GET, POST, …) |
r.uri | The address the handler answered on (for example, /promo/123) |
r.rawUri | The request path as it arrived, without the address parameters — the same as req.originalUrl |
r.args | The address and form parameters (key → value) |
r.params | Values captured from the path template (for example, id from /users/:id) |
r.requestBuffer | The request body as a string |
r.headersIn | The request headers |
r.remoteAddress | The visitor's IP |
r.variables | The click context: geo, click_id, sub1, sub2, sub3, sub4, sub5, lang |
r.session | The visitor session: get(key), set(key, value), delete(key) |
Building the response:
| Field / method | Action |
|---|---|
r.headersOut | The response headers (you can set and delete them) |
r.return(status, body?, location?) | Send the response; location is the redirect address |
r.log(...), r.warn(...), r.error(...) | Write to the run log (visible in the test run) |
Crypto helpers
A handler also has crypto helpers:
| Method | What it does |
|---|---|
crypto.uuid() | A random identifier |
crypto.hmac(algo, key, data) | HMAC of data with key, hex-encoded; algo is 'sha256', 'sha1', or 'md5' |
Handy, for example, to sign data before sending it to an external service via fetch.
Base64 and addresses
A handler has the same names for base64 and web addresses as a browser:
| Name | What it does |
|---|---|
btoa(text) | Encodes a string of Latin-1 characters as base64 |
atob(base64) | Decodes base64 back to a string; malformed input throws InvalidCharacterError |
new URL(url, base?) | The constructor parses an address; read and change its parts: protocol, username, password, host, hostname, port, pathname, search, hash, href, origin (read only) |
url.searchParams | The query of the address as URLSearchParams — change it, and url.search changes too |
url.toString(), url.toJSON() | The whole address as a string |
new URLSearchParams(init?) | The constructor takes a query string, an object or a list of pairs |
params.get(name), params.getAll(name), params.has(name) | Read a parameter: the first value, all values, whether it is there |
params.set(name, value), params.append(name, value), params.delete(name) | Replace, add or remove a parameter |
params.sort(), params.size | Sort the parameters by name; how many there are |
params.keys(), params.values(), params.entries(), params.forEach(fn) | Walk the parameters |
params.toString() | The query string without the leading ? |
These strings count toward the memory a run may hold, as any other string the handler builds.
Test a handler
Each handler has a built-in test run on the right of the editor — the Test runner panel. Send a test request and see exactly what the handler answers, without touching the live landing page. But the outbound requests from the run are real: if the handler sends a lead to a CRM via fetch or writes to your database via Qubix.db, the test run does it too.
- Pick the method and enter the path to test (for example,
/users/42). - (Optional) Fill in the request inputs:
- Query (JSON) — the address parameters as a JSON object, for example
{"id": "42"}; - Request headers — the request headers, also as a JSON object, for example
{"Content-Type": "application/x-www-form-urlencoded"}: without such a header, a form body isn't parsed into fields; - Body (raw) — the request body as is;
geo,click_id,sub1…sub5, andlang— the click context the handler reads inreq.variables(r.variablesin the older form).
- Query (JSON) — the address parameters as a JSON object, for example
- Click Run.
The run executes the code exactly as it is in the editor right now, unsaved changes included: there is no need to click Save before a test run.
The result appears below:
- the response status (colored green / blue / red) and how long the run took;
- params — the values captured from the path template;
- Location — the redirect target, if the handler set one;
- the response headers and body;
- Session state after the run — what the visitor's session holds after the run, if there is anything in it;
- console — everything the handler wrote to the log during the run.
If the handler wrote something to the visitor's session or deleted something from it, the session touched mark appears next to the status.
Above the response body the panel shows a warning line when something needs your attention:
- Route wouldn't match — on the live landing page this path would not reach this handler; the test run ran it anyway, with nothing captured from the path;
- Handler is disabled: it will not run on the live landing page.
- Handler not called: the code has no function named handle. — the line also lists the functions declared in your code;
- Handler did not respond: handle finished without a response — the visitor gets an empty page with status 200.
- r.return() was called without a status code and was ignored. Pass the status code:
r.return(200, body).
None of these lines changes what a visitor gets on the live landing page — they are for you.
The test run executes the handler with the same time and memory limits as the live landing page, but in a few places it differs from a visitor's request:
sqlruns with the rights of whoever clicked Run, not of the landing page's owner, so there may be more or fewer rows than on the live landing page;- the test run neither reads nor writes the handler's state:
ctx.state.getreturnsundefined, andctx.state.setandctx.state.deletethrow an error; - the visitor's session starts empty in every run;
req.ipis the address of whoever clicked Run;QubApp.mcpcalls the tools with the rights of whoever clicked Run and only reads: a tool that changes data is refused;QubApp.notifysends nothing: each of its methods (tgBot,qchat,email) is refused.
Query (JSON) and Request headers are JSON objects in which every value is a string in quotes. If the JSON is invalid, the test won't run and the field is highlighted. If a value isn't written as a string (for example, the number 42 instead of "42"), the run is refused with the field and the key named. Fix the field and click Run again.
Edit landing page files
The card's Files tab holds the landing page's static files (HTML, CSS, JS, images, fonts) in a tree on the left and a code editor on the right. Text files open with syntax highlighting; save with Save or Cmd+S (on Windows — Ctrl+S). Images, video, audio and other files get a preview or a download. You can drag files between folders and add new ones from your computer.
A full breakdown of the Files tab is in Landing pages and Uploading a landing page.
Field and behavior notes
Route (path pattern) — the address the handler answers on. Supports :name (one segment), * (the rest, captured), and ** (the rest, not captured). The captured segments are available to the handler and are shown in the test run in the params block.
Method — which HTTP method triggers the handler. ANY answers any method.
On — whether the handler runs on the live landing page. A disabled handler stays saved but is skipped. On a landing page you do not own, only the landing page's owner or an administrator can turn a handler on when it carries real code (its code runs with the owner's rights); an empty handler has no such restriction, and anyone who may edit the landing page can turn one off.
+ new — creates a handler from the built-in template, ready to edit.