Yandex Cloud
Search
Contact UsGet started
  • Blog
  • Pricing
  • Documentation
  • All Services
  • System Status
    • Featured
    • Infrastructure & Network
    • Data Platform
    • Containers
    • Developer tools
    • Serverless
    • Security
    • Monitoring & Resources
    • ML & AI
    • Business tools
  • All Solutions
    • By industry
    • By use case
    • Economics and Pricing
    • Security
    • Technical Support
    • Customer Stories
    • Gateway to Russia
    • Cloud for Startups
    • Education and Science
  • Blog
  • Pricing
  • Documentation
Yandex project
© 2025 Yandex.Cloud LLC
Yandex Cloud Functions
  • Comparison with other Yandex Cloud services
    • All tutorials
    • Creating a skill for Alice
    • Deploying a web application
    • Creating a skill for Alice and a website with authorization
    • Writing data from a device into a database
    • Writing load balancer logs to PostgreSQL
    • Developing a Slack bot
    • Developing a Telegram bot
    • Connecting to a YDB database from a Python function
    • Connecting to a YDB database from a function in Node.js
    • Converting a video to a GIF in Python
    • Creating a Node.js function using TypeScript
    • Developing a custom integration
    • Creating a budget trigger that invokes a function to stop a VM
    • Creating an interactive serverless application using WebSocket
    • Automatically copying objects from one Object Storage bucket to another
    • Running computations on a schedule in DataSphere
    • Interactive debugging of functions
    • Regular asynchronous recognition of audio files from Object Storage
    • Canary release of a Cloud Functions function
    • Deploying a fault-tolerant architecture with preemptible VMs
    • Creating triggers that invoke a function to stop a VM and send a Telegram notification
    • Loading data from Yandex Direct to a data mart enabled by Yandex Managed Service for ClickHouse® using Yandex Cloud Functions, Yandex Object Storage, and Yandex Data Transfer
    • Status monitoring of geographically distributed devices
    • Sensor reading monitoring and event notifications
    • Emulating multiple IoT devices
    • Streaming Yandex Cloud Postbox events to Yandex Data Streams and analyzing them using Yandex DataLens
    • URL shortener
    • Yandex Tracker: data export and visualization
    • Running computations in DataSphere using the API
    • Developing a Telegram bot for text and audio recognition
    • Configuring responses in Yandex Cloud Logging and Cloud Functions
    • Developing functions in Functions Framework and deploying them to Yandex Serverless Containers
  • Tools
  • Pricing policy
  • Access management
  • Terraform reference
  • Monitoring metrics
  • Audit Trails events
  • Release notes
  • FAQ

In this article:

  • Get your cloud ready
  • Required paid resources
  • Set up your environment
  • Create a service account
  • Create an authorized key
  • Create a YDB database
  • Create a function
  • Test the function
  • How to delete the resources you created
  1. Tutorials
  2. Connecting to a YDB database from a function in Node.js

Connecting to a Yandex Managed Service for YDB database from a Cloud Functions function in Node.js

Written by
Gayrat Vlasov
Improved by
Updated at May 7, 2025
  • Get your cloud ready
    • Required paid resources
  • Set up your environment
  • Create a service account
  • Create an authorized key
  • Create a YDB database
  • Create a function
  • Test the function
  • How to delete the resources you created

Note

This guide is intended for Linux users. On Windows, you can follow it in WSL.

You will create a function with a Node.js app that will run simple queries against a YDB database. You will deploy your app using Bash scripts and use the tcs command to compile it.

A function with an associated service account is authorized in YDB via the metadata service.

The application creates a YDB database connection driver, a session, and a transaction, and runs a query using the ydb library. This library is installed as a dependency when creating a function version. The DB connection parameters are passed to the application via environment variables.

To set up a connection to a YDB database:

  1. Get your cloud ready.
  2. Set up your environment.
  3. Create a service account.
  4. Create an authorized key.
  5. Create a YDB database.
  6. Create a function.
  7. Test the function.

If you no longer need the resources you created, delete them.

Get your cloud ready

Sign up in Yandex Cloud and create a billing account:

  1. Navigate to the management console and log in to Yandex Cloud or register a new account.
  2. On the Yandex Cloud Billing page, make sure you have a billing account linked and it has the ACTIVE or TRIAL_ACTIVE status. If you do not have a billing account, create one and link a cloud to it.

