A Guide to Connecting to PostgreSQL with Supabase and Sequelize ORM

A Guide to Connecting to PostgreSQL with Supabase and Sequelize ORM

Β·

7 min read

Overview

  1. Supabase: πŸš€

    • Overview: Open-source platform for building applications with real-time database, authentication, and storage.

    • Features: Real-time updates, authentication, scalable storage, REST and GraphQL APIs.

    • Use Case: Ideal for web and mobile app developers needing backend services without server management hassle.

  2. PostgreSQL: 🐘

    • Overview: Powerful open-source relational database known for extensibility and SQL support.

    • Features: ACID compliance, extensibility, JSON support, full-text search.

    • Use Case: Widely used in applications requiring robust relational database functionality.

  3. Sequelize ORM: πŸ”„

    • Overview: Node.js ORM library simplifying database interactions using JavaScript objects.

    • Features: Model-driven, query building, associations, migrations.

    • Use Case: Commonly used in Node.js apps for organized and convenient database operations.

Let dive into setting up

We'll use VSCode for this! πŸš€ Open your terminal and kickstart a fresh Node.js project.

Embarking on a Node.js journey involves a series of steps. Check out the general procedure below to set up your application. πŸ› οΈ

  1. Install Node.js and npm:

    • Download and install Node.js from the official website: Node.js.

    • npm (Node Package Manager) is included with Node.js, so you don't need to install it separately.

  2. Initialize a new Node.js project:

    • Open a terminal or command prompt.

    • Navigate to the directory where you want to create your project.

    • Run the following command to create a package.json file:

        npm init
      

      Follow the prompts to set up your project details.

  3. Create the main application file:

    • Create a main JavaScript file, often named index.js or app.js, where your Node.js application logic will reside.
  4. Install Dependencies:

    • Use npm to install any external packages (dependencies) your application needs. For example:

        npm install express
      

      This installs the Express.js framework.

  5. Create an Express Application :

    • If you're building a web application, you might want to use a framework like Express.js. Create an Express app in your main file:

        const express = require('express');
        const app = express();
      
        // Your routes and middleware go here
      
        const port = 3000;
        app.listen(port, () => {
          console.log(`Server is running on http://localhost:${port}`);
        });
      
  6. Run Your Application:

    • Execute your Node.js application using the following command:

        node index.js
      

      If you're using a framework like Express, make sure to adapt the command accordingly.

Configure Sequelize and PostgreSQL

Certainly! To use Sequelize with a PostgreSQL database in a Node.js application, follow these steps:

Step 1: Install Sequelize and PostgreSQL Driver

  1. Install Sequelize and the PostgreSQL Driver:

    • Install Sequelize and the PostgreSQL driver using npm:

        npm install --save sequelize pg
      

Step 2: Create Sequelize Configuration

  1. Create a Sequelize Configuration File:

    • Create a folder called config and create a file inside that folder named database.js as shown in below configuration:

        // config/database.js
      
        const { Sequelize } = require('sequelize');
      
        const sequelize = new Sequelize('your_username','your_password','your_database',{
          dialect: 'postgres',
          host: 'localhost',
        });
      
        module.exports = sequelize;
      

Step 3: Define Sequelize Models

  1. Create Sequelize Models:

    • Define your database models. For example, create a file named models/User.js:

        // models/User.js
      
        const { DataTypes } = require('sequelize');
        const sequelize = require('../config/database'); // Import the Sequelize configuration
      
        const User = sequelize.define('User', {
          username: {
            type: DataTypes.STRING,
            allowNull: false,
          },
          email: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true,
          },
        });
      
        module.exports = User;
      

Step 4: Use Sequelize in Your Application

  1. Use Sequelize in Your Application:

    • In your main application file (e.g., index.js), initialize Sequelize and use the .authenticate() function to test if the connection is OK

        // index.js
        const express = require("express");
        const sequelize = require('.config/database');
        const User = require('./models/User');
      
        const app = express();
      
        const port = 3000;
      
        // testing the connection
        // this is a promise based function
        sequelize.authenticate().then(()=>{
          app.listen(port,()=> console.log(`Database connected successfully and app listening on port ${port}`))
        })
        .catch((error)=>{
          console.log(error.message)
        });
      

