Using Prisma with Next.js - Prisma Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys what's going on this is River here and today we're going to see how to use prism my next JS so if you don't already know prism is an abstraction layer between your server and your database and the server is specifically a typescript server and if you ask why this abstraction it's to remove all the use of the Native queries your databases is like all the SQL queries MySQL and postgres stuff uses and instead using it in a more friendly in a more typescript functions way and it's more like a query builder for you and you can connect a lot of databases using it including mongodb and relational databases so it's it plays very friendly with your typescript app so let's jump into it so I have made this next.js application so if you don't already have an XCS application you can do npx create next app and the project name and I assume you should already know that if you're watching this video so yeah let's get started with installing the personal packages and stuff and setting up Prisma in your next race application so this is my terminal and we are going to install a few packages here so I'm going to use pnpm so if you're using yarn or if you're using npm you might use your favorite package manager so I am using pnpm so pnpm install so the first first dependencies we are going to install our developer dependencies so we are going to add D here and then we are going to have Dot envcli and we are going to see why exactly and the next one we need is Prisma and this is going to be a div dependency so yeah let's click enter and let's wait for this to install we are installing because by default Prisma uses dot EnV file from your project to pick up all the database details but since we are using a nexjs application and they recommend.tnv.local we need to override that to use dot env.local so that's why we use this and we will be creating scripts in our package package.json now we need to install some regular dependencies so pnpm install it should be at Prisma slash client and I think that's it so let's click enter this should not take a lot of time and yeah perfect now Prisma has a very handy command to automatically set up a Prisma thing in your project so to do that you do pnpx Prisma in it and this will just set up Prisma for you in your next test application automatically and you don't need to do anything else and if you see all of these things your project should have should now have a Prisma directory and you should have a schema.prisma here plus you should also have a DOT tnv file which we will rename to Doty and we dot local because we are using nexjs and by default next yes geticknose dot envy.local however if you want to use dot envy and add to getting no that's fine as well but since we are doing this in the next JS application I want to really keep it to how next just recommend things so yeah if you think this is overly complicated you can simply use EnV file now we have this database URL uh this is using postgres but before we change anything here I want to make sure that our DOT EnV file uh so that so right or Prisma uh so that Prisma uses the correct tnv file we need so let's go to package.json file here and here we need to create a few scripts so I'll just copy those scripts here and then we'll go one by one on these so Prisma generate command is used to generate any types so if if you look at node modules there should be a Prisma [Music] it should contain all of your types of all the models you create here so we don't need to look at them but adjusting you need to do this generate command when you are deploying it to a production environment then migrate Dev is used to make any changes like if if there are any changes you make to your model if you want them to reflect in your database you need to run this command in development environment and there is one for production and there is a Prisma Studio One which okay let's save that for later it's a pretty cool feature so let's save that for later and what this these commands are basically doing is npx.env and we are using the dot env.localfile and then we are running all of these commands so basically all of basically prefixing this tells the next command that hey from now your environment variable files.inv.local and you're not using dot tnv anymore so yeah that's what it's basically doing now let's save the file and in this tutorial we are simply going to create a new posting something like Twitter but not exactly Twitter so this is going to be uh uh place where you write post and if you click on post the post should go here I think I have stopped the server so I need to start it again perfect uh let's see let's write hello world if we click on post this should appear here and all of these are already in the database so let's get this away and let's work on our bare bone app and let's get towards the goal let's stop the server let's go back here now we will do pnpm Dev and we are going to run the server for our current next yes application perfect now let's create a new model so for this one for the one we have for the project I just shown there will be a post model and let's create that first so model so if you are using uh vs code there is a handy extension called as Prisma in the vs code store so you can just go here and search for Prisma and you can just install this and if you don't install this you won't get all the syntax highlighting and the code suggestions so I highly recommend installing this it will make your life a lot easier so we are going to type model here model post and they should have a few things so first of all it is doing everything for me but let's just write this because we are going to do a lot of copy pasting in the UI part because it's not really relevant and since this the database part it's important so we are specifying this that it's an ID and by default it will have an auto increment so by default it will if there is no ID specified it will auto increment from the previous ID in the database and then we will have created at which will be a date time and it will basically be the default value will be now so that when the record is created it will be the timestamp of that time itself then we will have updated that so Prisma has the school updated at TAG already so if you modify any changes in modify stuff in your database it will already be reflected in updated at it's a pretty cool feature and then we are going to have a Content which is going to be a string if you save this file I think prettier doesn't like to work here but let me get a move formatted version of this so that it looks good this should work too but I just wanted to keep it a little better yeah perfect now the thing is that we don't really have a database here and for local development environments we could do something like installing a postgres local database in our computer but it's a lot of work and I don't really want to do it for tutorials so what we can do here is we can use an sqlite database which really is just a small just a small file which will have which will basically be your database and it's very handy for local environments so and for testing stuff so we are going to change the provider to sqlite uh the code sessions should work here and in the database URL we will just go to env.local and we will change the database URL to file colon and now we can just specify the relative path uh from this schema.prisma DB so when we migrate these changes there will be a new database created inside this folder so if you are wondering this is not this way this will not just work outside the box already you need to migrate these changes to make sure these changes you just now made for in our case is creating a model is reflecting in the database to do that we are going to run the command which we created here so it's the migrate Dev command so let's just copy this let's go to our terminal let's open a new terminal and do pnpm migrate Dev now it's the sqlite database Dev dot DB created at this location and now we can see that this is dev.db thing perfect and now the the cool thing about about our script which was like Prisma Studio I was hiding from you now it's the time to unveil that and let's try to use that command and you can see oh oh the migration is not completed so I forgot to type so it's like I enter a new for the new migration it's same like a commit message so if we type in it it's done and now we should see a migrations folder and if you look at it in the migration SQL you will have a all the SQL code which will lead us back to the changes we made here so in this case we created a post model and it will it is creating a post table in sqlite database sorry for not sorry for not having a lot of attention here so yeah now let's do pnpm Prisma Studio I was just excited about Prisma Studio to be completely honest let's click enter I want to open this in YouTube perfect move here now we have a built-in database Explorer with Prisma in this case it's just exploring our sqlite database if you had some kind of postgreso stuff or even mongodb it would allow you to browse the database here and even add records here so we can just do an add record and we can just create a new create content here so this post directly comes from database we can just click somewhere else and we can click save on changes and boom it's added to the database it's a pretty handy feature in the testing environments where you really need to quickly check the database and see what's really happening instead of like logging into your credentials and stuff or really opening your applications for postgres and stuff it's Prisma Studio really comes in handy and uh we created our first first post through the database and we are going to display it in the app so let's go back to vs code now all of this is sorted out and we need we don't need to check this again so let's close this migration folder now what we need to do is we need to create a new server folder here so let's call it server and let's create a new file called prisma.ts and this file helps us to manager of Prisma connection with nexjs and the thing with nexgs is that whenever you create a new API call sometimes the server goes to sleep and when you wake it back up a new Prisma instance is created and if you create a new Prisma instance in every single API call it will create like 10 different instances and it will really slow down your performance or it it might lead to you reaching your limits in your database provider so to tackle that we can simply go to our browser and the Prisma team really has a good snippet to take care of so we can just search for Prisma next.js and we can just click here so we have this link best practice for instantiating Prisma client with next.js so they know what what's really happening so they say a lots of users have have come across this warning while working with nextjson development there are act there are already 10 instances of Prisma client active actively running so yeah as I said it will just keep creating instances and it will really cost you a lot so uh if it will cost you a lot if it really costs you for having multiple connections so let's copy this um we can just use this copy button so and let's go back to our vs code let's paste this so what this file is doing it's creating one Prisma instance and it's going to maintain it up we are going to maintain this across the entire server and we are going to use this Prisma variable we are extracting and we are going to keep using this and if some for some reason if the server sleeps it also it automatically creates a new Prisma instance so they really have this script for production ready so you don't really need to worry about it we can just click cross and now we can start working so let's go to our Pages directory let's go to index.tsx but before let's go to localhost 3000 here because we haven't even opened the app which is funny um hold on what happened now we see this next year's thing now we need to remove everything we don't really need anything here so let's go back here let's remove everything from inside the main and for the UI I'm not going to use a lot of time here so we are going to have some style for the main tag so I'll just copy it and paste it here uh if you want of course you can use tailwind and stuff but since this is a specific database tutorial for Nexus I don't really want to go in that it will just waste your time so yeah now we have this jsx I'll just copy this and paste it for you and we're going to see what this exactly is so first of all we have a text area which is write a post and then we have a button and then we map all the posts and we haven't really got the post yet so we are going to do that but let's work towards that first and this is basically the same UI which I showed you moments ago so let's first work on getting the post so I'll just remove this on click and stuff we don't really need this uh we can probably create this States right now so let's create the state for the text box so constant let's remove react Dot ah let's Auto Import your state perfect and now yeah I think it should be fine now we need to the method we are going to use to get the post is going to be using get server side props in next.js if you don't know what that is which is value highly unlikely I'm pretty sure you all must know it's basically before the page loads the server already fetches the data for you and passes it as props and we are also yet to get the props here so let's go here and export export async function get server side props and we don't really need a contact so we're just going to leave it empty and now we are going to okay it's going to suggested dummy data copilot be like copilot so yeah we don't really need to do that so let's get the post so how easy it is it to get posts so we are going to do const post is equal to Prisma we are going to Auto Import it dot copilot shut up please post dot find many and if you look at post dot there are a lot of different things basically instead of using query you can basically interact with these function and it's going to be a lot more cleaner in your code and it is type safe so if you're creating a new post it's very types it it will automatically prompt you what you really need and what you don't so yeah so in this case we just need to find many and we're going to leave it to that because we want all the posts and now we are going to do X we are going to do return props posts and we're going to leave it there and this code is going to cause an error but let's just try to run this anyway so we are going to have props of posts here and it's going to say that we need a type so let's just create a type so type post uh posts I think it's props sorry and here we're going to have posts which is going to have the type of okay now this is interesting how do you know how to get the type of this one option would be like to create a new type of getting like using creating new type with all these data types and the second would be just being an intelligent person and using the prism using the types that Prisma created for you so you can just go ahead and type post and you can all you can already see it's it's importing for Prisma client so you can just do this and yeah it's since it's an array we can just do this perfect and now we can just specify this this has props perfect pretty amazing now I think this should work oh no we will have an error interesting cannot read properties often okay so reloading fix that but then we have this error the error which I wanted to show you error serializing dot posts and uh reason object cannot be serialized as Json so what really is happening here is when we are fetching the pose it will it has date time object and it really isn't converting it back to Json so next.js isn't doing that and we cannot directly transfer objects back to the client side so since it cannot transfer object to the client side it's showing us there a simple way to fix this is simply going to be creating an object that can be passed into Json and sent back to our client side to do that we are going to create a new object so Json dot parse and we're going to do Json Dot stringify and we're going to do posts so what this exactly is doing is first of all it's going to stringify our post object into a Json so it's plain Json and then we are going to use Json pass to create it into an object and these objects are serializable and this can be transferred back to a front end now this should work let's go back to our browser let's reload post.map is not a function and that's really interesting because this should really work prisma.post dot find many who is json.pass but this is supposed to be an array right so what really is happening here I think I know what that is all about maybe yeah we missed the weight here so maybe it's just returning a promise and it's never converting back to Json so yeah let's try again yep now we already have our first post which is like this post directly comes from our database and yeah if you go back to our Prisma Studio and if we type something else so definitely does we are going to update this and now let's save on changes and you can see the updated ad changed if you're not really sure you can just go back five seconds and see it really changed after we clicked on save so yeah let's go here and now reload this page it says definitely change so so you know that this is really pulling up from a database and we are not using any fake dummy data of course we are using memory data but we are not really using a fake array or something like that so I think this is finished getting the post is done now we need to work on creating a post and we cannot do this in a get server set cross because we need to make it so that when a person clicks on this button the post should be created so there are a lot of ways to do this and there might be a lot of efficient ways to do this but I really want to just not focus on the react part and not really focus on the best way to refetch all the data I just really want to get this done and explain you how to really work with prismine and Extras application I am pretty sure your your all are very intelligent enough to come up with different ideas and make this as efficient as possible if you want to so yeah and plus this is not a tutorial on optimization and stuff if you if you want something like that please leave that in the comments below and yeah I'll make that tutorial for you so yeah now I think we need to go to the API folder and let's create a new file called create post dot TS so this is going to be our new API route so let's just copy this okay you know what I'm going to copy the entire thing paste it we don't need the data it's too much work and let's remove the command perfect and now here we are going to have some backend logic so let me just open it here so that okay so there are a few things we are going to do here first of all we are going to make this an asynchronous function and now we are going to have a try catch block here and if there's an error we are going to Simply do console.error error or and and then we are going to just pass in a response that it is an error in a server so rest dot status 500 and we're going to say dot Json message internal server error we are done with the cache block and now let's start with the try block so we're going to check the method so if request dot method is not equal to post so if the user sends a get request or stuff then we are going to return and we are not going to execute any further and we are just going to return an error so rest dot status uh this is going to be 405 and Dot Json this is going to have a message not allowed perfect and now if everything is okay we are just going to do const uh we are going to restructure we are going to get content out of the body of the request and we are going to request.body so we're going to get the content out of the request body and we haven't made the part where we send the request yet we are just expecting that this that the API call will send up uh object with content having a string so yeah just assuming that remedy is working on that so const new post is equal to a weight Prisma Dot post dot create and now here we can say data and now here's where all the fun part starts you can just do come control space or yeah it's control space on both Windows and Mac you can see all the things so here we only need the content so it picks up that we need content and yeah we can just leave it here because it will pick up from here now this new post after the post is created this new post object will have the specific record of it we can just send it back to through our response or if it has any sensitive data you can you should not send it back to the app but since this is just a dummy thing we can just send it back so press dot status you know what I'm going to copy this which one take a lot of time to type this yep so it basically says real estate is 200 post credit successfully and then we're going to pass the new post here and I'm pretty sure there will be some problem in parsing here as well so let's just okay I don't I don't think that problem is there for API outs I think it's only for server side rendering but yeah anyways uh let's go back to our index.tsx file and now we need to create a new function that create that makes an API request and we are not going to use a lot of time here and I will run through the code so let's just paste this here and see what really it does so this is a function called as create post and what it basically doing is creating a post request to slash API slash create post so it is the route which we created just now and in the body we are going to pass the Json with the content which will be in the state so whatever you type in the input box will be updated in the state and we are going to pass in the state here and then we are just going to tell through the headers that hey this is Json data and if there is a problem with the response we are just going to alert out you know what we are not going to alert about this we are going to alert out uh first we need to get the data so const data is equal to a weight response dot Json so now here we're going to type out data.message or something went wrong so you see that here we have passed in message in all error error cases so we can just pass it down here or if it still doesn't have for whatever reason we can just say something went wrong now I think this should be enough uh we know we need to pass this function into our button so let's go here and say on click create post and I think they should be done so oh yeah we are also reloading the document once it's done and this is the reason as I said I remember to really waste a lot of time in refetching if you're using like react query and stuff you can really do that and one more thing I really wanted to point out here is like you really don't know what data you are getting back here unless you are using some kind of specific types here but I've guessed it two days ago or three days ago I think I created a new vid new video on trpc and trpc really helps you create some type save backends and typescript and if you're using xjs it's more easier you get all of the code suggestions and stuff and a lot of type safety so if you want to check that video out I think it will be here somewhere or here not really sure it depends on the editing but yeah um let's go and I think wish it should work so let's reload this let's type a new post and this one is coming from the app directly let's pause this perfect now it's in the database now we can just keep on adding new things and stuff so we can just say subscribe to this channel and let's pause this boom it's here by the way you really should subscribe to this channel if you really want some cool technical content from me and some dope tutorial tutorials I'm really bad at speaking okay so let's go back to Prisma studio and let's reload this and you should see these two things and yeah pretty fun it's pretty smart I just like Prisma Studio I cannot stop appreciating it now let's go back to vs code and now I really want to tell you how to set this up to deploy in production environment we are not going to deploy it in production environment but if you really want to do that uh you just need to change your database URL here to whatever you want if it's a mongodb thing you need to use your connect URL or if it's postgres or stuff you need to use a connect URL as well and then you need to go to schema Prisma and need to change this to something else so if you're using so um Prisma supports all of these stuffs cockroachdb mongodb MySQL postcode SQL sqlite and SQL Server so yeah but we are going to stick to sqlite here you can just choose whatever you want and it will start working and in production what you want to do is uh for the build script it's for the production script what you should do okay you know what we should create a new productions build production so we need to do something so first of all let's do uh the stuff we really need this then we need to do migrate npx Prisma no we need to use the in pm run migrate and then we need to do npm run build oh we need to also do npm run generate to generate the latest typings if they are not already done and we need to do npm build and this will point back to our next.js build function so if you are deploying this to Versa make sure this is your build command and not the regular build one and what this will basically do is like if you have any migrations and stuff it will automatically perform all the migrations on your production database just while deploying the application to production so it's very handy and it's pretty cool so yeah I think that's it for the tutorial so yeah that's it for this video in this video we saw how to use space my Unix application and all the specific stuff about Prisma so if you really like this video and if you found value in this video I would really appreciate if you like this video And subscribe to this channel it will really help me create a lot more tutorials and bring value to you more and yeah if you have any more ideas about future videos and stuff make sure you leave them in the comments below and I will make sure to make them so yeah that's it for this tutorial uh all of the code will be posted in the description below and yeah that's it I'll see you guys in the next one bye
Info
Channel: Atharva Deosthale
Views: 5,147
Rating: undefined out of 5
Keywords: programming, programmer, coding, javascript, react, typesafety, nextjs, prisma, orm, database, sqlite, postgresql
Id: 3aWgYi-Liog
Channel Id: undefined
Length: 33min 59sec (2039 seconds)
Published: Wed Sep 06 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.