Introduction
Express.js is a beginner-friendly framework for building web applications with Node.js, while CockroachDB PostgreSQL offers a reliable and flexible database solution. Sequelize makes it easy to work with databases in Node.js without diving too deep into SQL.
By the end of this tutorial, you'll have the skills to connect your Express app to a CockroachDB PostgreSQL database using Sequelize. Let's dive right in!
Lets create our Express App.
First we create a directory or folder for our app using the commands below in our bash terminals:
$ mkdir connectcockroachdb
$ cd connectcockroachdb
Use the npm init command to create a package.json file for your application.
$ npm init
This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:
entry point: (index.js)
Enter app.js, or whatever you want the name of the main file to be. If you want to keep it as index.js
, hit ↵ Enter
to accept the suggested default file name.
Now install Express in the connectcockroachdb directory and save it in the dependencies list.
$ npm install express
Let's create our express server
In our (index.js)
file we'll add the following code snippet:
const express = require('express');
const app = express();
const port = 4000;
app.use(express.json());
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`
Server running at http://localhost:${port}...
`))
Now let's start our Express Server with the command below;
$ node index.js
We should get an output like this below if our development server starts up successfully.
$ Server running at http://localhost:4000 ...
Now let's install some few packages we'll need to communicate with CockroachDB PostgreSQL database.
$ npm install sequelize-cockroachdb
Now in the root of our application file let's create a file called /dbconnection.js
.
I am assuming you've already set up your Cockroachlabs account and created your PostgreSQL cluster, if not, you can quickly do so by following the steps outlined in the Cockroachlabs documentation at https://www.cockroachlabs.com/docs/. It's straightforward and simple, I assure you!
Let's write the code for our database connection in our /dbConnection.js file
.
First let's copy our database link from our cockroach labs cluster and store it in a variable. You can get this link by clicking on the connect button in the top right corner of your cluster dashboard on Cockroach labs.
const {Sequelize} = require('sequelize-cockroachdb');
const dbConnection = async () => {
const dbLink = "your link from your cluster on cockroachlabs"
const sequelize = new Sequelize(dbLink,
{
dialect: 'postgres',
protocol: 'postgres',
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false
}
}
}) ;
await sequelize.authenticate().then(() => {
console.log('Connection has been established successfully.');
}).catch(err => {
console.error('Unable to connect to the database:', err);
});
}
module.exports = dbConnection;
Now in our index.js
file let us import our dbConnection module from our dbconnection.js
file.
const express = require('express');
const app = express();
const port = 4000;
//importing dbConnection module
const dbConnection = require('/dbConnection');
//Initiating a connection by calling our connection function.
dbConnection();
app.use(express.json());
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`
Server running at http://localhost:${port}...
`))
Now let's start our Express server again with the command below;
$ node index.js
On a successful connection to our database we should get an output like this:
Executing (default): SELECT version() AS version
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
Executing (default): SELECT crdb_internal.increment_feature_counter(concat('Sequelize ', '6.33'))
Executing (default): SELECT crdb_internal.increment_feature_counter(concat('sequelize-cockroachdb ', '6.0.5'))
And with that we have been able to successfully connect to our CockroachDb database.
Well done for following through. Please leave your comments and questions in the comments. Thank you !!
Top comments (0)