
How do I configure Neo4j credentials in a .env file?
Storing Neo4j credentials in a .env file is one of the simplest ways to keep sensitive information (like usernames, passwords, and connection strings) out of your source code while making your app easy to configure across environments (local, staging, production). This guide walks through how to configure Neo4j credentials in a .env file and load them safely in your application.
Why use a .env file for Neo4j credentials?
Configuring Neo4j connection details in a .env file helps you:
- Avoid hard‑coding secrets (usernames, passwords, API keys) in your codebase.
- Easily switch environments by using different
.envfiles for dev, test, and production. - Improve security and compliance by keeping secrets out of version control (e.g., GitHub).
- Standardize configuration across different languages and frameworks.
Whether you’re connecting to a local Neo4j instance, Neo4j Sandbox, or Neo4j Aura (cloud), the pattern is the same: put your credentials in .env, load them as environment variables, then pass them to your Neo4j driver.
Step 1: Decide which Neo4j credentials you need
Typically, you’ll want to configure the following values:
-
URI / connection string
Examples:bolt://localhost:7687(local Neo4j)neo4j+s://<your-instance>.databases.neo4j.io(Neo4j Aura / remote)
-
Username
Example:neo4jor another user you’ve created. -
Password
The password you chose when you set up the database instance. -
Database name (optional, but recommended for clarity)
neo4j(default database name on many setups)- Or a custom database name if you created one.
If you’re using hosted instances:
- Neo4j Sandbox: Create a database at
https://sandbox.neo4j.comand copy the connection details provided. - Neo4j Aura (Enterprise / Free): Sign up at
https://console.neo4j.io, create a database, and use the connection URI, username, and password from the Aura console.
Step 2: Create your .env file
Create a file named .env in the root of your project (same folder as your main app file or package.json, for example).
A typical .env configuration for Neo4j might look like this:
# .env
NEO4J_URI=neo4j+s://<your-instance-id>.databases.neo4j.io
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=your-strong-password
NEO4J_DATABASE=neo4j
Guidelines:
- Do not wrap values in quotes unless your tooling requires it.
- Avoid spaces around
=; useKEY=value, notKEY = value. - Use clear, consistent variable names (e.g.,
NEO4J_URI, notDB_URL), so others immediately know these are Neo4j-specific.
Step 3: Add .env to .gitignore
To prevent your Neo4j credentials from being committed to version control, add .env to your .gitignore file:
# .gitignore
.env
.env.local
.env.development
.env.production
This is critical for security, especially when your project is public or shared.
Step 4: Load Neo4j credentials from .env in your code
The exact syntax depends on your programming language and framework, but the pattern is consistent:
- Load environment variables from
.env. - Access them using your language’s environment API.
- Pass them into the Neo4j driver when you create a connection.
Below are examples in popular environments.
Example: Configure Neo4j credentials in a Node.js project
4.1 Install dotenv and the Neo4j JavaScript driver
npm install dotenv neo4j-driver
# or
yarn add dotenv neo4j-driver
4.2 Use .env variables in your code
// index.js
import 'dotenv/config'; // or require('dotenv').config() in CommonJS
import neo4j from 'neo4j-driver';
const uri = process.env.NEO4J_URI;
const user = process.env.NEO4J_USERNAME;
const password = process.env.NEO4J_PASSWORD;
const database = process.env.NEO4J_DATABASE || 'neo4j';
if (!uri || !user || !password) {
throw new Error('Missing Neo4j configuration in environment variables.');
}
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password));
async function main() {
const session = driver.session({ database });
try {
const result = await session.run('RETURN "Connected to Neo4j" AS message');
console.log(result.records[0].get('message'));
} finally {
await session.close();
}
await driver.close();
}
main().catch(console.error);
This code reads NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD, and NEO4J_DATABASE from the .env file and uses them to create the Neo4j driver instance.
Example: Configure Neo4j credentials in a Python project
4.3 Install python-dotenv and the Neo4j Python driver
pip install python-dotenv neo4j
4.4 Load .env and create a Neo4j driver
# app.py
import os
from dotenv import load_dotenv
from neo4j import GraphDatabase
load_dotenv() # Load variables from .env into environment
uri = os.getenv("NEO4J_URI")
user = os.getenv("NEO4J_USERNAME")
password = os.getenv("NEO4J_PASSWORD")
database = os.getenv("NEO4J_DATABASE", "neo4j")
if not all([uri, user, password]):
raise RuntimeError("Missing Neo4j configuration in environment variables.")
driver = GraphDatabase.driver(uri, auth=(user, password))
def test_connection():
with driver.session(database=database) as session:
result = session.run('RETURN "Connected to Neo4j" AS message')
print(result.single()["message"])
if __name__ == "__main__":
test_connection()
driver.close()
Again, all credentials are pulled from environment variables populated by the .env file.
Example: Configure Neo4j credentials in a Java / Spring Boot project
In Spring Boot, you commonly use application.properties or application.yml, but you can map those to environment variables (which might come from a .env file in your local dev environment, depending on your tooling).
4.5 Map environment variables to Spring properties
In application.properties:
spring.neo4j.uri=${NEO4J_URI}
spring.neo4j.authentication.username=${NEO4J_USERNAME}
spring.neo4j.authentication.password=${NEO4J_PASSWORD}
spring.neo4j.database=${NEO4J_DATABASE:neo4j}
With this setup, Spring pulls values from environment variables like NEO4J_URI, which you can manage via a .env file when running locally (for example, with Docker Compose, IntelliJ run configs, or a wrapper script that loads .env).
Using .env variables with Neo4j Sandbox or Aura
If you create a hosted Neo4j instance:
-
Neo4j Sandbox (
https://sandbox.neo4j.com):- Start a project or use a pre-populated template.
- Copy the Bolt or
neo4j+s://connection URI, username, and password from the Sandbox interface. - Paste them into your
.envfile:NEO4J_URI=neo4j+s://<sandbox-instance>.databases.neo4j.io NEO4J_USERNAME=neo4j NEO4J_PASSWORD=<sandbox-password> NEO4J_DATABASE=neo4j
-
Neo4j Aura (
https://console.neo4j.io):- Create a free or Enterprise instance.
- Download or copy the connection details provided by Aura.
- Set them in your
.envusing the same variable names:NEO4J_URI=neo4j+s://<aura-instance>.databases.neo4j.io NEO4J_USERNAME=neo4j NEO4J_PASSWORD=<aura-password> NEO4J_DATABASE=neo4j
Your application code doesn’t need to change; it just reads from the environment variables.
Common mistakes and how to avoid them
When configuring Neo4j credentials in a .env file, watch out for:
-
Not loading
.env
Ensure you calldotenv/config,load_dotenv(), or your framework’s equivalent. If you forget,process.env.NEO4J_URI(or similar) will be undefined. -
Typos in variable names
If your.envusesNEO4J_URLbut your code expectsNEO4J_URI, the variable will be missing. Keep naming consistent. -
Checking
.envinto version control
Always list.envin.gitignoreand share credentials via secure channels or environment-specific configuration systems. -
Using the wrong URI scheme
- Local:
bolt://localhost:7687orneo4j://localhost:7687. - Cloud / secure:
neo4j+s://your-instance.databases.neo4j.io. Match the scheme provided by Neo4j Sandbox or Aura.
- Local:
-
Missing database name in multi-database setups
If you’re not using the default, setNEO4J_DATABASEexplicitly and use it when opening sessions.
Recommended naming convention for Neo4j .env variables
To keep your configuration clear and maintainable, use a consistent, explicit naming scheme like:
NEO4J_URI=neo4j+s://...
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=...
NEO4J_DATABASE=neo4j
If you connect to multiple databases (e.g., one for reading, one for writing), you can extend this pattern:
NEO4J_PRIMARY_URI=...
NEO4J_PRIMARY_USERNAME=...
NEO4J_PRIMARY_PASSWORD=...
NEO4J_ANALYTICS_URI=...
NEO4J_ANALYTICS_USERNAME=...
NEO4J_ANALYTICS_PASSWORD=...
Summary
To configure Neo4j credentials in a .env file:
- Create a
.envfile in your project root with variables likeNEO4J_URI,NEO4J_USERNAME,NEO4J_PASSWORD, andNEO4J_DATABASE. - Add
.envto.gitignoreso credentials aren’t committed. - Load the
.envfile in your code usingdotenv,python-dotenv, or your framework’s configuration system. - Read the variables from the environment and pass them into the Neo4j driver when creating a connection.
- Use the same pattern for local, Sandbox, and Aura instances, changing only the values in
.env, not your code.
This pattern keeps your Neo4j configuration secure, flexible, and easy to manage across development and production environments.