Install and Set up Prisma for a New Project

Xiaoru Li
InstructorXiaoru Li

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

Prisma makes database access easy with an auto-generated and type-safe query builder.

In this lesson, we will learn how to install all the necessary dependencies and set up Prisma for an existing npm project, with an empty PostgreSQL database running in the background. We will create our first Prisma data model in the schema, and use Prisma Migrate to map our data model into the database.

Finally, we'll generate the Prisma Client into our node_modules directory, so later we can simply import and use the client tailored to our data models as a normal npm package in the project.

At the time of recording this lesson, Prisma Migrate is in an experimental state, so the extra flag --experimental is needed to perform the save and up commands.

Xiaoru Li: [0:00] First, let's install the Prisma extension for VS Code. In our project, let's run npm install @prism/cli typescript ts-node, and the type definitions for Node as dev dependencies. After the installation is finished, let's run npx tsc --init to create a tsconfig.json file.

[0:35] Now we can run npx prisma init to generate a new directory called prisma, with a status schema and a .env file which contains the DATABASE_URL string that we need in order to connect to our database.

[0:54] Since we already have a Postgres database running in the background, we'll change the username, password, the port number, and the name of the database to our own.

[1:08] Now let's go to the schema.prisma file to define our first data models. Let's create a new model called Profile, which is going to have an id field and a name field. The id field will be an integer that we want to automatically generate when an entry is created. We'll also mark it with an id attribute. For the name field, we can set it to be a string.

[1:38] Since we're starting with an empty database, we'll use the npx prisma migrate save command to prepare the mapping of new database tables to our data models. We'll also give this first migration a name called init.

[2:00] After this, we'll be able to see a new directory called migrations created in the prisma folder. Inside this particular migration, we can see a README file detailing what SQL commands should be performed for our first migration.

[2:17] To perform the migration, we'll run the npx prisma migrate up command.

[2:28] Now we can generate the prisma client based on our data model with npx prisma generate. The generated code will live inside the node_modules directory. Later, we can simply import and use the Prisma database Client tailored to the data models of our project as a normal npm package.