Code Icon

Build an app / Node.js + HTTP

How to connect a Node.js app to SingleStore via HTTP

on-this-guideOn this guide

In this guide, you’ll learn how to connect a Node.js application to SingleStore using its HTTP Data API. We’ll walk you through creating a deployment, workspace, and database in the SingleStore Portal, retrieving your connection credentials, and configuring your Node.js project with environment variables. Finally, you’ll implement a reusable helper function to execute and query SQL statements over HTTP, giving you a solid foundation for building applications on SingleStore.

prerequisitesPrerequisites

  • SingleStore Account

  • Node.js

Don’t have a SingleStore account yet?

Sign up nowArrow Up Right Icon

create-deploymentCreate deployment

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Create NewDeployment.

3. In the Create Workspace form, follow the on‑screen instructions to complete the form.

4. Click Create Workspace.

5. Wait for the workspace to finish deploying.

create-workspaceCreate workspace

Note: If the required workspace already exists in the target deployment, you can skip this step.

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Deployments.

3. From the deployments list, select the deployment where you want to create a workspace.

4. In the left‑hand pane, click + Create Workspace.

5. In the Create Workspace form, follow the on‑screen instructions to complete the form.

6. Сlick Create Workspace.

7. Wait for the workspace to finish deploying.

create-databaseCreate database

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Deployments.

3. From the deployments list, select the deployment where you want to create a database.

4. In the right‑hand pane, click + Create Database.

5. In the Create Database form, enter a new database name and select the workspace to attach it to.

6. Click Create Database.

retrieve-database-credentialsRetrieve database credentials

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Deployments.

3. From the deployments list, select the deployment that contains your database.

4. From the workspaces list, select the workspace to which your database is attached.

5. In the selected workspace, click Connect.

6. In the Connect dropdown, choose SQL IDE.

7. In the SQL IDE tab, copy the connection parameters.

If you don’t know the password, click Reset Password, then copy the new password.

prepare-environmentPrepare environment

1. Create a .env file in the root of your project.

2. In this file, define your connection details by adding the following variables:

1

DB_USER="<USER>"

2

DB_PASSWORD="<PASSWORD>"

3

DB_HOST="<HOST>"

4

DB_PORT="<PORT>"

5

DB_NAME="<DATABASE_NAME>"

If you don’t know your connection string, see the Retrieve database credentials section above.

3. Now, in a terminal pointing to the root directory of your project, install the dotenv NPM package to load your environment variables by running the following command:

1

npm install dotenv

4. Then, you’ll need to import dotenv into your application so you can retrieve the environment variables stored in your .env file. To do this, at the following import statement at the very top of your application entry point (e.g., index.js):

1

import 'dotenv/config'

5. Finally, you’ll add helper functions to query your database:

1

import { Buffer } from "buffer";

2

3

const { DB_USER, DB_PASSWORD, DB_HOST, DB_NAME } = process.env ?? {};

4

const CREDENTIALS = Buffer.from(`${DB_USER}:${DB_PASSWORD}`).toString("base64");

5

6

async function request(url, body) {

7

const response = await fetch(`https://${DB_HOST}/api/v2${url}`, {

8

body,

9

method: "POST",

10

headers: {

11

"Content-Type": "application/json",

12

Authorization: `Basic ${CREDENTIALS}`,

13

},

14

});

15

16

if (!response.ok) {

17

const text = await response.text();

18

throw new Error(`${response.status} ${response.statusText}\n${text}`);

19

}

20

21

return response.json();

22

}

23

24

async function query(sql, database = DB_NAME) {

25

return request("/query/rows", JSON.stringify({ sql, database }));

26

}

27

28

async function execute(sql, database = DB_NAME) {

29

return request("/exec", JSON.stringify({ sql, database }));

30

}
  • execute (/api/v2/exec): Executes SQL statements without returning result sets, typically used for DDL and DML operations (e.g., CREATE TABLE, INSERT, UPDATE, DELETE).

  • query (/api/v2/query/rows): Executes SQL statements and returns result sets typically used for SELECT queries. Each row in the result set is represented as an object mapping column names to their corresponding values.

query-databaseQuery database

Once you’ve added the above code, let’s test to make sure that the connection is working as anticipated. Here is an example of a simple code snippet you can add to your app's main function at the entry point (e.g., index.js).

1

import "dotenv/config";

2

import { Buffer } from "buffer";

3

4

const { DB_USER, DB_PASSWORD, DB_HOST, DB_NAME } = process.env ?? {};

5

const CREDENTIALS = Buffer.from(`${DB_USER}:${DB_PASSWORD}`).toString("base64");

6

7

async function request(url, body) {

8

const response = await fetch(`https://${DB_HOST}/api/v2${url}`, {

9

body,

10

method: "POST",

11

headers: {

12

"Content-Type": "application/json",

13

"Authorization": `Basic ${CREDENTIALS}`,

14

},

15

});

16

17

if (!response.ok) {

18

const text = await response.text();

19

throw new Error(`${response.status} ${response.statusText}\n${text}`);

20

}

21

22

return response.json();

23

}

24

25

async function query(sql, database = DB_NAME) {

26

return request("/query/rows", JSON.stringify({ sql, database }));

27

}

28

29

async function execute(sql, database = DB_NAME) {

30

return request("/exec", JSON.stringify({ sql, database }));

31

}

32

33

async function main() {

34

try {

35

console.log("Create users table");

36

const createTableSQL = `

37

CREATE TABLE IF NOT EXISTS users (

38

id BIGINT AUTO_INCREMENT PRIMARY KEY,

39

name VARCHAR(255) NOT NULL

40

)

41

`;

42

43

await execute(createTableSQL);

44

45

console.log("Insert user");

46

const insertUserSQL = "INSERT INTO users (name) VALUES ('John')";

47

const insertUserResult = await execute(insertUserSQL);

48

const insertedUserId = insertUserResult.lastInsertId;

49

console.log(insertUserResult);

50

51

console.log("Select all users");

52

const selectUsersSQL = "SELECT id, name FROM users";

53

const selectUsersResult = await query(selectUsersSQL);

54

console.dir(selectUsersResult, { depth: 5 });

55

56

console.log("Select user");

57

const selectUserSQL = `SELECT id, name FROM users WHERE id = ${insertedUserId}`;

58

const selectUserResult = await query(selectUserSQL);

59

console.dir(selectUserResult, { depth: 5 });

60

61

console.log("Update user");

62

const updateUserSQL = `UPDATE users SET name = 'John Doe' WHERE id = ${insertedUserId}`;

63

const updateUserResult = await execute(updateUserSQL);

64

console.log(updateUserResult);

65

66

console.log("Delete user");

67

const deleteUserSQL = `DELETE FROM users WHERE id = ${insertedUserId}`;

68

const deleteUserResult = await execute(deleteUserSQL);

69

console.log(deleteUserResult);

70

} catch (error) {

71

console.error(error);

72

}

73

}

74

75

main();

Once you’ve saved your changes, open a terminal, navigate to your project’s root directory, and run the test script:

1

node ./index.js

This will issue a query against your SingleStore instance, allowing you to see if connectivity was successful or if further troubleshooting is required.