In JavaScript, connecting to databases typically happens on the server side using Node.js. Browsers do not directly connect to databases for security reasons. Instead, server-side code handles the database connection and queries.

💡 Key Concept
Node.js allows you to interact with databases using specific drivers or libraries tailored to each database type (e.g., MySQL, MongoDB, PostgreSQL).
Common Database Drivers & Libraries for Node.js
| Database Type | Popular Node.js Client Library |
|---|---|
| MySQL | mysql2, knex |
| PostgreSQL | pg, sequelize |
| MongoDB | mongodb, mongoose |
| SQLite | sqlite3 |
Basic Steps to Connect to a Database
- Install the appropriate Node.js database client via npm.
- Import or require the client in your JavaScript file.
- Configure the connection with credentials and database info.
- Establish the connection (usually asynchronous).
- Perform queries or operations.
- Close the connection when done.
Example: Connecting to a MySQL Database
This example uses the mysql2 library to connect and query.
📌 Deep Dive: MySQL Connection with mysql2
const mysql = require('mysql2/promise');
async function connect() {
const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'your_password',
database: 'test_db'
});
const [rows] = await connection.execute('SELECT * FROM users');
console.log(rows);
await connection.end();
}
connect().catch(console.error);
💡 Async/Await
Database operations are asynchronous; use async/await or promises to handle them properly.
Example: Connecting to MongoDB
Using the official mongodb Node.js driver to connect:
📌 Deep Dive: MongoDB Connection
const { MongoClient } = require('mongodb');
async function connect() {
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
await client.connect();
const database = client.db('test_db');
const collection = database.collection('users');
const users = await collection.find({}).toArray();
console.log(users);
await client.close();
}
connect().catch(console.error);
⚠️ Security Warning
Never commit database credentials (usernames, passwords) directly in your source code. Use environment variables or secure config files.
Summary
- Use Node.js database clients to connect and interact with databases.
- Connections are asynchronous; handle them with async/await or promises.
- Each database has specific libraries and connection methods.
- Always secure your credentials outside of your codebase.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Where does JavaScript typically connect to databases?
Question 2 of 2
Which Node.js library is commonly used to connect to MongoDB?
Loading results...