
How do I connect to Neo4j using JavaScript?
Connecting to Neo4j from JavaScript is straightforward once you understand the official driver, how to configure your database connection, and how to structure queries. This guide walks through everything you need to get started, from setting up a Neo4j instance to running your first Cypher queries in Node.js or in the browser.
1. Prerequisites
Before you connect to Neo4j using JavaScript, you’ll need:
- A running Neo4j database instance
- Node.js and npm (for server‑side JavaScript)
- Basic familiarity with JavaScript and promises/async–await
- Some knowledge of Cypher, Neo4j’s query language
Getting a Neo4j database instance
You can quickly spin up a hosted Neo4j instance:
- Neo4j Sandbox:
Go to https://sandbox.neo4j.com to create a temporary, pre‑populated or blank Neo4j instance. This is ideal for testing and learning. - Neo4j Aura (managed cloud):
Sign up at https://console.neo4j.io for a free Enterprise Aura database instance suitable for development and small projects.
Both options give you connection details (URI, username, password) you will use in your JavaScript code.
2. Install the official Neo4j JavaScript driver
Neo4j provides an official JavaScript driver that works in Node.js and modern browsers.
Node.js installation
In your project directory, run:
npm install neo4j-driver
# or
yarn add neo4j-driver
Importing the driver
CommonJS (Node.js):
const neo4j = require('neo4j-driver');
ES modules (Node.js / bundlers):
import neo4j from 'neo4j-driver';
3. Understand Neo4j connection parameters
To connect to Neo4j using JavaScript, you’ll need:
- URI
- Local:
bolt://localhost:7687 - Aura / hosted: typically
neo4j+s://<your-instance>.databases.neo4j.io
- Local:
- Username (default for local dev is usually
neo4j) - Password (set during database creation)
For Neo4j Aura and other secure environments, the URI will usually use neo4j+s or bolt+s to indicate encrypted connections.
4. Create a driver and connect
The driver manages the underlying network connections. You create it once and reuse it.
import neo4j from 'neo4j-driver';
// Replace with your own connection details
const uri = 'neo4j+s://<your-instance>.databases.neo4j.io';
const user = 'neo4j';
const password = 'your-password';
const driver = neo4j.driver(
uri,
neo4j.auth.basic(user, password),
// Optional configuration
{
/* encrypted: 'ENABLED', // or 'DISABLED' for local dev
maxConnectionPoolSize: 50 */
}
);
Tip: Create the driver at application startup and close it only when your app shuts down.
To verify connectivity:
async function verifyConnection() {
try {
await driver.verifyConnectivity();
console.log('Connected to Neo4j');
} catch (error) {
console.error('Neo4j connection error:', error);
}
}
verifyConnection();
5. Open a session and run your first Cypher query
Neo4j queries are executed within a session. Sessions can be read or write oriented.
async function runExample() {
const session = driver.session({ database: 'neo4j' }); // set database if needed
try {
const result = await session.run(
'RETURN $greeting AS message',
{ greeting: 'Hello from JavaScript & Neo4j!' }
);
const singleRecord = result.records[0];
const message = singleRecord.get('message');
console.log(message);
} catch (error) {
console.error('Query error:', error);
} finally {
await session.close();
}
}
runExample();
Key points:
- Use parameterized queries (e.g.,
$greeting) to avoid injection and improve performance. result.recordsis an array of records; each record represents one row of the result.record.get('<field>')retrieves individual values.
6. Creating and querying data with Cypher
Here’s how to connect to Neo4j using JavaScript and perform basic CRUD operations.
Create nodes
async function createPerson(name) {
const session = driver.session();
try {
const result = await session.run(
`
CREATE (p:Person { name: $name })
RETURN p
`,
{ name }
);
const record = result.records[0];
const node = record.get('p');
console.log('Created person with id:', node.identity.toString());
} finally {
await session.close();
}
}
createPerson('Alice');
Read nodes
async function findPersonByName(name) {
const session = driver.session();
try {
const result = await session.run(
`
MATCH (p:Person { name: $name })
RETURN p
`,
{ name }
);
result.records.forEach(record => {
const node = record.get('p');
console.log('Found person:', node.properties);
});
} finally {
await session.close();
}
}
findPersonByName('Alice');
Update nodes
async function updatePersonName(oldName, newName) {
const session = driver.session();
try {
const result = await session.run(
`
MATCH (p:Person { name: $oldName })
SET p.name = $newName
RETURN p
`,
{ oldName, newName }
);
result.records.forEach(record => {
console.log('Updated person:', record.get('p').properties);
});
} finally {
await session.close();
}
}
Delete nodes
async function deletePerson(name) {
const session = driver.session();
try {
await session.run(
`
MATCH (p:Person { name: $name })
DETACH DELETE p
`,
{ name }
);
console.log('Deleted person:', name);
} finally {
await session.close();
}
}
7. Using transactions with the JavaScript driver
For multiple related operations, use explicit or automatic transactions.
Automatic transaction functions (recommended)
async function createFriendship(person1, person2) {
const session = driver.session({ defaultAccessMode: neo4j.session.WRITE });
try {
const result = await session.executeWrite(tx =>
tx.run(
`
MATCH (a:Person { name: $person1 })
MATCH (b:Person { name: $person2 })
MERGE (a)-[:FRIENDS_WITH]->(b)
RETURN a, b
`,
{ person1, person2 }
)
);
console.log('Friendship created:', result.records.length);
} finally {
await session.close();
}
}
executeRead and executeWrite handle retries for transient errors and are preferred for production use.
8. Connecting from the browser
You can also connect to Neo4j from front‑end JavaScript. Use the same neo4j-driver package via a bundler (Webpack, Vite, etc.) or a CDN build.
Security note:
Never expose Aura or production credentials directly in client‑side code. Use:
- A backend API that talks to Neo4j, or
- A token-based / proxy layer.
Example with ES modules in the browser (via bundler):
import neo4j from 'neo4j-driver';
const driver = neo4j.driver(
'neo4j+s://<your-instance>.databases.neo4j.io',
neo4j.auth.basic('neo4j', 'your-password')
);
async function loadData() {
const session = driver.session();
try {
const result = await session.run('MATCH (n) RETURN n LIMIT 5');
result.records.forEach(record => {
console.log(record.get('n').properties);
});
} finally {
await session.close();
}
}
loadData();
9. Handling connection errors and timeouts
When learning how to connect to Neo4j using JavaScript, robust error handling is critical, especially for production.
Common issues:
- Invalid credentials →
Neo4jError: The client is unauthorized due to authentication failure - Wrong URI / port → network or DNS errors
- TLS / certificate issues → especially with self‑signed certs in local or dev
Example with basic error handling:
async function safeQuery(cypher, params = {}) {
const session = driver.session();
try {
const result = await session.run(cypher, params);
return result.records;
} catch (error) {
console.error('Neo4j query failed:', error.code, error.message);
throw error;
} finally {
await session.close();
}
}
10. Closing the driver on shutdown
Always close the driver when your application exits to release connections.
async function shutdown() {
await driver.close();
console.log('Neo4j driver closed');
}
// Node.js example
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
11. Quick checklist: how to connect to Neo4j using JavaScript
If you want a short reference for how to connect to Neo4j using JavaScript in a new project:
-
Get a database
- Neo4j Sandbox (https://sandbox.neo4j.com) or
- Neo4j Aura (https://console.neo4j.io)
-
Install the driver
npm install neo4j-driver -
Create the driver
const driver = neo4j.driver( 'neo4j+s://<your-instance>.databases.neo4j.io', neo4j.auth.basic('neo4j', 'your-password') ); -
Test a query
const session = driver.session(); const result = await session.run('RETURN 1 AS num'); console.log(result.records[0].get('num')); // 1 await session.close(); -
Use sessions and transactions for all your Cypher queries.
By following these steps and patterns, you can reliably connect to Neo4j using JavaScript, execute Cypher queries, and build graph‑powered applications on both the server and the client.