Next JS with PostgreSQL

How To Connect Next JS with PostgreSQL Server?

Next.js is my preferred framework for developing React-based web applications, and I’m using it for API Routes to implement a REST API. The REST API needs to store and retrieve data and that’s why it needs a database whatever like PostgreSQL, MySQL, Oracle, and MongoDB database, but need to mention here the MongoDB with Node.js based project is easy & comfortable, you can find tons of examples over the Google but SQL? You may not find so many examples, so it is an article on how to connect to the database server with PostgreSQL. This article describes how I create and manage that database connection within the API routes.

I am assuring you it is easier than you think!

First of all, prepare your Next.js boilerplate project based on their doc.

Then install that package like

//NPM
npm install pg-promise

//Yarn
yarn add pg-promise

Create an API file in `/pages/api/product.js` & open the file and write code something like that below

// pages/api/product.js
const pgp = require('pg-promise')({
    noWarnings: true
})

const db = pgp(`postgres://User:Password@localhost:5432/product-test`)

From the above line the User is PostgreSQL User and the Password is PostgreSQL Password and the localhost is the hostname and 5432 is Database Port & The Database port by default is 5432 and lastly the product-test is a database name.

Now follow the below code

// pages/api/product.js
...
export default async (req, res) => {
    try {
        const { name, price,  imageUrl, description } = req.query

        if(!name || !price || !imageUrl || !description){
            return res.status(422).send({error: ['Missing one or more fields']})
        }

        const product = await db.one('INSERT INTO products(name, price, imageUrl, description) VALUES($1, $2, $3, $4) RETURNING *', [name, price, imageUrl, description])

        res.status(200).json(product)

    } catch (error) {
        // console.error(error);
        res.status(500).send({message: ["Error creating on the server"], error: error})
    }
}

And here it is! Was not it fun? Definitely it was nice.

Now you can cover all your stuff like Select, Update, Delete from Learn by Example

Don’t forget to create a comment if you have any confusion.

Happy Coding 🙂