You've successfully configured Sequelize with a PostgreSQL database in your Node.js app! πŸŽ‰ Just a heads-up: don't forget to swap out the placeholders ('your_username', 'your_password', 'your_database') with your real Supabase credentials. Let's grab those from Supabase! πŸ”

To set up PostgreSQL on Supabase and obtain the database, user, and host details, follow these steps:

Step 1: Create a Supabase Account

  1. Sign Up for Supabase:

    • Go to the Supabase website.

    • Click on the "Start for free" button.

    • Sign up for a Supabase account by providing the necessary information.

Step 2: Create a New Project

  1. Create a New Project:

    • Once logged in, create a new project by clicking on the "New Project" button.

    • Enter a project name and click on "Create Project."

Step 3: Set Up Database

  1. Access the Database Section:

    • In your project dashboard, go to the "Database" section.
  2. Create a New Database:

    • Click on the "Create Database" button.

    • Choose a name for your database and click on "Create Database."

Step 4: Obtain Database, User, and Host Details

  1. Access Database Details:

    • In the "Database" section, click on your created database.

    • Navigate to the "Settings" tab.

  2. Get Database, User, and Host Details:

    • You will find the following information:

      • Database URL: This URL contains information about the database name, user, password, and host.

      • Database Name: The name of your database.

      • User: The username for accessing the database.

      • Host: The host URL or IP address of your database.

    • Make note of these details, as you will need to replace placeholder values (e.g., 'your_username', 'your_password', 'your_database') in your config/database file with your actual database credentials you obtained from supabase..

    • Certainly! Here's the code snippet with your Sequelize configuration:

        const Sequelize = require("sequelize");
      
        const sequelize = new Sequelize("postgres", "postgres", "Vyo6JywUn96CFPuU", {
          host: "db.qsyxrexhxeiwsygsaxor.supabase.co",
          dialect: "postgres"
        });
      
        module.exports = sequelize;
      

      This code exports a Sequelize instance configured to connect to a PostgreSQL database hosted on Supabase. Make sure to use your actual Supabase database credentials when implementing this configuration in your Node.js application.

Let's bring Nodemon into the mix! πŸš€ Time to install it.

Installing Nodemon:

To install Nodemon globally in your Node.js environment, you can use the following npm command:

npm install -g nodemon

This installs Nodemon as a global package, making it available as a command-line tool.

Short Explanation of Nodemon:

Nodemon is a utility that monitors for changes in your Node.js application and automatically restarts the server whenever there is a file change. It helps streamline the development process by eliminating the need to manually stop and restart the server every time you make changes to your code. Nodemon is particularly useful during development to enhance productivity and speed up the testing of code changes.

Set up the nodemon in your package.json file:

Certainly! Make sure your package.json file incorporates Nodemon by adding a 'start' script in the 'scripts' section: πŸš€

{
  "name": "Postgres-Supabase-Sequelize-Nodejs-Guide",
  "version": "1.0.0",
  "description": "A Guide to Connecting to PostgreSQL with Supabase and Sequelize ORM in Node.js Application",
  "main": "index.js",
  "scripts": {
    "start": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "nodemon": "^3.0.1",
    "pg": "^8.11.3",
    "postgres": "^3.4.0",
    "sequelize": "^6.33.0"
  }
}

In this version, I added the "nodemon" script under the "scripts" section. When you run npm start, it will use nodemon to watch for changes in your index.js file and automatically restart the server. This is a common setup for Node.js development to enhance the development experience by avoiding the need to manually restart the server after each code change.

you can run npm start on your local machine to start your Node.js application using Nodemon.

  1. Open a terminal in your project directory.

  2. Run the following command:

     npm start
    

This will trigger Nodemon to start your application (index.js in this case) and monitor for any changes. If you make changes to your code, Nodemon will automatically restart the server for you, saving you the trouble of manually stopping and restarting the application.

If you follow all the procedure given above, you should see something like this:

Here's a bash script that represents the output:


[nodemon] 3.0.1
[nodemon] to restart at any time, enter 'rs'
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting 'node index.js'
Executing (default): SELECT 1+1 AS result
Database connected successfully on port 5000

Your connection to Supabase PostgreSQL has been established successfully! πŸŽ‰ In the next post, we'll dive into the exciting world of model querying. πŸš€ Stay tuned!

Β