How to set up Prisma with Next.js and Postgres!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're going to install Prisma with next JS using postgres as the backing database we're going to do this in the app directory but also show how you can use Prisma in the old Pages directory as well Prisma is a fantastic orm that lets you define your schema run migrations and manage your database it's built on top of typescript so everything you do with Prisma is type safe this makes development super easy it's pretty easy to get started with but there are a couple of small gotchas that might trip you up we're going to go through this end to end and make sure you have it running correctly let's get started we're going to do this entirely from scratch so we're going to create a brand new next.js app of course you can use your own if you already have one we'll call Prisma postgres and we'll use the app directory so we can do this both ways all right make sure you CDN the first thing that you're going to need is a postgres database to connect to to test this you can use super bass you can use a postgres instance running locally I like to use Docker it's great for ephemeral postgres databases I do this a lot so here's a command to run postgres on Port 5432 this is going to create the default postgres user and the default postgres database make sure you know how to connect to your database we'll need that soon back in the project directory we're going to install two packages we're going to install Prisma and the client the Prisma package you only need in Dev mode or maybe in your CI CD pipeline it's the thing that's going to help manage your database it creates the migrations it executes them it can pull from the database and it can push to the database you don't need this package in production so make sure you only install it into your Dev dependencies the client is what you'll use to connect to your database in your application and actually execute all the SQL queries so that you're going to need p and PM and only for Dev and then we'll install the client as well the next thing you're going to need to do is you're going to need to initialize Prisma luckily there's an easy command for this npx Prisma in it this will create a folder called Prisma and set up all the defaults for you there we go with that let's jump in here's the Prisma folder with a default schema we're using postgres which is the default so we don't need to do anything there and it's reading the environment variable database URL it's put that into our environment file which is nice but this connection string is obviously not correct for us we're using the postgres user and there is no password 5432 is correct and the database is just postgres all right now we can create a very basic Prisma schema for this we're just going to create a basic user model and fill in some fields we'll give it an ID a required email maybe required password and an optional name now that we've modified our schema we have to tell Prisma that we've made a change to it Prisma executes changes on the database as a migration you could have migrations roll forwards and apply to the database and you can also create a way to roll backwards in case something goes wrong this is useful when you're making changes to production and you want to ensure you have a way to reverse the change that you made in case there's a bug or something in your application that's causing problems so to create our very first Prisma migration we're going to run npx Prisma migrate Dev and we'll name it something simple like inits because it's our very first one all right it creates a very unique migration here and then it applies it to our database so it's connecting with that connection string that we just used and then it goes ahead and generates the Prisma client and makes sure that all the type definitions there are fully up to date the first gotcha is that the Prisma client stores the type definitions in the node modules folder now you don't commit the node modules folder to a git repo so when you go to build your application and when you're deploying it to versl or deploying it somewhere else anywhere in your CI CD pipeline one of the first things you do is reinstall all the node modules see where I'm going with this when you reinstall the node modules you don't have the Prisma type definitions you have to regenerate those so you can either post installation generate them or as part of the build process you can regenerate them I like to add it as part of the build process so open up your Prisma dot package and go ahead and jump right here into build and do Prisma generate and then do the next build this means that on platforms like Purcell the first thing that's going to happen when it goes to build it is first you're going to generate all the typescript definitions for your schema then you'll complete the build this will ensure there are no type errors all right we have our schema and it's been applied let's go ahead and take a look and see exactly what that looks like I have a nice little program for browsing postgres databases and here you can see we're on localhost the postgres database and here's our user table we can go ahead and jump in and take a quick look at the structure has an ID email password name everything exactly as we defined of course for Content there are no users yet we have nothing luckily Prisma gives us a nice way to seed the database to get this working with typescript in next.js specifically we have to do a couple things first the first thing we have to do is we have to install TS node this lets us execute a node script but the script is written in typescript the Prisma documentation says that there's a key in the package.json file which Prisma will read to seed the database after commands we go ahead and take a look we're going to go ahead and add a new Prisma key and in it we'll call this seed and this is where you're going to execute the TS node into a new seed script however the next JS default settings for modules are not compatible with just executing a simple script so when we go and add the command to execute our seed script that Prisma is going to use we have to set the compiler options accordingly here we're saying execute TS node what we just installed and we're setting the compile options to make sure the module is being used as common JS and then there's going to be a prismac file that it executes we don't have that yet so let's go ahead and create that now this can be named anything but this is a common name for it and in this file Prisma is going to execute it after it runs migrations or updates or resets the database this will allow us to have an easy way to see default information when you're building an application development speed is everything so it's really useful to be able to just see the default data once and then whenever you're rapidly iterating you don't need to worry about the data being there or not for this we're just going to upsert a user so here we have Prisma user upsert and we're going to check the email we have to add unique here and then regenerate the Prisma client here we're simply upsetting a user into our database we're checking to see if this user exists because otherwise every time you ran a migration it would just create a new one if you used create instead of upsert so we're checking to make sure the user does not exist and if it does then we're simply going to do nothing because we don't need to update it and if it doesn't then we're going to create this test user this very secure password is password lastly we're simply going to log the output there's a couple of places where this will run it will run after a migration it'll run after you reset the database or you can just run a command to see the database the command is Prisma DBC you'll see that it picked up the command that we wrote Into the package.json if you don't have these compiler options this won't work in next.js and then it outputs exactly what it did and the C command has been executed if we jump back into our database and refresh we now have a user so let's go ahead and use it you can see in our application this is the main way you're going to be using the Prisma client however if you keep creating a Prisma client you're going to keep creating connections into your database the Prisma client has pooling built in so you really just want to have one instance of a client in your application at any one time this pattern is commonly known as a Singleton most of the time single tins are anti-patterns you don't need them that frequently but this is a good example of when a single tin is actually correct to use you want to have a single object that is managing the connection to your database and it manages everything internally to go ahead and make that easy we're going to create a new folder called lib and then inside create a prisma.ts file this is going to create that Global instance of our connection this came straight from the docs so don't think of it as anything too special we're importing the Prisma client and then we're going to check the global object um to see if it has Prisma already if it does we're going to use that Global Prisma object and if it doesn't we're going to create one because we're exporting this this is only going to be executed once during the export process where we'll create a new one and then after that we'll simply reuse that same Prisma client go ahead and save this and now when you're importing Prisma to use it don't import the Prisma client and create a new one instead import the Prisma instance from this file all right let's go ahead and use it in our app folder for the first time here we can go ahead and start running our Dev server let's go ahead and take a look make sure everything is exactly as we imagine this should show our default sort of Welcome to next JS application all right there we are it's working perfectly to see this in use we're going to do this in two places we're going to use the client in the app directory in a react server component and we'll also create an old-fashioned page in the Pages directory so if you're using that you know how you can use it remember the Prisma client is connecting to your database you can't use a client-side you have to use this server side first we're going to clean up a little bit of this code this looks good all right we now have a blank application so to use this in the app directory we need to do a couple things first mark it as async because we're going to use a weight in it and then const user will await Prisma make sure you're importing it from the file we created user and let's uh let's just find the first one where email is test.test.com now this user may or may not exist so you can add a check if you want for seeing if that user is there or not but since we seated the database we know it is so here we'll do hello user and then just as safety conditional name save that and there you go that's all you had to do to use the Prisma client connect to the database find a user and return it in a react server component so this is how you would use it in the app directory but if we're using this in a page in the Pages directory you're going to need to use a slightly different method let's go ahead and create pages and then we'll call the file example here we have no server components so we're just going to export a regular page this is example so if we go here to example it should say that's weird we had to restart our Dev server for that to show up I think that's a bug in xjs so once you create that it should say hello over there might need to restart your Dev server if that's not the case and now we can use git server side props as the function that's going to connect to the database get the user information and return it okay and now we can also ensure we have the properties we can infer the property types using the inferget server-side props and then make sure and now once again hello refresh the page and there you have it thanks for watching if you made it this far I build SAS applications and help you build yours if you like this video give it a thumbs up and go ahead and subscribe and until next time happy coding
Info
Channel: Build SaaS with Ethan
Views: 22,576
Rating: undefined out of 5
Keywords: next, nextjs, next.js, react, prisma, postgres, software, coding, software engineering
Id: _ER9jHiylAo
Channel Id: undefined
Length: 17min 39sec (1059 seconds)
Published: Fri Feb 24 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.