 Hey, welcome everybody! In today's video, we will dive deep into creating a numbered pagination using Next.js 14 and MongoDB as a database. Everything will be done on the server side and this code can be adjusted to work with other databases. If you find this video useful, please like it and consider subscribing. Hey, welcome everybody and let's get started. Just so everybody can follow along, I will create a brand new Next.js project. So let's copy the code from here and let's open the terminal. So I'm going to go to this folder here, which is located in my C drive and I've called the Next.js. Inside here, I'm going to do left shift right click and open in terminal. Essentially, this is just going to CD to this folder here that we currently in and that's pretty much it. So from here, let's install the project by doing right click and this is going to paste the MPX create-next-app at latest press center. Let's give it the name of Next.js 14-pagination, press enter, type script no, yes, lint no, tailwind.js, yes, source directory, yes, up router, yes, default import alias no and this should take a couple of seconds to install. Right, now we need to navigate to our newly created project, which is under Next.js 14-pagination. So CD, Next.js 14-pagination. From here, we need to install our database, which is MongoDB in this case. So MPM if we install and then MongoDB, press enter and this should take a couple of seconds. All right, now let's set up our database super quickly. So I'm going to go back to the browser and navigate to MongoDB.com. We're going to be using a free cluster today, so everybody can follow along. And if you wish to, you can also use their graphical user interface, which is called Mongo Compass. You can install a new computer and do exactly the same thing. So from here, let's sign in. All right, now that we're on the dashboard, let's create a new project. Here on the right side, they've changed the layout a little bit and I've turned on the dark mode, but here on the right side, new project. And let's give it a name of Next 14-pagination. Click Next. From here, we can leave the default settings and click Create Project. And now we need to create a deployment. So click Create. From here, I'm going to choose the M0, which is the free cloud environment. And then click Create. Now in this step, we need to create our username and password, which is going to allow us to authenticate. So here, I've got as default ready, auto-generated a password for me. So I'm going to keep it the way it is, but make sure that you copy both of them. So I'm going to open Notepad and paste both of them. So ready. And then here is the password. So I'll paste it here and save this and keep it open for a bit. Let's click Create User. From here, select my local environment, scroll down. And here you have your IP access list. Essentially, they're going to add your current IP address, which means that you're only going to be able to access the database with this IP address here. But of course, you can remove it and allow anybody to connect to your database if you wish to. And one thing that I need to mention is that sometimes when you restart your computer, your IP address might change. And then if you need to update it, you can go here to network access and add a new IP address. That's pretty much it. And finish and close. Okay, so here is our cluster. Let's click on this arrow here and all database is still being created. So it's going to take a couple of seconds and I will come back. All right, finally, now that I have the cluster ready, let's click on connect. From here, choose MongoDB for VS code and copy the string from here. Copy it. I'm going to paste this into the Notepad and leave it as it is for now. I'm going to minimize this and close. And then from here, let's click Browse Collection. And as of now, we don't have any data into the database, but I'm going to add my own. And because we're going to be displaying programming languages, I'm just going to call the database name as programming. And then the collection is just going to be languages, like so. And click create. Okay, I've already prepared some dummy data that we can insert. So I'm going to leave this in the GitHub repository, link in the description below, insert document. From here, choose the first option here. And then let's remove everything and paste the dummy data, which consists of name and a language. Let's click insert. And we have around 40 records. Now, super quickly, if we look at the record, you will see that MongoDB automatically added a unique identifier for each record. And then we just have a name with the programming language. And it just goes on like this. It repeats so on. And I think that we have 40 records. Now that we are done, let's minimize this and let's go and open the project in Visual Studio Code. So here is your project. I'm going to click inside the project and open it in Visual Studio Code by doing left shift, right click and open in terminal. I'm going to do code period, enter. And this will open Visual Studio Code for me. Let's close everything else. And the other way of doing it is obviously file, open folder and navigate to your project. Now, the first thing that we need to do is create a dot ev file so we can add or connection string. We might as well copy all of them. And then and here in the main directory, let's create a new file called dot ev. And since we're working locally, I'm just going to put local presenter. I need that here, we can create an ev variable name, which is going to store or string. So I'm going to do MongoDB underscore URI. Let me zoom in one more time. This is going to be equals the string that we copied from MongoDB. So here it is, paste here. And we have the username, which is already here. And now we need to just put the password and replace it here. And that's it. Let's tidy things up and save. I'm going to close the dot ev file. And now let's create or connect Mongo file, which is going to help us connect to the database. So let's open the explorer. From here, let's create a utils folder. And that folder needs to be inside the source. I'm going to do any folder utils. And then inside this utils folder, I'm going to create a file called connect Mongo.js. And let's focus on this file. So this is how it should look like. All right, we're not going to need this anymore. Let me close it. Since we installed MongoDB early in this tutorial, we can bring the Mongo client in order to connect to the database. So import in curly brackets, Mongo client, like so. And this comes from MongoDB. Now we need to bring our database string, which comes from the dot ev, the local file. And it's called MongoDB URI. So let's close this. And let's put it into a const MongoDB URI equals process dot ev. And then the name of the variable, which is the same as the concept MongoDB underscore URI. All right, now I'm going to use a singleton pattern and create a let client, which means that every time we want to connect to the database, it's going to check whether we've already connected, whether that connection exists and use it. And if it doesn't, then we'll make a new connection essentially want to prevent multiple connections to the database. So what I'm going to do is call let client. And as default, I'm going to put it as no, that's it. Now let's create our function, export async function. And we're going to call it connect to database. And then inside here, we can check whether we've already connected to the database. So I'm going to do if we have client, then return client. And that's it. So if you already connected to the database, just going to use this, and it's not going to continue. That's it. We're not going to create a new connection. And the other thing that we can do, which could be helpful is to check whether we have the MongoDB URI from or EMV. So what I'm going to do exactly the same thing, if we don't have the MongoDB URI this time, I'm putting the exclamation mark here at the front, then we're going to do Conzo, the log, and we want to say MongoDB URI not found. That's it. The last thing that we need to do is the database connection. So I'm going to do try catch. And then inside the try, we're going to have client equals await. And then we're going to bring the Mongo client from here dot connect. And then inside the connect, we need to put the string, which comes from MongoDB URI here. So I'm going to put it inside here. If you wish to, you can put more options. You can just do comma and then options, but you need to create the object with the options and so on. I'm not going to have any. So I'm going to leave this part off. And then let's do another console log log and then inside here, let me move a little bit connected to MongoDB successfully. And then the last thing that we need to do is return the client. So return client like so. And inside the catch, we can just console error dot error. And then we can just put a message saying error connecting to the database. And then we can bring the error from here button comma and then the error. That's pretty much it. If I do right click and format document, that's gonna tidy up for me. And let me zoom out a little bit just so you can see the full code. That's pretty much it. All right, now let's start our project actually and create a page. First of all, I'm already in my project folder here. And all we need to do is let's clear this. And all we need to do is MPM run depth. So everything seems to be working here. We have the localhost of 3000. And we are getting the EMV.local, which means that everything is looking good. Let's open this in the browser by doing control and press on it. And here we go. We have a working next.js application. Instead of using this page, I'm actually going to create a new one. And I'm going to leave the default styles. The default styles are located inside app and then global CSS. You can remove them if you want. I'm going to keep them as they are and just create a new page. So in order to create a new page, let's close everything. First of all, save this and inside the app, we can create a new page by creating a new folder. And then this folder is going to be called languages. As we're going to be displaying languages, and then inside this folder, we're going to have a page.js. So here is our page. This is going to be the year round. And this is where we write the actual page. Awesome. I'm going to zoom in one more time. And now let's create a very basic page just so we can test to do this, we can start with export, default, and then async function, call it page and create the function like so. Inside here, we return and then in brackets, we can do hello, like that and save. That's pretty much it. A very basic page. Now if we go to the browser and go slash languages, you'll see that we're getting hello here on the left side. Let's make this a little bit better. Let's put it in the middle of the screen. I'm not going to spend too much time on styling. So inside here, let's make some space. And let's create a div with the class name of container. Mx, auto, which is going to bring the whole container in the middle of the screen and a margin top of something around eight, what did the job? And let's close it. Put hello again. And then let's go back to the browser. And as you can see, the hello has shifted here on the left side, which means that a container is centerline. Now let's try to connect to a database and do a first query. I'm going to right click and form a document. I believe that I'm using pretty for this. And now here at the top, we need to bring or connect Mongo file. So the file that we created earlier from the utils connect Mongo. Inside here, we do import. And then we do connect to database. And then this is going to be from add utils connect Mongo like so. And this is all connection to the database. Now we need to create a function that where we can do all of their queries. So this is going to be an asynchronous function. And we can call it get data like so inside this function, we can start doing the queries. So for example, if we put everything into a try cast statement, we can do db connect const client equals, and then this is going to be equals await. And then we need to grab connect to database like so and start the function. That's it. That's how we connect to the database. And now we can use the client to select which database that we want to use. So I'm going to do const db equals client dot db. And then here we select the database. Early in this tutorial, we created the database and we gave it the name of program. And then we can do our queries. Before we do the queries, let's catch the error. And I'm going to do throw new error. And this is going to have a message of fail to fetch data. Please try again later and closer. Let's do a very basic query of basically getting all of their languages from the database. In order to do this, we can put it into a const of items. So const items, and then equals await. And we await for the database. So db. And then we need to select which collection. So the collection in this case is going to be called languages as programming languages. And then we can change the rest of the step. For example, we can do find. And this is going to find all the records if we put the curly brackets in here. And we need to do one more thing to array like so. That's it. Now technically speaking, if we don't have any errors yet, well, we won't because we haven't started the function, we should be able to get all of the items, but we need to return them. So what I'm going to do in a second, we're going to not only get the items, but we're going to get the amount of items. So we're going to do two queries. So what I'm going to do is put a const of response. So we're going to store everything in response. And this is going to store the items. And then later, we'll have one more, which is going to be the item count. We'll do that in a second. Let's start with this. And now let's bring the response. So I'm going to do return response like so. Let's do right click and format document that's looking a little better. And now we need to start this function. So let's grab the get data. And here where we have the export default async function inside here, we can call the get data function. You know to do this, I'm going to store everything into accounts data. So it comes data equals, and then this is going to be a weight and then get data like so. That's it. So this is going to start the function here and do the query for us. So now technically speaking, we should be able to use this data and then go and this data is going to have also this property of items inside it. So first of all, save this and look at your console, make sure that you have no errors. And as you can see, we have connected to MongoDB successfully, which is a good sign. Right. Let's go back. And now let's have a look at how we can look through this data. So inside here, let's remove the hello. And let's create, I'm going to tidy things up, remove the four spaces. I need to reset this. So indent using tabs, two tabs. Okay, that's much better. Now inside here, let's do an unordered list. And this unordered list is going to be very basic. But I'm going to wrap it in a grid so we can have multiple columns. And then this is going to be grid dash calls of four. So we have four columns and then gap between them can be four and then text center. Nothing special here. We just need to insert a few lists in curly brackets data. We grab in the data from here. And this data is going to have items. So we grab the items, so dot items. And then we map for them like so. And then we can do item. And this is going to be a narrow function, open and close to bananas. And let's make some space like so. And now inside here, we can create or list. So let's create a list. And I showed you earlier in the tutorial when we created the database that each item has a unique identifier or item ID. And we can put it here on the list as key equals item dot underscore ID. And essentially this helps react to find references to the appropriate note of the list. Otherwise, if you don't do it, you might get some warnings in your console. And then let's give this a class name background dash green of 500. It's not going to look the best, but it should do the job. And then round it MD parting or four and then text black. That's it. And inside here in curly bracket, we can do item dot name because we have because this comes from the database name. If you remember, we have the ID and the name here. So Python and JavaScript and so on. So we have the ID like so and the name. That's it. So now if I save this, hopefully we don't have any errors, let's go to the browser. And as you can see, everything is looking good, except we actually get in the list, which is amazing. And it's looking pretty cool. But the only thing that isn't working is the grid. So I must have misspelled something. So we have great. So I've misspelled grid here. So let me copy and paste it. So great grid goes for that's it. Save them. And now, yep, everything is now in a grid, as you can see, which is awesome. Now, let's do the other query is well. So as we are here, this is our first query. And let's do one more. And I want to be able to get the count of how many items we have in our database. So let's do cons and let's call an item count equals and we're going to do exactly the same thing as yes, our weight database dot collection. And then we select languages. And then in order to get the amount of documents that we have, count document, like so. And inside here, we need to put the curly brackets, oops, like so. And now we can grab this item count and put it in the response as well. Like so. And this should be also available when we get the data. I can grab this. So essentially somewhere on here, I can just just as an example, I'm not going to actually display but I can do data dot item count and this should display the item count. Let's save it. And here it is, we have 40 items in the database. Obviously, I'm going to remove this, but I just want to show you that's pretty much it. Right now that we have this working, let's have a look at how we are going to do the pagination. So essentially here, we have all of the languages, but we don't want to display so many, maybe we want to display eight per page. And the way we can do this, we can make links. And when we click those links, we can change the page here, the page parameters. So for example, we can have languages and then question mark and then page equals one. So on the first page, we're going to display eight items. On the second page, we're going to display the next eight items. And we can do this by first of all, we need to be able to grab the parameter from here, which is called page in this case. So let's do that and we'll build slowly on it. Essentially, to grab the parameters from the URL, we need to do it inside here. And where we have the page, we can just do in curly bracket search params. And this is going to allow us to get the parameter from the URL. So as an example, we can do console.log and then inside here I can do search params.page as this is the parameter we want to grab. So if I was to save this, and if I go to the browser, let's press enter. And now if I go to my console, you should see that we have two. If I was to change this to three, let's say, and if I click on my command line here, you will see that we're getting three. So that's how we get the parameters from the URL, which is awesome. And now we can store this as the page. So I'm going to remove this and give it a let page. And this is going to be equals. And then if I leave it as this, we're going to have a problem because this is actually going to come as string. And obviously, we're not going to be able to compare numbers with a string. So we need to convert this into a number. So in order to do that, there are many ways I guess, but I'm going to do it with pass int. And I need that here, we can do the search parameter of page, which is going to give us a number, hopefully. And then and then I'm going to do 10, which means that we're going to convert this into an integer. So as an example, if somebody puts on the URL, question mark page equals 4.9 for some reason, this is actually going to be converted to four. And if they put something like page equals 4.4.1, this is still going to be equals four. So that's pretty much how this works. So we're going to have one more problem here. And that is so first of all, we have this as an integer, which is great, but also somebody can put a negative number, which we don't want. So what I'm going to do is I'm going to grab this let or variable, whatever you want to call it, which essentially is going to be representing a number. Now this is going to be equals. And then we're going to check if the page is undefined, no false or zero. So we're going to do page or if the page doesn't have a value, so it has nothing. And let's check if the page is less than one, we have a question mark, which is a ternary operator for setting a default for setting a default value, in this case, one or page. I hope this makes sense. But now we're not going to get any new values. And we're not going to get any negative values either. The next thing that we need to do is figure out how many items do we want per page. And in this case, I'm going to do const per page, and I'm going to set this equals to eight. So if we grab this per page, which is equals eight, I'm putting it into the get data here. Now this is going to be available in the get data function. So I can put in here per page. And now we can modify or query. So the one that we want is where we have all the items coming in from. So it's this one items here, and we can maybe put them on another line, just so it's easier to read. And we can limit the results by doing dot limit. And inside here, we can put the per page number, which is set to eight here. And now if I save this, and if I go back to the browser, you will see that we're getting eight numbers, which is great. This still doesn't work. So I can change it to whatever you like, but it won't work just yet. Now let's make this work. In order to make this work, we can do exactly the same thing as the per page. So per page, so I'm going to grab the page variable here and paste it inside here. And then this is going to be available in the function here. So I'm going to put comma page. And now we can use it again inside here. But in order to get the formula right, we're going to have to do something a little bit more difficult. So inside here, we're going to do another MongoDB function, which is skip. And inside the skip, we want to do a little formula, which essentially is going to be per page times the page that we are on, which comes from the URL minus one. And this essentially calculates the offset because we don't want to start from, we start counting from zero technically. And this is going to be page two. Otherwise, if we don't have the minus one, that's pretty much it. Let's save this. Let's go back to the browser. And now here where we have page one, everything is looking good so far. If I push page two manually, you will see that operation is starting to actually work. Page three, page four, page five. And I think that's going to be the last one. So if I was to put, what can I put zero, if I was to put zero, we're going to get the first page. If I was to put one again, the first page. Okay, so everything that we've done so far is working. Wow. All right, let's go back. And now we can focus on the actual pagination links. Now we're going to have to do another formula for this. And we're going to have to do it inside here on our export async function. All right, the next step would be to do our pagination navigation. So the previous link and the next link. So in order to do this, I'm going to do const pref page. And then this is going to be equals or variable name here page minus one to offset it. So it's zero. And then if it's bigger than zero, we want to set it to page minus one or one. Then after this, we can do the next page. So that's going to be const. And this one is going to be easy. We're just going to do next page and it's going to be equals page plus one. But for the next link, we also need to calculate how many total pages do we have depending on the number and records. So what I'm going to do here is const const and then total pages equals and this is going to be math dot C I L. And then inside here, we can do data and then item count, which comes from the database here. We've got an item count. That's going to be 40 in this case. And then we divided by the per page, which is eight in this case. So essentially, in this case, to get the total pages, we are dividing 40, which is a total count by eight. And we should get in total five pages, like so. Save this. And now we can use these to do the navigation. First of all, let's start with the previous button. So somewhere around here, just after the you have, let's do a curly bracket page equals equals equals one. So if the page is equals one, we put the ternary operator and inside here, we kind of want to have a disabled link. So I'm going to put a diff with the class of opacity dash 60, just so we have something different. And let's put previous like so. And then if it's not, we want to display the actual link. So I'm going to do link press enter. And this shirt at import link from next JS link here. And now we can do href. And in single slanted codes, we can do question mark page, which is the parameter that we used so far equals an $ sign. And we can get the calculation from previous page like so. And close it inside here, we can just put previous. Hopefully, if I go back, you should see that we are getting previous. So if I put zero, first of all, nothing happens, which is great. Okay, if I remove them, nothing should happen. And we have the previous and it's not clickable. But if I put two, as you can see, now it's lighting up and we can go back. So let's go to page four, for example, and let's try to click on it. So back, back, back. And we are on the first page, which means that our previous link is working. So let's finish it up super quickly on here on the previous weekend at area disabled equals to true, just so we add a little more accessibility to a button. And on the link here, we can add area dash label. And then this is going to be equals previous page like so. And that's it. Now let's do the next button, which is going to be very similar. So I'm going to do it right here. And this time we're going to do page equals equals equals total pages. And then if we are on the last page, basically, we want to disable, we want to display a disabled div, just like he actually, so I'm going to copy this and paste it. And this is going to be next. But then if we are on any other page, we want to display the link. So it's active. So I'm going to do all and then inside here, we can display the link, copy paste. So this is going to be previous. This is going to be next page. And then next page. And then next, I think that's looking good. Okay. If I click next, next, next, next. And as you can see now, the next button is disabled, obviously because of the div it goes on the line, but we'll fix that. So on the fifth page is disabled. And on the first page, the previous is disabled as well. And now let me quickly wrap them up in a div just so they look a little bit better. So I'm going to do this with a class name of flex. And then just if I center items center and imagine top of 16, make sure that you close the div. And let's wrap everything here. Right click format. And then inside this div, which basically kind of like centers everything here in the middle. I'm going to wrap them with one more div with a class name of flex border. Let's just put a custom one of one pixel. And then gap can be gap can be four rounded can be 10 pixels border light green and then padding of four. Let's close this div, make sure that you wrap everything again, right click format, save it. And now we should have this kind of like border and it gives it all links a little more space. Now the next bit is going to be even trickier. Let's have a look at how we can do it. So if I go here, in this case, we're going to have five pages and I want to put the numbers here. So one, two, three, four, five. Every time we are on a certain number, let's say we're on page number three, I want the page number three to be highlighted. And I also want to offset the numbers so we don't display all of them. So this is going to be a little bit tricky, but I'm gonna, but I think I've made it fairly simple to understand. So first of all here, just after our next page, we can generate a list of numbers centered around the current page. So let's do const page numbers. And this is going to be an empty array. And now we want to create an offset. So in this case, const, let's say offset number. And this is going to be equals three, for example. Now, inside here, we can do a for loop. And then for this for loop, we're going to do let I is equals the page minus the offset number from here, minus three in this case. And then we can do if I is less or equals the page, we want to do plus offset number. And then I plus plus. And essentially now we want to check if we are not on the first page or the last page, we want to push the offset and numbers. So this is going to work like this. If I is bigger or equals the one and I is less and equals them total pages, then we want to push into this array pages, numbers, and we push I like, oops, and we push I like so. But essentially, we're just offsetting the page numbers with three either way. And now let's see how we can use this. So somewhere in the middle of or previous and next around here, we want to put the number and we want to loop for them. Let's start with curly brackets, page numbers, everyone to loop for them. So map. And inside here, maybe we can call a page numbers index is going to be giving us a unique ID that we can put on all links is going to be equals another function like so. And then we can just put a link. Close the link, everything is looking good. And let's just put href for now. And this is going to be equals in single slender quotes, question mark, page equals dollar sign. And then we do the page number. Sorry, page number, instead of numbers. That's it. And now we need to put this number inside here, otherwise, it's just going to be an empty thing. We want to display some page number. So let's go back. And as you can see, we have 12345 and they're all linked. So if I click on 12345 and so on. Now the easiest way to and by the way, the offset is working as well as you can see one is gone. But if I click on two, if I click one, now five is gone. Now when I highlight the current link that we on, let's say three, then you'll see the offset that then you'll see how the offset is actually working, which is pretty cool. So an easy way to do this is that we can give this link a class. So it's going to look a little bit ugly, but around here, first of all, we need to give it a key, which I forgot. So let's give it a key. That's why I put the index here. So they will have unique key and react doesn't scream in our console. Let's have a look. As you can see, check the top level render call Dave. Yeah, unique key. This is what I was thinking about. Okay, so we can fix that by doing the key index. And then let's give it a class name. And for the class name, instead of double quotes, we put curly brackets inside here, we can do some check. So let's say page, if the page is equals equals the page number that we are on right now, then with the question mark with the ternary operator, we can display if this is if we're on the current page. So this is going to be if we are on the current page and we can highlight the button. So background green dash 500, maybe font weight of bold and then pattern X of two rounded MD and then text black, like so. That's it. And then for the error, if we're not on this number, we can just do maybe hover and we can just do background light green. Let's tie the things up. Maybe I can just do right click format document. Yep, save. Let's go back to the application. And as you can see, now we are in page number three and this is highlighted. If I go previous, as you can see, goes page two, one and so on. And now we're disabled here. This is pretty cool. I think that's pretty much everything. I really hope that I didn't miss anything. Hopefully this should just work now. And maybe the last thing that we can do is at the moment we have five pages, right? And maybe if somebody puts page six, somebody is trying to do that, we could fix this as well. Let's have a look. Well, an easy way of fixing this could be around here where we have the next page, we can do one more. So let's do const and let's say is page out of range and then we can do equals. So if page is bigger than the total pages, we don't display anything or we can, well, you can decide what you want to do, but we can now get this const and wrap everything inside here. So potentially, I mean, I didn't really plan this, but potentially can this page out of range, you can do a ternary operator and maybe you can display div normal pages. I don't know, something like this. And then if you put all inside here is where we put all div. So I don't know where it starts. So we have two divs. Okay. So we need to grab two divs and put them inside here. Save. Now, no more pages. I mean, I don't know what else to put, but if we put zero, it should totally work. If we don't put anything, it should totally work. If we start navigating, everything's working and somebody puts 55, no more pages. I don't know what you want to do here, but maybe you can handle it in a better way. And I think that's going to be everything from this tutorial. It's not an easy thing to do. It's a little bit confusing, but I hope that you found somewhere useful. And thank you very much for watching. Consider subscribing. I'll see you next time. Bye.