If you have an active billing account, you can navigate to the cloud page to create or select a folder for your infrastructure to operate in.

Learn more about clouds and folders.

Required paid resources

The infrastructure support cost for this scenario includes:

  • Fee for using the function (see Yandex Cloud Functions pricing).
  • Fee for running queries to the database (see Yandex Managed Service for YDB pricing).

Set up your environment

  1. Clone the repository using Git:

    git clone https://github.com/yandex-cloud-examples/yc-ydb-connect-from-serverless-function.git
    
  2. Install and initialize the Yandex Cloud CLI.

  3. Go to the project root directory:

    cd ~/yc-ydb-connect-from-serverless-function
    

    Make sure to run all further commands in this directory.

  4. Install the jq utility:

    sudo apt-get install jq
    
  5. Install Node.js:

    curl --fail --silent --show-error --location https://deb.nodesource.com/setup_current.x | sudo -E bash - \
    sudo apt-get install -y nodejs
    
  6. Install the dependencies:

    npm install
    

    Result:

    up to date, audited 269 packages in 1s
    
    29 packages are looking for funding
       run `npm fund` for details
    
    found 0 vulnerabilities
    

Create a service account

Management console
CLI
Terraform
API
  1. In the management console, select the folder where you want to create your service account.
  2. In the list of services, select Identity and Access Management.
  3. Click Create service account.
  4. Enter a name for the service account: sa-function.
  5. Click Add role and select editor.
  6. Click Create.
  1. Create a service account:

    yc iam service-account create --name sa-function
    

    Result:

    id: aje028do8n9r********
    folder_id: b1g681qpemb4********
    created_at: "2023-08-23T06:24:49.759304161Z"
    name: sa-function
    
  2. Assign the editor role to the service account:

    yc resource-manager folder add-access-binding <folder_ID> \
      --role editor \
      --subject serviceAccount:<service_account_ID>
    

    Result:

    ...1s...done (4s)
    effective_deltas:
    - action: ADD
       access_binding:
          role_id: viewer
          subject:
          id: aje028do8n9r********
          type: serviceAccount
    

For more information about the commands, see the CLI reference.

If you do not have Terraform yet, install it and configure its Yandex Cloud provider.

  1. In the configuration file, describe the service account parameters:

    resource "yandex_iam_service_account" "sa" {
      name = "sa-function"
    }
    

    For more information about the resources you can create with Terraform, see the relevant provider documentation.

  2. Make sure the configuration files are correct.

    1. In the command line, go to the directory where you created the configuration file.

    2. Run a check using this command:

      terraform plan
      

    If you described the configuration correctly, the terminal will display a list of the resources being created and their settings. If the configuration contains any errors, Terraform will point them out.

  3. Deploy the cloud resources.

    1. If the configuration does not contain any errors, run this command:

      terraform apply
      
    2. Confirm creating the resources: type yes in the terminal and press Enter.

To create a service account and assign it a role, use the create and setAccessBindings methods for the ServiceAccount resource.

Create an authorized key

Management console
CLI
Terraform
API
  1. In the management console, select the folder the service account belongs to.

  2. From the list of services, select Identity and Access Management.

  3. In the left-hand panel, select Service accounts.

  4. In the list that opens, select the sa-function service account.

  5. Click Create new key in the top panel.

  6. Select Create authorized key.

  7. Select the encryption algorithm.

  8. Enter a description for the authorized key so you can easily find it in the management console.

  9. Save both the public and private parts of the authorized key to the yc-ydb-connect-from-serverless-function/service_account_key_file.json file:

    {
      "service_account_id": "<sa-function_service_account_ID>",
      "key_algorithm": "RSA_2048",
      "public_key": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n",
      "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
    }
    

Run this command:

yc iam key create --service-account-name sa-function -o service_account_key_file.json

For more information about the yc iam key create command, see the CLI reference.

If successful, the private part of the authorized key (privateKey) and the ID of its public part (id) will be written to the service_account_key_file.json file.

  1. In the configuration file, describe the authorized key parameters:

    resource "yandex_iam_service_account_key" "sa-auth-key" {
      service_account_id = "<sa-function_service_account_ID>"
      key_algorithm      = "RSA_2048"
    }
    

    For more information about the resources you can create with Terraform, see the relevant provider documentation.

  2. Make sure the configuration files are correct.

    1. In the command line, go to the directory where you created the configuration file.

    2. Run a check using this command:

      terraform plan
      

    If you described the configuration correctly, the terminal will display a list of the resources being created and their settings. If the configuration contains any errors, Terraform will point them out.

  3. Deploy the cloud resources.

    1. If the configuration does not contain any errors, run this command:

      terraform apply
      
    2. Confirm creating the resources: type yes in the terminal and press Enter.

