Client applications

This section describes how to manage database connections within an application.

The Driver Object

Neo4j client applications require a Driver Object which, from a data access perspective, forms the backbone of the application. It is through this object that all Neo4j interaction is carried out, and it should therefore be made available to all parts of the application that require data access.

In languages where thread safety is an issue, the Driver Object can be considered thread-safe.

A note on lifecycle

Applications will typically construct a Driver Object on startup and destroy it on exit.

Destroying a Driver Object will immediately shut down any connections previously opened via that Driver Object, by closing the associated connection pool.

This will have the consequence of rolling back any open transactions, and closing any unconsumed results.

To construct a driver instance, a connection URI and authentication information must be supplied.

Additional configuration details can be supplied if required. The configuration details are immutable for the lifetime of the Driver Object. Therefore, if multiple configurations are required (such as when working with multiple database users) then multiple Driver Objects must be used.

Example 1. The driver lifecycle
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))

try {
  await driver.verifyConnectivity()
  console.log('Driver created')
} catch (error) {
  console.log(`connectivity verification failed. ${error}`)

const session = driver.session()
try {
  await'CREATE (i:Item)')
} catch (error) {
  console.log(`unable to execute query. ${error}`)
} finally {
  await session.close()

// ... on application exit:
await driver.close()

Connection URIs

A connection URI identifies a graph database and how to connect to it.

The encryption and trust settings provide detail to how that connection should be secured.

Starting with Neo4j 4.0, client-server communication uses only unencrypted local connections by default. This is a change from previous versions, which switched on encryption by default, but generated a self-signed certificate out of the box.

When a full certificate is installed, and encryption is enabled on the driver, full certificate checks are carried out (refer to Operations Manual → SSL framework). Full certificates provide better overall security than self-signed certificates as they include a complete chain of trust back to a root certificate authority.

Neo4j Aura is a secure hosted service backed by full certificates signed by a root certificate authority.

To connect to Neo4j Aura, driver users must enable encryption and the complete set of certificate checks (the latter of which are enabled by default).

For more information, see Examples below.

Initial address resolution

The address provided in a neo4j:// URI is used for initial and fallback communication only.

This communication occurs to bootstrap the routing table, through which all subsequent communication is carried out. Fallback occurs when the driver is unable to contact any of the addresses held in the routing table. The initial address is once again reused to bootstrap the system.

Several options are available for providing this initial logical-to-physical host resolution. These include regular DNS, custom middleware such as a load balancer, and the Driver Object resolver function, all of which are described in the following sections.

DNS resolution

DNS resolution is the default, and always-available option. As it is possible to configure DNS to resolve a single host name down to multiple IP addresses, this can be used to expose all core server IP addresses under a single host name.

dns resolution
Figure 1. Initial address resolution over DNS

Custom middleware

Middleware, such as a load balancer, can be used to group the core servers under a single public address.

custom middleware
Figure 2. Initial address resolution using custom middleware

Resolver function

Neo4j Drivers also present an address resolution intercept hook called the resolver function.

This takes the form of a callback function that accepts a single input address and returns multiple output addresses. The function may hard code the output addresses or may draw them from another configuration source, as required.

resolver function
Figure 3. Initial address resolution using resolver function

The example below shows how to expand a single address into multiple (hard-coded) output addresses:

Example 2. Custom Address Resolver
function createDriver (virtualUri, user, password, addresses) {
  return neo4j.driver(virtualUri, neo4j.auth.basic(user, password), {
    resolver: address => addresses

function addPerson (name) {
  const driver = createDriver('neo4j://', user, password, [
  const session = driver.session({ defaultAccessMode: neo4j.WRITE })

    .run('CREATE (n:Person { name: $name })', { name: name })
    .then(() => session.close())
    .then(() => driver.close())

Routing table

The routing table acts like the glue between the driver connectivity layer and the database surface. This table contains a list of server addresses, grouped as readers and writers, and is refreshed automatically by the driver as required.

The driver does not expose any API to work directly with the routing table, but it can sometimes be useful to explore when troubleshooting a system.

Routing context

A routing context can be included as the query part of a neo4j:// URI.

Routing contexts are defined by means of server policies and allow customization of the contents of the routing table.

Example 3. Configure a routing driver with routing context

This example will assume that Neo4j has been configured for server policies as described in Neo4j Operations Manual → Load balancing for multi-data center systems. In particular, a server policy called europe has been defined. Additionally, we have a server to which we wish to direct the driver.

This URI will use the server policy europe:


Server-side configuration to enable routing drivers with routing context

A prerequisite for using a routing driver with routing context is that the Neo4j database is operated on a Causal Cluster with the Multi-data center licensing option enabled. Additionally, the routing contexts must be defined within the cluster as routing policies.

For details on how to configure multi-data center routing policies for a Causal Cluster, please refer to Operations Manual → Causal Clustering.

Exposing a single instance deployment on a remote host using the neo4j URI scheme

If you are using a single instance of Neo4j, deployed on a remote machine whilst using the neo4j URI scheme, you will need to complete additional configuration of the server.

To make the server aware of its deployment environment, you need to configure default_advertised_address with your deployment machine’s host name, as visible from the client machine.


Connection URIs are typically formed according to the following pattern:


This targets a routed Neo4j service that may be fulfilled by either a cluster or a single instance. The HOST and PORT values contain a logical hostname and port number targeting the entry point to the Neo4j service (e.g. neo4j://

In a clustered environment, the URI address will resolve to one of more of the core members; for standalone installations, this will simply point to that server address. The ROUTING_CONTEXT option allows for customization of the routing table and is discussed in more detail in Routing context.

An alternative URI form, using the bolt URI scheme (e.g. bolt://, can be used when a single point-to-point connection is required. This variant is useful for the subset client applications (such as admin tooling) that need to be aware of individual servers, as opposed to those which require a highly available database service.


Each of the neo4j and bolt URI schemes permit variants that contain extra encryption and trust information. The +s variants enable encryption with a full certificate check, and the +ssc variants enable encryption, but with no certificate check. This latter variant is designed specifically for use with self-signed certificates.

Table 1. Available URI schemes
URI scheme Routing Description






Secured with full certificate



Secured with self-signed certificate






Secured with full certificate



Secured with self-signed certificate

Neo4j 3.x did not provide a routing table in single instance mode and therefore you should use a bolt:// URI if targeting an older, non-clustered server.

The table below provides example code snippets for different deployment configurations. Each snippet expects an auth variable to have been previously defined, containing the authentication details for that connection.

Connecting to a service

The tables below illustrate examples of how to connect to a service with routing:

Table 2. Neo4j Aura or Neo4j >= 4.x, secured with full certificate


Neo4j Aura, Neo4j >= 4.x


Secured with full certificate

Code snippet

neo4j.driver("neo4j+s://", auth)


This is the default (and only option) for Neo4j Aura.

Table 3. Neo4j >= 4.x, unsecured


Neo4j >= 4.x



Code snippet

neo4j.driver("neo4j://", auth)


This is the default for Neo4j >= 4.x series

Table 4. Neo4j >= 4.x, secured with self-signed certificate


Neo4j >= 4.x


Secured with self-signed certificate

Code snippet

neo4j.driver("neo4j+ssc://", auth)
To connect to a service without routing, you can replace neo4j with bolt.


Authentication details are provided as an auth token which contains the user names, passwords or other credentials required to access the database. Neo4j supports multiple authentication standards but uses basic authentication by default.

Basic authentication

The basic authentication scheme is backed by a password file stored within the server and requires applications to provide a user name and password. For this, use the basic auth helper:

Example 4. Basic authentication
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))

The basic authentication scheme can also be used to authenticate against an LDAP server.

Kerberos authentication

The Kerberos authentication scheme provides a simple way to create a Kerberos authentication token with a base64 encoded server authentication ticket. The best way to create a Kerberos authentication token is shown below:

Example 5. Kerberos authentication
const driver = neo4j.driver(uri, neo4j.auth.kerberos(ticket))

The Kerberos authentication token can only be understood by the server if the server has the Kerberos Add-on installed.

Custom authentication

For advanced deployments, where a custom security provider has been built, the custom authentication helper can be used.

Example 6. Custom authentication
const driver = neo4j.driver(
  neo4j.auth.custom(principal, credentials, realm, scheme, parameters)



The maximum amount of time a session will wait when requesting a connection from the connection pool. For connection pools where all connections are currently being used and the MaxConnectionPoolSize limit has been reached, a session will wait this duration for a connection to be made available. Since the process of acquiring a connection may involve creating a new connection, ensure that the value of this configuration is higher than the configured ConnectionTimeout.

Setting a low value will allow for transactions to fail fast when all connections in the pool have been acquired by other transactions. Setting a higher value will result in these transactions being queued, increasing the chances of eventually acquiring a connection at the cost of longer time to receive feedback on failure. Finding an optimal value may require an element of experimentation, taking into consideration the expected levels of parallelism within your application as well as the MaxConnectionPoolSize.

Default: 60 seconds

Example 7. Configure connection pool
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password), {
  maxConnectionLifetime: 3 * 60 * 60 * 1000, // 3 hours
  maxConnectionPoolSize: 50,
  connectionAcquisitionTimeout: 2 * 60 * 1000 // 120 seconds

The maximum amount of time to wait for a TCP connection to be established. Connections are only created when a session requires one unless there is an available connection in the connection pool. The driver maintains a pool of open connections which can be loaned to a session when one is available. If a connection is not available, then an attempt to create a new connection (provided the MaxConnectionPoolSize limit has not been reached) is made with this configuration option, providing the maximum amount of time to wait for the connection to be established.

In environments with high latency and high occurrences of connection timeouts it is recommended to configure a higher value. For lower latency environments and quicker feedback on potential network issues configure with a lower value.

Default: 30 seconds

Example 8. Configure connection timeout
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password), {
  connectionTimeout: 20 * 1000 // 20 seconds

Specify a custom server address resolver used by the routing driver to resolve the initial address used to create the driver. See Resolver function for more details.


Specify whether to use an encrypted connection between the driver and server.

Default: False

Example 9. Unencrypted configuration
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password), {
  encrypted: 'ENCRYPTION_OFF'

The maximum duration the driver will keep a connection for before being removed from the pool. Note that while the driver will respect this value, it is possible that the network environment will close connections inside this lifetime. This is beyond the control of the driver. The check on the connection’s lifetime happens when a session requires a connection. If the available connection’s lifetime is over this limit it is closed and a new connection is created, added to the pool and returned to the requesting session. Changing this configuration value would be useful in environments where users don’t have full control over the network environment and wish to proactively ensure all connections are ready.

Setting this option to a low value will cause a high connection churn rate, and can result in a performance drop. It is recommended to pick a value smaller than the maximum lifetime exposed by the surrounding system infrastructure (such as operating system, router, load balancer, proxy and firewall). Negative values result in lifetime not being checked.

Default: 1 hour (3600 seconds)


The maximum total number of connections allowed, per host (i.e. cluster nodes), to be managed by the connection pool. In other words, for a direct driver using the bolt:// scheme, this sets the maximum number of connections towards a single database server. For a driver connected to a cluster using the neo4j:// scheme, this sets the maximum amount of connections per cluster member. If a session or transaction tries to acquire a connection at a time when the pool size is at its full capacity, it must wait until a free connection is available in the pool or the request to acquire a new connection times out. The connection acquiring timeout is configured via ConnectionAcquisitionTimeout.

This configuration option allows you to manage the memory and I/O resources being used by the driver and tuning this option is dependent on these factors, in addition to number of cluster members.

Default: 100 connections


The maximum amount of time that a managed transaction will retry for before failing. Queries that are executed within a managed transaction gain the benefit of being retried when a transient error occurs. When this happens the transaction is retired multiple times up to the MaxTransactionRetryTime.

Configure this option higher in high latency environments or if you are executing many large transactions which could limit the number of times that they are retired and therefore their chance to succeed. Configure lower in low latency environments and where your workload mainly consists of many smaller transactions. Failing transactions faster may highlight the reasons behind the transient errors making it easier to fix underlying issues.

Default: 30 seconds

Example 10. Configure maximum retry time
const maxRetryTimeMs = 15 * 1000 // 15 seconds
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password), {
  maxTransactionRetryTime: maxRetryTimeMs

Specify how to determine the authenticity of encryption certificates provided by the Neo4j instance that you are connecting to. If encryption is disabled, this option has no effect.

Possible values are:

  • TRUST_SYSTEM_CA_SIGNED_CERTIFICATES - [Default] Accept any certificate that can be verified against the system store.

  • TRUST_CUSTOM_CA_SIGNED_CERTIFICATES - Accept certificates at specified paths. Paths are specified as a list to the extra config parameter trustedCertificates.

  • TRUST_ALL_CERTIFICATES - Accept any certificate, including self-signed ones. Not recommended for production environments.

Example 11. Configure trusted certificates
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password), {
  encrypted: 'ENCRYPTION_ON',


All official Neo4j Drivers log information to standard logging channels. This can typically be accessed in an ecosystem-specific way.

The code snippet below demonstrates how to redirect log messages to standard output:

const loggingConfig = {logging: neo4j.logging.console('debug')};
const driver = neo4j.driver(..., loggingConfig);