• Start

Languages

/

JavaScript

/

Concepts

Bound queries

The JavaScript SDK provides bound queries and template tags for safely composing parameterised SurrealQL queries.

When composing dynamic queries, it is important to avoid string interpolation to prevent injection vulnerabilities. The JavaScript SDK provides bound queries and the surql template tag to safely parameterise values, along with an expressions API for composing dynamic conditions.

Utility

Description

surql

Tagged template literal for composing parameterised queries

BoundQuery

Class for manually building parameterised queries

expr()

Composes type-safe expressions for use in queries

The surql tagged template literal is the recommended way to compose parameterised queries. Interpolated values are automatically bound as parameters, preventing injection and preserving type safety.

import { surql } from 'surrealdb';

const name = 'John';
const minAge = 18;

const query = surql`SELECT * FROM users WHERE name = ${name} AND age > ${minAge}`;
const [users] = await db.query(query);

The surrealql export is an alias for surql if you prefer the longer name.

import { surrealql } from 'surrealdb';

const query = surrealql`CREATE person CONTENT ${{ name: 'Tobie' }}`;
Note

The SurrealQL VSCode extension provides syntax highlighting for surql template literals.

The BoundQuery class provides manual control over query composition. You can construct a query with initial bindings, and incrementally append fragments with additional parameters.

import { BoundQuery } from 'surrealdb';

const query = new BoundQuery(
    'SELECT * FROM users WHERE status = $status',
    { status: 'active' },
);

await db.query(query);

Use the .append() method to conditionally add SurrealQL fragments. The method uses the same tagged template literal syntax as surql, so interpolated values are automatically bound.

const query = new BoundQuery('SELECT * FROM person');
const filterName = 'Alice';

if (filterName) {
    query.append(surql` WHERE name = ${filterName}`);
}

const [results] = await db.query(query);

The expressions API provides functions for building dynamic conditions in a type-safe way. Expressions integrate with both surql and query builder methods like .where().

const checkActive = true;

await db.query(surql`SELECT * FROM users WHERE ${eq('active', checkActive)}`);

Was this page helpful?