To create an authorized access key, use the create method for the Key resource.

Create a YDB database

Management console
  1. In the management console, select the folder where you want to create a database.

  2. From the list of services, select Managed Service for YDB.

  3. Click Create a database.

  4. Name the database. Follow these naming requirements:

    • It must be from 2 to 63 characters long.
    • It may contain lowercase Latin letters, numbers, and hyphens.
    • It must start with a letter and cannot end with a hyphen.
  5. Under Database type, select Serverless.

  6. Click Create a database.

    Wait for the DB to start. While being created, the database will have the Provisioning status. Once it is ready for use, its status will change to Running.

  7. Click the name of the database you created.

  8. Save the value of the Endpoint field from the Connection section. You will need it at the next step.

Create a function

Note

Before creating a function, make sure the .env file and the create-func.sh and create-func-ver.sh files from the deploy directory have the LF (line feed) character set.

  1. Go to the project root directory:

    cd ~/yc-ydb-connect-from-serverless-function
    
  2. Edit the .env file:

    • ENDPOINT: First part of the previously saved Endpoint field value (preceding /?database=), e.g., grpcs://ydb.serverless.yandexcloud.net:2135.
    • DATABASE: Second part of the previously saved Endpoint field value (following /?database=), e.g., /ru-central1/r1gra875baom********/g5n22e7ejfr1********.
    • FUNCTION_NAME: Function name, func-test-ydb.
    • FOLDER_ID: Folder ID.
    • SERVICE_ACCOUNT_ID: sa-function service account ID.
  3. Create a function:

    ./deploy/create-func.sh
    

    This script creates a new function in your folder and makes it public.

  4. Create a function version:

    ./deploy/create-func-ver.sh
    

    Result:

    npx tsc --build tsconfig.json
    rm: Cannot delete '../build/func.zip': File or folder does not exist.
    adding: queries/ (stored 0%)
    adding: queries/clients-table.js (deflated 57%)
    adding: queries/helpers.js.map (deflated 43%)
    adding: queries/helpers.js (deflated 48%)
    adding: queries/clients-table.js.map (deflated 59%)
    adding: index.js (deflated 49%)
    adding: index.js.map (deflated 56%)
    adding: database.js.map (deflated 62%)
    adding: index-local.js (deflated 42%)
    adding: package.json (deflated 55%)
    adding: database.js (deflated 60%)
    adding: index-local.js.map (deflated 43%)
    yc function version create func-test-ydb
    done (27s)
    id: abcd2d363b4b********
    function_id: efghm9el0ja9********
    created_at: "2023-08-15T07:41:07.591Z"
    runtime: nodejs16
    entrypoint: index.handler
    resources:
          memory: "268435456"
    execution_timeout: 5s
    service_account_id: hijk3hlu8gqe********
    image_size: "33497088"
    status: ACTIVE
    tags:
          - $latest
    log_group_id: lmnoivbe341g********
    environment:
          DATABASE: /ru-central1/b1gia87mbaom********/etnilt3o6v9e********
          ENDPOINT: grpcs://ydb.serverless.yandexcloud.net:2135
    log_options:
          folder_id: pqrs81qpemb********
    

Test the function

Management console
  1. In the management console, select the folder containing the function.

  2. From the list of services, select Cloud Functions.

  3. Select the func-test-ydb function.

  4. Navigate to the Overview tab.

  5. In the Link to invoke field, click the link.

  6. In your browser address bar, add the api_key parameter to the link, e.g., ?api_key=b95:

    https://functions.yandexcloud.net/efghm9el0ja9********?api_key=b95
    
  7. A successful DB connection will create a table named b95 with a single record added to it. A message in JSON format will appear on the page, e.g.:

    {
      "info": "b95 table created, one record inserted"
    }
    

How to delete the resources you created

To stop paying for the resources you created:

  1. Delete the DB.
  2. Delete the function.

Was the article helpful?

Previous
Connecting to a YDB database from a Python function
Next
Converting a video to a GIF in Python
Yandex project
© 2025 Yandex.Cloud LLC