TechSolutionsHere.com

Next.js with Sequelize and PostgreSQL

next-js-sequelize

Today we will see how to implement Next.js with Sequelize and PostgreSQL.

First of all, you have to generate your Next.js starter project then need to install the below packages

npm install pg pg-hstore sequelize validator

then create a folder like model and index.js file into this and the index.js file looks like the below

// model/index.js
import Sequelize from 'sequelize'

const sequelize = new Sequelize('db-name', 'db-user', 'db-paasword', {
    host: 'localhost',
    dialect: 'postgres',
    operatorAliases: false,
    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000
    }
})

const db = {}

db.Sequelize = Sequelize
db.sequelize = sequelize
//...

export default db

Remember that the pool is optional, it is here Sequelize connection pool configuration.

Need to know about pool keys:

Now create a model into the model folder like user.js and the file will look like below

// model/user.js
const userModel = (sequelize, Sequelize) => {
    const User = sequelize.define("user", {
        id: {
            type: Sequelize.UUID,
            defaultValue: Sequelize.UUIDV4,
            primaryKey: true
        },
        name: {
            type: Sequelize.STRING,
            allowNull: false
        },
        email: {
            type: Sequelize.STRING,
            allowNull: false,
            trim: true
        }
    })
  
    return User
}

export default userModel

Again open up the index.js file and update like below

// model/index.js
import userModel from './user'
// aftere that below line add like that
// db.sequelize = sequelize
//...
db.users = userModel(sequelize, Sequelize)

now save and close the file.

Now create an API file for save data into the database. under the pages folder add an api named folder and into this folder add user.js named file and put code like that

// pages/api/user.js
import isEmail from 'validator/lib/isEmail'
import isLength from 'validator/lib/isLength'
import db from '../../../model'
db.sequelize.sync()
const User = db.users

export default async (req, res) => {
    // console.log(req.body)
    // Recieved params from request
    let { name, email } = req.body
    try {
        // check email, name, password format
        if (!isLength(name, {min: 3, max: 15})) {
            return res.status(422).send("Name must be 3-10 characters long");
        } else if (!isEmail(email)){
            return res.status(422).send("Email must be valid");
        }

        // Check if user with that email if already exists
        const user = await User.findOne({
            where: { email: email }
        })
        if(user){
            return res.status(422).send(`User already exist with that ${email}`)
        }
        const newUser = await User.create({
            name, 
            email
        })
        res.status(201).send(newUser)
    } catch (error) {
        console.error(error)
        res.status(500).send("Error in signup. Please try again.")
    }
}

That’s it! Now using postman call the URL with the necessary key & value and check the database, you will see tables are created with columns & values.

Happy Coding 🙂

Exit mobile version