Search This Blog

2026/04/15

Using Prisma with express.js

First create express app using generator


    npx express-generator --view=ejs myapp

In mysql create a database myapp.

# install npm packages
npm i

# Install Express and Prisma Client
npm install express @prisma/client

# Install Prisma CLI as a dev dependency
npm install prisma --save-dev

# run prism init
npx prisma init

It will create This creates a prisma/ folder with a schema.prisma file and a .env file in your root directory.

in env add database url
    DATABASE_URL="mysql://root:sangram%2381@localhost:3306/myapp"

In schema.prisma you should modify as

        generator client {
         provider = "prisma-client-js"  //other option is typescript specific which may come bydefault
        }

        datasource db {
            provider = "mysql"
            url      = env("DATABASE_URL")
        }

        model users {
            id        Int      @id @default(autoincrement())
            name      String?  @db.VarChar(255)
            email     String?  @unique(map: "email") @db.VarChar(255)
            createdAt DateTime @db.DateTime(0)
            updatedAt DateTime @db.DateTime(0)
        }
# run
    npx prisma migrate dev --name init

    it runs
        npx prisma generate

    create models in js inside prisma folder is node_modules &

# run
    npx prisma db push

    to maake sure table is created

inside user route include prisma client
    const { PrismaClient } = require('@prisma/client');
    const prisma = new PrismaClient();

add route for test as

    router.get('/add-user', async (req, res) => {
        const user = await prisma.users.create({
            data: {
            name: "Sangraam",
            email: "sangram@example.com",
            createdAt: new Date(),
            updatedAt: new Date()
            }
        });
        res.json(user);
    });

#Now run
    npm start

# hit url http://localhost:3000/users/add-user

confirm in mysql entry has been aadded or not.

No comments:

Post a Comment