Build applications with Neo4j and JavaScript

Installation

Install the Neo4j Javascript driver with npm:

npm i neo4j-driver

Connect to the database

Connect to a database by creating a Driver object and providing a URL and an authentication token. Once you have a Driver instance, use the .verifyConnectivity() method to ensure that a working connection can be established.

var neo4j = require('neo4j-driver');
(async () => {
  // URI examples: 'neo4j://localhost', 'neo4j+s://xxx.databases.neo4j.io'
  const URI = '<URI to Neo4j database>'
  const USER = '<Username>'
  const PASSWORD = '<Password>'
  let driver

  try {
    driver = neo4j.driver(URI,  neo4j.auth.basic(USER, PASSWORD))
    await driver.verifyConnectivity()
    console.log('Connection estabilished')
    console.log(serverInfo)
  } catch(err) {
    console.log(`Connection error\n${err}\nCause: ${err.cause}`)
  }
})();

Query the database

Execute a Cypher statement with the method Driver.executeQuery(). Do not hardcode or concatenate parameters: use placeholders and specify the parameters as keyword arguments.

// Get the name of all 42 year-olds
const { records, summary, keys } = await driver.executeQuery(
  'MATCH (p:Person {age: $age}) RETURN p.name AS name',
  { age: 42 },
  { database: 'neo4j' }
)

// Summary information
console.log(
  `>> The query ${summary.query.text} ` +
  `returned ${records.length} records ` +
  `in ${summary.resultAvailableAfter} ms.`
)

// Loop through results and do something with them
console.log('>> Results')
for(record of records) {
  console.log(record.get('name'))
}

Run your own transactions

For more advanced use-cases, you can take full control over the transaction lifecycle. A transaction is a unit of work that is either committed in its entirety or rolled back on failure. Use the methods Session.executeRead() and Session.executeWrite() to run managed transactions.

let session = driver.session({ database: 'neo4j' })
try {
  const { records, summary } = await session.executeRead(async tx => {
    return await tx.run(`
      MATCH (p:Person WHERE p.name STARTS WITH $filter)
      RETURN p.name AS name ORDER BY name
      `, { filter: 'Al'}
    )
  })
  console.log(
    `The query ${result.summary.query.text} returned ${result.records.length} nodes.`
  )
  for(let record of result.records) {
    console.log(`Person with name: ${record.get('name')}`)
    console.log(`Available properties for this node are: ${record.keys}\n`)
  }
} finally {
  await session.close()
}

Close connections and sessions

Call the .close() method on the Driver instance when you are finished with it, to release any resources still held by it. The same applies to any open sessions.

session.close()
driver.close()

Glossary

LTS

A Long Term Support release is one guaranteed to be supported for a number of years. Neo4j 4.4 is LTS, and Neo4j 5 will also have an LTS version.

Aura

Aura is Neo4j’s fully managed cloud service. It comes with both free and paid plans. Every Neo4j-backed application requires a Driver object.

Cypher

Cypher is Neo4j’s graph query language that lets you retrieve data from the graph. It is like SQL, but for graphs.

APOC

Awesome Procedures On Cypher (APOC) is a library of (many) functions that can not be easily expressed in Cypher itself.

Bolt

Bolt is the protocol used for interaction between Neo4j instances and drivers. It listens on port 7687 by default.

ACID

Atomicity, Consistency, Isolation, Durability (ACID) are properties guaranteeing that database transactions are processed reliably. An ACID-compliant DBMS ensures that the data in the database remains accurate and consistent despite failures.

eventual consistency

A database is eventually consistent if it provides the guarantee that all cluster members will, at some point in time, store the latest version of the data.

causal consistency

A database is causally consistent if read and write queries are seen by every member of the cluster in the same order. This is stronger than eventual consistency.

null

The null marker is not a type but a placeholder for absence of value. For more information, see Cypher Manual — Working with null.

transaction

A transaction is a unit of work that is either committed in its entirety or rolled back on failure. An example is a bank transfer: it involves multiple steps, but they must all succeed or be reverted, to avoid money being subtracted from one account but not added to the other.

backpressure

Backpressure is a force opposing the flow of data. It ensures that the client is not being overwhelmed by data faster than it can handle.

transaction function

A transaction function is a callback executed by an executeRead or executeWrite call. The driver automatically re-executes the callback in case of server failure.

Driver

A Driver object holds the details required to establish connections with a Neo4j database.