Skip to main content
View on YouTube to comment and like!

Syntax Video

Create your own Next.js Starter Template

Chapter 1 0:00

Intro

there has been a lot of talk recently about nextjs and what you get out of the box whenever you decide to create an app with it and it's very often compared to things like laravel which come with a lot of things built in and uh a lot of people that have tried laravel kind of see it and see the fact that when you're working with nextjs you kind of have to set all this stuff up yourself Lee has a really great post where he talks about why that is in the world of JavaScript and ultimately it comes down to the fact that we have a lot of choices which can be a good thing but ultimately you have to make those decisions when you're starting a project to actually be productive and not spend all of your time picking libraries and setting things up every time you decide to go build a new application now in this video we are going to talk about nextjs what it includes and I'm going to show you how I build my own starter kit and how I pick and choose all of these various libraries so this diagram here kind of shows you what you get out of the box anything in red is something that you don't get out of the box and you potentially have to make a decision about when you're deciding to build an application with nextjs and really we're

talking about production ready applications software as a service applications internal tools not just blogs and landing pages things that get real work done and have real features require a lot of this stuff now obviously in a single video I'm not going to be able to set all of this up but I am going to show you my process of how I chose these various libraries to fill in these gaps and also I'll show you how I set them up so that sounds good to you let's dive in my name is CJ welcome to zintex [Music] now before we go creating our own starter kit let's actually take a look at the landscape of what exists out there today so if you just head to GitHub and search for nextjs starter or nextjs boilerplate or nextjs template you're going to get a lot of results and it can be very hard to determine if any one of these starter kits are for you so I've filtered them down a bit and I'm including starter kits here that have at least 1,000 GitHub Stars they're actively maintained they have some style solution or UI framework they include a database and they include off I'm not

Chapter 2 1:36

Existing Solutions

including things that are just blog starters marketing sites or landing page templates I really just want to have a good list of things that are production ready and give you all the base things that you need to build an application now this obviously isn't an exhaustive list and if you know of others definitely leave a comment down below and people can check it out and also leave a comment on this GitHub gist which I'll link in the description and I'll add it to the list uh but this has a few that I am going to point out here and first we'll start with CLI generators now these are great because they pretty often allow you to make decisions as you're generating your app about which specific types of libraries you want to use for all of these various things whereas boiler plates and starter kits make all of those decisions for you and you're essentially just cloning down their repo and probably the most popular generator that's out there is create T3 app which is essentially a CLI tool that will scaffold out an application for you and you can choose what do you want to use for your database drizzle or Prisma do you want to use trpc should it set up authentication for you and so a lot of people have gotten really good mileage of using T3 app and their CLI tool now

Chapter 3 2:22

Next.js CLI Generators

another one that is more recent is keramas and it looks really cool and so similarly it lets you scaffold out an app but what's interesting is you actually start with create next app so you can guarantee that every project you start will at least always be as up toate as create next app is which is very wellmaintained and does stay up to date but then from there it's a CLI tool that works within that codebase to add and generate new things that you might need like an omm or authentication or setting up a component library and various other things as well and another thing they provide Beyond just setting up these libraries for you is a generation command and so essentially this can scaffold out models views and controllers and if you check out this video by Nico you can actually see how it works essentially you can run one command and it generates the database table it generates the queries it generates the page and they can have like nested models and stuff like that and so this is the kind of thing that I like to see that will really allow you to move quickly when building applications with nextjs so definitely check out keramas now another CLI I came across is called super plate and you can

see on their landing page that they support a ton ton of libraries and Frameworks and specifically if you look at the nextjs section you can see that you can use their CLI to add all of these things to your nextjs app the one thing that does seem to be missing though are things around like database and authentication and authorization but they actually do have a really cool plug-in system so it would be possible to create your own custom plugins that add those kinds of things to your nextjs applications so super plate seems pretty cool as well now lastly there's the INX CLI so INX is a monor repo tool but they also have project generators for all kinds of things not just nextjs and I'm including it in this list because if you're already working in an NX mono repo they have a way of getting up and going with a next app inside of that monor repo very easily and they do have a couple of sub generation commands that can generate like pages and components for you but this does not come with like a UI library or off or database setup or anything like that but it does include a few more things than you get with just the create next app CLI now next up we have starter kit and boilerplate repos

Chapter 4 4:53

Starter Kits and Boilerplates

so essentially to use these you would literally clone down the repo and just start working from the codebase that they provide now I'm not going to go in depth on all of these but I essentially went through and found all of the ones that have like at least a thousand GitHub stars and are regularly maintained and updated like this one was last updated 3 days ago four days ago last month yesterday so all of these are actively maintained and that's the one of the things you want to look out for when choosing a boiler plate because packages go out of date very quickly right and if someone is not on top of keeping that package.json up to date and also like fixing any breaking changes or anything like that that base codebase is going to go out of date very quickly so check out this list you can see all of the libraries that they include but you just want to make sure whatever kit you choose is up to- date and maintained now next up we specifically have SAS starter kit so this is software as a service and typically this is a starter kit that also has like stripe integration so you can start accepting payments and also thinks about the idea of like multi-tenancy where you potentially are going to have multiple entities that are all using your application but their

Chapter 5 5:38

SaaS Starters

data needs to be separated in a certain way these starter kits try to handle that now now a very recent one is from Lee Rob and he's been working on this in public you can see his last commit was 54 minutes ago now Lee actually works at versell and works on the nextjs documentation so if you had to trust one of these starter templates I would definitely trust this one because it's actually coming from somebody that knows the framework really well but it is fairly new and and Lee is still working on it but this one is definitely worth a look now there's a few others here like I said I'm not going to dive deep into them but they all have some way to accept payments and then also a lot of them have things that will help you out with sending transactional emails like this one includes react email and this one includes like web hook orchestration and integrating with an audit log service this one has a focus on multi- tendency and this one includes other things you might need like internationalization or error handling with Sentry so they're definitely all worth a look especially if you already have some opinions about maybe what kind of database you might want to use or whatever else so you can pick your starter kit accordingly and then there are also paid offerings so these are

Chapter 7 7:47

Toolkits / Wrappers

here is Blitz JS now I've talked about it a little bit on the channel before but they call themselves The Missing full stack toolkit for xjs so it's not a starter template it's not a boiler plate essentially you still are building an xjs application but there are quite a few libraries and helpers behind the at Blitz JS namespace that provides a lot of the things that you typically need in an application like authentication and like RPC and like multi- tendency and like databases so it's cool to see that projects like this have popped up because it's basically just another layer on top of nextjs and one of the things about starter templates and boiler plates that I'm not necessarily a fan of is the fact that you have all of this setup code that you potentially only ever touch once but it exists in every single one of your applications and so a project like Blitz is essentially abstracting away some of that setup so that way you don't even have to think about it you can literally just import it and so I definitely like that idea as well now the last one to check out here is refine and this is really more than just like a CLI and a tool it's more of a an ecosystem and it

works with more than just nextjs this diagram kind of shows you what you can get with it where basically you have all these different kind kinds of platforms that you might be building with like nextjs and all these different kinds of UI Frameworks and off providers and data providers and real-time providers and Integrations and access control and refine essentially allows you to bring all of those things together in a very streamlined way so it's definitely worth checking out as well they have this whole idea of like data fetching and data loaders and you essentially use it inside of your nextjs application but it's a lot more opinionated so it can take care of some of these things as well so refine is definitely worth a look now like I said if there's something that should be in this list but is not leave a comment down below I'll be sure to add it and at this point we're not going to talk about existing Solutions anymore we're going to build our own so the rest of this video is just me setting up an xjs app from scratch and making all of these decisions about the pieces I need to have a production ready codebase so everything in blue here you're going to see me setting up in this video and I'll also talk about why I made a specific decision about the library that I'm choosing now of course you may not like the decisions that I'm making in this video but that's why I'm showing you my

Chapter 8 9:28

Lets build!

process because if you want to do the same thing you can go through and build your own starter kit that works for your company or your team so definitely check the description where there will be time stamps to all of the sections of the video where I am not only setting these things up but also talking about why I chose a specific library now the first part of this video is all about getting really good base settings for ES lint prettier tailwind and typescript and VSS code and making them all work really well together so even if you don't agree with the libraries that I choose for the other parts of this video you definitely can find something useful in this section of the video that just really talks about code formatting and linting and code style first let's generate a nextjs app so I'm going to copy the command here from nextjs dorg run it in my terminal and we're going to call this next start we're going to use typescript will be using eslint and prettier which we'll set up next we're going to be using Tailwind I like to put all the code in the source directory this makes it easier for any sort of Dev command that specifically needs to look at source files and that way all of our configs are at the root but our actual

Chapter 9 10:08

Code Style / Editor Settings

Chapter 10 10:30

Generate next.js app

source code is in the source directory so yes be like the source directory also going to use the app router and we're going to use these import aases but we're not going to customize them and here we go now let's CD into that directory that got created and open it up with vs code you can see our app gets generated with this eslint rc. Json now this has some good defaults essentially next typescript has all of the recommended settings for eslint but eslint is for linting we want to also add prettier for formatting so let's do that now you can see in the nextjs documentation they tell you how to set up prettier essentially we can just grab the eslint config prettier package and install it so I'll head to my terminal run that command and now we can add this to our esent RC So within our ESL RC we're just going to add extends prettier here by adding prettier here we're essentially disabling any esent rules that might conflict with our formatting rules that are enabled by prettier let's create our prettier config I'm going to create a prettier rc. Chason and I'll specify my preferred prettier settings

Chapter 11 11:14

prettier setup

now this is where you might actually diverge from my preferred settings but I prefer semicolon so I'm going to set that to true and then I like double quotes so I'm going to set sing single quote to false and I like a tab width of two and then lastly I like a trailing comma to be compatible with es5 so these are my preferred formatting settings again yours may differ but just set those up inside of your prettier RC and now I'm just going to do a quick reload of vs code and this should allow everything to kick in now next up there are a couple of linter rules I can enable that are not formatting rules and this is one of the main reasons I still like to use es lint and not just prettier so let's take for example using regular functions as call back so let's say I have an array and then I do like a for each and then I pass in a function here okay great I have a little Anonymous function we're logging out every item from the array but one of the things I prefer in my code base is if I have an anonymous callback I want that to be an arrow function instead of a regular function and there's actually an

Chapter 12 12:19

Enabling eslint rules

esent rule that can automatically fix that for us so if we go to our esent config and then add a rules section there is a rule called uh prefer eror call back and I'm going to set this to error so once I do this now we get a lter error that says hey you should use an arrow function and if I run eslint fix all autof fixable problems that automatically converts any Anonymous functions in callbacks into Arrow functions inside of callback so that's great and again this isn't a formatting rule this is now an A linter rule but I like the fact that it can be fixed automatically with that specific linter Rule now another linter rule I like is to prefer template literals so let's say I have like a first name variable and then I have a last name variable and then I want to combine these together into a a full name variable and so you might do something like first name plus space plus last name and then we'll just log out that full name okay awesome now technically there isn't anything formatting wise wrong with this code but

if I want to use template strings everywhere there is a linter rule for that so if we head back over to our eslint RC here we can say prefer template and set that to error and now with this you can see that it's saying hey some unexpected string concatenation you should use a template string instead and again this is automatically fixable so if I run command shift p uh fix all autof fixable problems it instantly converts that into a template literal so that's great now a couple more rules I like to enable which is not a popular thing to do is I actually want to see an error if I don't have semicolons or if I'm using the wrong kind of quotes now typically you use something like prettier because you don't want to have to worry about format errors like quotes or semicolons but personally I do like to see in my file if I'm missing a semicolon so we can just add that rule here inside of our eslint RC so inside of here I can say semi and then set that to error and now inside of the document if I'm ever missing a semicolon I actually see a lter error that says I'm

missing a semicolon now again you may not want to see this rule just don't enable that rule if that's the case and the other thing is I like to see a lter rule if I'm using the wrong kind of quotes So if I have single quotes here I actually want to see a lter rule that says you should use double quotes So for that we'll add a rule that says uh quotes and we'll say error for double and now you can see I get a lter error that says it should use double quotes but again if we run es lint fix all autof fixable problems that'll update that to be double quotes now I don't want to always format and lint manually I actually want my Editor to do this for me whenever I save the document and for this we can specify some vs code settings so in our directory here I'm going to set up a vs code folder and inside of there I can create a settings.

Chapter 13 15:15

VS Code Format / Lint on Save

Json now I like to specify these settings specifically inside of the project because if any other developers are working on this project they're going to get these exact same settings instead of having to set them themselves inside of vs code the first setting is to just format on save so I'm going to set editor dot format on save to true so anytime I save the document it's automatically going to run prettier and then I also want it to run eslint fix all autof fixable problems every time I save the document as well and so for that we have editor. code action on Save and in here I can say source pixall and set that to always and now check this out whenever I save the document things will be automatically updated so let's say I go back to where I had like the function here and then this was actually uh string concatenation and then maybe up here I was missing a semicolon and I'm using a single quotes Okay so there's there's a bunch of stuff wrong with the document if I press save boom it just fixes everything automatically now next up another linting formatting rule that I

Chapter 14 16:26

prettier sort imports

like is to automatically sort the Imports at the top of a file because this can get really messy if you have like Alias Imports and relative path Imports and thirdparty libraries and they're all kind of like intermixed at the top of the file you can sort these in a specific order and for this I like to use this prettier plugin sort Imports and what's nice about it is it can essentially group things into specific areas and there are rules and regular Expressions you can specify to sort them into specific areas so you can see that if you have some code that looks like this you can set it up so that thirdparty libraries are at the top and then you have some Alias server Imports here and some other Alias Imports here and then relative Imports here and it can put a space between them so it's nice and clean and easy to look at if you ever need to go back up and modify those Imports so let's add it to the project I'm going to install it and then from there we're going to add it to our plugins inside of our prettier RC and then we can specify our sorting settings so I'm just going to copy the settings that they have specified in their Docs

throw those there so import order separation means it's going to put a space in between the different types of imports I prefer that you can turn this off if you don't like it and then import order sort specifier says that within each group of imports it should sort them alphabetically and then lastly import order is where you can specify the order of how things should be sorted and by default thirdparty libraries are always going to be at the top of the file and if you want them elsewhere you can specify within this array and I'll show you that in a second but with this you can see that any relative Imports are always going to come at the end so so if we take a look back at this file and let's say I put that relative import at the top and let's say I put this there whenever I save the file it's automatically going to sort them you can see that it put the relative import at the bottom and then it sorted these Imports in alphabetical order so if I swap them in this way they're always going to be an alphabetical order now to see more of these rules kick in let me actually create some other files so here in the source directory I'm going to create a folder called components and then for now I'm just going to create an example component so I can show this working this will just be a super simple

component okay so now let's say I want to import this example component into this file I can import it using an import Alias so if I say import example from I can do at slash and whenever we generated our nextjs project we specified that we wanted that default import Alias so now with the at sign anything inside of the source directory can be imported so I'll import components SL example just like that and then we'll use this component for now just like right there if I save the file it actually pushes that import to the top because it doesn't know that this is an import Alias it just thinks it's a third party Library so to fix that we need some custom rules and these rules that it has here are going to vary depending on your type of project I actually don't use this convention in my project like core server or UI so I'm going to remove those and specifically add a rule that looks for things that are Alias with at slash and so here's a nice little regular expression that says if the import starts with the at sign followed by a slash followed by anything else that should appear before any

relative import so if I save that come back over here and and save the file now you can see I have a section for all of my Alias Imports now lastly one of the things I like to do is put everything that's related to react or nextjs at the very top of the file then any third party modules after that and then our Alias Imports and then any relative path Imports and that looks like this so essentially this is a regular expression that says if an import comes from react or from next or next SL something that should appear at the top of the file followed by any thirdparty modules that's anything that you installed from npn followed by Alias Imports followed by any relative path Imports and so now if I also let's say imported from low Dash I don't know we did something like this uh whenever it formats this it's always going to put it in that specific order so we've got next to react third party Alias and then relative Imports now you can customize this order to your heart's content what I see a lot of people do as well is not only just have Alias Imports here but you might separate these out so depending on what your directory starts to look like you

might say oh well I want to see all of my components listed above any other relative Imports or maybe I have some utils and I want those to be listed here um or maybe I have some Hooks and I wanted those I want those to be listed here so you can specifically choose where you want those to appear and in what order for my app I just like to have all of my uh Alias Imports in one spot because I know anything that's Alias is going to be coming from my app directory and they're ultimately going to be sorted in alphabetical order anyway so they're going to be grouped uh all in one section now our last prier plugin is specifically for towin now you may not know this but the order of classes inside of your class attribute actually doesn't matter what matters is the order that those specific classes are defined in in the CSS file and this plugin takes into account the order that they're defined in inside of tailwind and automatically sorts them in that specific order so you'll see which classes actually have precedence because they'll be in the order of how they're actually defined in the generated Tailwind CSS if you're not following

Chapter 15 20:54

prettier tailwind plugin

just read this article explains it a lot better um so we're going to install this specific plugin here and then we're going to add it to our plugins in our prettier RC so we're going to copy that we'll throw it on here now that I have that plug in added I'm just going to reload vs code to make sure that all of those settings are picked up and now if we take a look at our page. TSX you can see that it has quite a few Tailwind classes inside of here and if I save the file you'll see that it actually Resorts these classes because actually Min height screen is technically defin before some of these other classes that are in here and because we enabled autof format on Save anytime you save the document no matter what order you put those uh tail in classes in they're automatically going to be sorted in the proper order so yeah this plugin is great make sure that you're actually defining these in the order that they're defined in so you don't run into any weird issues where you're thinking that you're overwriting something when you're actually not now lastly let's set up a script that will actually run prettier on all of our files so we head over to package.json so here I'm just going to add a task called format we're going to

Chapter 16 22:12

format script

run prettier specify that it should run on the source directory and then it should actually write those files so after formatting overwrite those files with the formatted codes so now that I have that script if I run mpm run format it's going to look at all the files inside of the source directory and and if there needed to be any sort of formatting changes it'll overwrite them now next up is a linter setting we can add that will prevent us from running into case sensitivity issues now this was inspired by the nextjs FAQs so these are FAQs from the nextjs Discord I highly recommend you check these out because there's a lot of good tidbits of info for when you're working in your nexj app but this one specifically talks about module not found cannot resolve some module name and it talks about potentially using camo casing whereas when you're on a Case insensitive operating system like Windows it doesn't differentiate that versus all lowercase some file. js and so because of that the recommendation is actually to always use lowercase and to use Kebab case naming for all of your files now they even mentioned that this isn't popular in the

Chapter 17 22:41

eslint kebab-case rule

react Community but I've been using it in my projects and I like it it actually looks a lot more consistent and I know for some people seeing Kebab case is a lot easier to read than camel case now to implement this we're actually going to take a look at the bulletproof react repo so if you haven't heard of bulletproof react it is a GitHub repo that has recommendations for how you should work inside of a production react and now nextjs codebase so just last week Allan updated the guide to also have recommendations for the app router and Pages router in nextjs but they have a section that talks about file naming conventions so let's take a look at it so if you go to their repo they have a bunch of different sections on Project standards and structure and testing and all the stuff that you should care about in a production code base and maybe if you don't have your own opinions yet you can actually take a look at this repo and it will give you the opinions that you need and for this we're going to take a look at the project standards section here in bulletproof react and they actually talk about eslint and prettier and give you some example codes for setting up your own configurations but down here at the bottom they talk

Chapter 18 23:31

bulletproof-react

about file naming conventions and there's actually a plugin for eslint called check file where you can add a rule that specifically says files should be Kebab case so let's set this up we need to install esent plug-in check file if we search for esent check file on npm you can find it eslint plug-in check file and then we'll just need to install this and then we're going to throw these settings at the bottom of our rules here in our eslint rc. Json file uh but this actually needs to be in Json format with like double quotes so I'm just going to convert this really quick I just found a random online converter to throw these in nice now I have like a nice copy pastable Json version of that so if we put it in sweet looks good and so now any file we Define has to use Kebab case or we're going to get a lter eror and then also any folder we Define will have to have Kebab case as well now this is specifically saying that you can have a directory called tests with beginning and ending with underscores I don't use that so I'm just going to make make this say that every directory should use

Chapter 19 24:31

eslint-plugin-check-file kebab-case setup

Kebab case like that and then for these rules to actually work we need to specifically add the check file plugin here to our R C file so we throw this in so now with that plug-in installed and these rules enabled let's see if it works so for instance this component let's actually rename it to example thing using camel casing and you'll notice immediately uh we get a giant error inside of the file that says the file name does not match Kebab case so if I really wanted to call it example thing I would have to do example Dash thing like that and then the linter is happy now if you're not used to Kebab case this might take some getting used to but person personally I I like it a lot I actually like the consistency because seeing these lowercase file names which is the nextjs convention combined with capital camel cased files once you have a bigger code base it's harder to to parse when you're like looking at your list of files with Kebab case it's nice and separated and and easier to read so I actually prefer it I I recommend uh giving it a try um but

especially so that you don't run into these weird file naming issues if you have developers that are working in in different operating systems now another great set of rules that they provide for you in bulletproof react has to do with project structure now I'm not going to enable these in this specific template but I definitely recommend you give this a read because it talks about what your top level folders should be and can be and then from there it has some specific rules about preventing imports from various parts of your application because if you start to structure your application in terms of features then you can prevent this import spaghetti where like this feature imports from that feature by having these rules is enabled and make it so that if this thing needs to import the same thing as that thing it actually just needs to be moved into utils or some standardized location so definitely take a look at these I'm not going to enable these in this project but it's definitely worth a look to prevent that like import spaghetti across your application now there are a few more project-wide settings I can set inside of my

Chapter 20 26:27

bulletproof-react Project Structure Rules

Chapter 21 27:15

remove unused imports

settings. Json file here and this next one makes it so that if I have any unused Imports inside of a file it automatically REM moves those cuz typically it's like unused code so I can say source. organize Imports set that to always so let's say I was importing uh cach from react for some reason but then like I'm not using it anymore now you can see I have a lter error which says cash is declared but its value is never read when I save the file it's automatically going to remove any of those unused Imports and our last project setting has to do with CSS so if we take a look at our CSS file you can see that by default these tail and directives are unknown and we're getting an editor warning but we can tell vs code when it's looking at a CSS file it should use Tailwind so inside of here we're going to add files. associations and we're specifically going to look at any CSS files and tell it that it should use Tailwind CSS and now when I'm inside of a CSS file I get autocomplete with tailwind and it's aware of it and I

Chapter 22 27:49

tailwind support in css files

don't get any sort of weird warnings or errors now another project setting has to do with the version of typescript that's running inside of vs code and because we're using typescript with nextjs we want to make sure that the version of typescript running nvs code is the same version that nextjs is using and so if you look in the nextjs docs they tell you how you can do this so inside of VSS code if I have a typescript or TSX file open I can press command shift p search for typescript select typescript version and you're going to want to choose use workspace version and you can see that VSS code's version is 5.5.4 but the version installed by nextjs is 5.6.2 so we'll select that and you can see that in your settings. Json it added this section here and a typescript we can enable specifically inside of nextjs has to do with statically typed links so in our next config if we set experimental typed routes to true then whenever we're dealing with the link component we'll get type errors if the href doesn't match a specific path within our application so I'm going to open up my nextjs config and inside of here we're

Chapter 23 28:20

Project typescript version

Chapter 24 28:56

Next.js Typed Routes

going to set experimental typed routes true now with that setting if I'm ever using the link component I'll get a type error if I specify a path that doesn't actually exist within my application now when you're working in the nextjs app router every single page is called page. TSX and every layout is layout. TSX and also you might have components that are in a folder and inside of there you have index. TSX if that's the case you might benefit from this VSS code setting so essentially what it does is it makes it so that the tab bar displays the name of the page with the word page and the name of the layout with the word layout instead of seeing the full path so you don't see a bunch of page. TSX all over the place now personally I don't even use tabs inside of vs code but if you do this is a nice setting to enable now at this point let's just clear out all the extra stuff that I'm not using so I'm actually just going to delete this components folder for now and then in my layout I'm going to get rid of everything including the local fonts

Chapter 25 29:28

VS Code Tab Name Settings

Chapter 26 30:01

Clear out extra code

also set up my metadata and then remove any of this extra stuff here get rid of that example component cool so nice and basic layout here and then on our main page I'm just going to get rid of everything and just have a nice little hello world and so if I start up my next app you should see Hello World great uh but you can see it has some default Styles where it's setting like the background color uh to Black and the foreground color to white so if we look in our global. CSS I'm actually just going to remove all of these default Styles because we are going to be installing a component library that sets all of our styles for us just like that we have no Styles it's just the basic Tailwind reset another thing is let's just get rid of the fonts that got installed and then also this default versel favicon and uh one of the fun things we can do is we can actually set our favicon as an emoji so there's actually this CSS tricks article that tells us how we can do it basically you do it by specifying an SVG that has an

Chapter 27 31:01

Set custom favicon

emoji inside of it so we can copy this link and then here inside of our layout we'll throw it in the head give it a closing tag and then specify the Emoji that we want to use and I'm actually just going to choose the package Emoji because this is a starter kit with a package and such cool so now that I have have that um I go back to my app you can see that the favicon here is set as that emoji now from here I'm actually going to start installing specific libraries that I like to use for like UI components and authentication in my database and I realized that you might not make those same choices so I'm actually going to put this bass setup with all of my es lint settings and prettier settings and project settings on a branch called bass so if you want to look at that without seeing all the other stuff that I install and set up it's going to be a specific branch called Bas in the repo that's linked in the description next up I'm going to set up a Tailwind based component library now our app is already ready to go with tailwind and if you're not familiar with Tailwind it is essentially a CSS utility library but Tailwind doesn't give us any pre-built components they essentially

Chapter 28 31:33

base setup branch

Chapter 29 31:58

What is tailwind?

give us utilities we can use to build our own components and the best example of this is to kind of just look at what they show in their documentation that talks about what Tailwind is and so in a traditional CSS framework you might actually have some class names like chat notification or whatever else but if you you look at the Tailwind implementation there are no class names they are just a bunch of utilities so we have P6 Max width margin Auto background white and so all of these are utility classes that are provided by Tailwind that essentially allow us to style with CSS but without having to directly specify classes inside of a CSS file now there's a lot more to Tailwind than just that essentially it's also a design system so even though we see p-6 that's a padding of six but that doesn't mean six Rim six is a unit in their design language so it actually means 1.5 but once you get used to their design system um it's nice and easy to use and all of your CSS is kind of scoped to where you defined the components now I'm not here to sell you on Tailwind we are going to use it and

we're already using it but I want something more than just these utility classes and for that I am going to choose a component library and essentially component libraries take the building blocks of tailwind and give us reusable components so we don't have to write everything from scratch uh whenever we're using and defining comp components now sometimes we will if we want to customize it but it's nice to have things that come out of the box already styled so we don't have to build up button styles from scratch now one of the most popular component libraries out there is a library called Shad CN UI you've probably heard a lot about it recently especially with the launch of their CLI and integration with vzer but essentially they give you components that are ready to go you don't have to assemble all of the Tailwind classes yourself so for instance if I want to add this button to my app all I need to do is import it and then I get a nice styled button that also supports like other variants like secondary destructive outline and um I don't have to write all the custom CSS for that but the thing about Shad Cen is all these components are very minimally styled and

Chapter 30 33:12

Tailwind Component Libraries

Chapter 31 33:36

shadcn/ui

so I would say Shad CN is a really good choice if you have your own design system or branding in mind where you want to take these base components and highly customize them to fit your specific look and style of the kind of website that you're building uh but they provide a really good base and the interesting thing about Shad xen also one of the controversial things things about it is you aren't actually installing the library they have a CLI tool that literally copy pastes the component code into your application so if you look at this manual tab here literally this is all of the code required for this button component and this file will live inside of your codebase but because you have direct access to the source code you can modify it and customize it to your hearts content so that's what shads in is really good for essentially they give you the base Styles and base components that you would then further customize within your app and again every single one of these components if you bring it into your application that source code is going to be living inside of your application it's not an mpm dependency definitely take a look at their introduction they have an FAQ that talks about all those things uh but for me

Chapter 32 35:09

NextUI

specifically a lot of the apps that I build I'm not designing all of the styles from scratch a lot of times I'm building like a quick prototype or I'm just trying to get some internal tool ready to go and I don't necessarily need highly custom Styles and because of that I'm actually going to choose a library called Next UI now this actually has no relation to nextjs it's just called Next UI but it's a component Library based on top of Tailwind that has some default Styles so if we take a look at these buttons they're a little bit more stylized right they don't look as plain as like the shadan ones and essentially if you pull these components into your app you're basically saying your app's going to look like this maybe with a few slight modifications because of course you can always customize the styles by adding new Tailwind classes but these give you good styles by default like if we look at the card component we can see a lot of like highly stylized elements that are pretty much built in and ready to go now this library is installed as an mpm dependency and whenever you need to use one of their components you're actually importing from nexi org um but of course you actually don't have any

way to modify the source code of this button component the only way to customize it would be through like the props that they make available and then of course you can always pass down custom CSS classes and if you take a look at their section here called overwriting Styles they talk about basically the mechanisms they provide for customizing it but because you don't have direct access to the source code for it sometimes s your customizations might be limited and for the apps that I'm building that's completely fine most of the time I'm just going to be using the default Styles provided by these components but it's really great that I don't have to add any of my own Tailwind CSS classes for most situations I can literally just import the component in and it looks good by default I might add some maybe like padding or margin or layout styles to customize my app further but the base styles of all these components are essentially what I'm going to be using and this is how my application is going to look when I choose these components now a few other popular libraries you should take a look at are headless UI headless UI is very similar to Shaden and that they are completely unstyled they're very like

Chapter 33 36:58

Headless UI

minimal generic Styles and essentially these are more interactive components that need some JavaScript behind the scenes and if you take a look at them you actually do import directly from the installed library and they give you these reusable components but they're completely unstyled and you can look at their docs for further styling them and like I said they actually don't provide a ton of components cuz they're ultimately providing some of the JavaScript functionality you might need for more interactive components because if you are building out your Styles completely from scratch you wouldn't necessarily want to implement all of the functionalities of these types of components from scratch yourself These are nice CU you get some base functionality and then you can further customize the Styles and and move on from there uh but there aren't a lot of components included because it's expected that you're likely going to be styling all of the other things yourself from scratch with Tailwind now the last two I'll point you to are flowy react and Daisy UI give them all a try um and pick the one that you like the most but specifically for my starter kit I'm going to be using next UI I have been testing out all of these libraries and this is the one that I like the most it

Chapter 34 37:52

Flowbite / DaisyUI

has most of the components that I need the Styles look good by default it's customizable in the way that I want to and it works really well with react server components so this is one of the other aspects of choosing one of these component libraries is if they are have not been updated or they're not aware of this idea of server and client components it might make it so that anytime you want to use one of their components you literally have to only import it inside of a client component and that gets really cumbersome especially if you just want to like show a button inside of a server component for like flow bite and Daisy UI these haven't been updated yet to support react server components so any component you want to use has to be inside of a client component but that is not the case with next UI you can actually use these components inside of server components and all of their components have the ability to be serers side rendered now there are probably a lot of other libraries based on Tailwind that give you react components that I didn't mention and maybe I don't even know about let me know down in the comments if you know of a library that you like to use that's based on tailwind and gives you react components but for my starter kit I'm going to be using next

Chapter 35 38:12

Component Library RSC Compatibility

UI so that's what we're going to set up in the next section of this video so to get started with next UI we'll head to their documentation and they have an installation section now they actually have their own CLI which allows you to generate different types of react and next applications but I tried it out and it generates a lot of extra stuff that I don't necessarily want in my app I kind of want to be in control of of most of the things that get created so we're actually going to go the manual route but you should definitely check out their CLI if you're interested to see how they set things up but if we head over to manual installation we can install the packages that we need now because I am using pnpm I do need to add this to my npm RC so I'm going to go ahead and do that so here in my repo I'm going to add a npmrc file throw that in there and then we can install the dependency so I'm going to add next UI or react and framer motion now since I just updated my mpm RC to change that pattern there we do need to run a pnpm install first which is going to recreate the directory with that new setting and

Chapter 36 39:08

Set Up NextUI

then we can install next UI now we can set up Tailwind so if we open up our Tailwind config we essentially just need to tell it that it should look at the nexi components as well so we'll head over here and you can see this Tailwind config got generated when we created our nextjs application um but all of my code is going to live in The Source components directory and Source app directory I'm not using the Pages directory so I'm going to remove that and then I'm going to add the next UI org includes here at the bottom now we are going to be using dark mode and light mode so I want dark mode set to class and then we can pull in the next UI plugin so we're just going to set that here and then we can import next UI like that now these settings here were actually generated whenever we created our next app we don't need these so I'm just going to set these back to empty great from here we need to set up the next UI provider essentially any next UI component needs to be a child of the next UI provider so we're going to set that up inside of a provider's component and then wrap our entire application in

that so if we look at layout. TSX this is the main entry point for any page that gets rendered or any component get that gets rendered in our app and we want to wrap this in all of our providers so let's actually create a provider component I'm going to create a folder in Source called components and then I'll create a file in here called providers. TSX then we'll export a function called providers and this is going to take in some react children so we'll add children here and then we need to pull in that next UI provider and wrap the children in that so we're going to return we'll grab our next UI provider import that and then render the children inside of it now we can set up our props here essentially children is just a react node so I can just call this a react node and then import that from react so this provider component is going to include all of the providers that we might need as we set up the other things inside of our application and so we're actually going to include this in the layout so now that I have this component over here in my layout I'm going to grab grab my providers like so and then we'll render the children

inside of there make sure you import it from components we should be good to go now to test this out let's actually just try adding a button to our homepage and see if it renders in the correct way so to do that we just need to import the capital B button component so over here in my codes let's go to the page and we'll make this a capital B button instead of an H1 and then I can import that button from next UI so we'll save that start up my app and see if we get a button and we do so next UI is set up we can start importing components and using them in our app now let's get a basic layout so I essentially just want like a navbar and then a main area so I'm going to grab the Navar component and there's a couple of different things you can do with it so by default we just have like a Navar at the top with like a logo here and um the one that I want to do is the one that will automatically collapse on smaller screens like this so you can see that when you're on a smaller screen you get a menu that looks like that and then on larger screens you show the links there so this is what I would like I'm just going to go ahead and copy this entire example and pull it into my own

Chapter 37 42:30

App Navbar Component

component in my app so let's do just that here in the components folder I'm going to create a new file called app navb bar.txt SX but I don't want it to conflict with the navbar component that I'm importing from next UI so I'm giving it an app- prefix so in here I'll paste that example that I grabbed and then rename the export to be app nav bar now this example is bringing in a logo I'm just going to remove that for now and then get rid of the logo down down here and then we can try using this component so in my layout I want to bring in that navbar and make it the first child of the providers here so here I'm going to grab app navbar like so and let's see if it worked ah it needs to be a client component so you can see um the code that we copied in is actually using react's Ed state to know whether or not that menu is open so we need to actually specify this app navbar component as a client component so that way we can use state so here I'm just going to say use client save it and there we go we have a

Navar up at the top awesome and to test out the automatic collapsing let's see yeah so when it's on a smaller screen it collapses we have a nice menu cool so I'm just going to go in and remove all those extra things and just maybe have like one link to profile cuz we're not going to have many pages for this starter template is just going to have like one profile page so here we can see that it is specifying menu items as strings I think instead I'd actually like to specify these as objects that have like a label and an href and for now we'll just have two links we'll have one that goes back to home so we'll say the label is home and the HF is just slash and then we want another item where the label is profile and the hrf is SL profile great and so now whenever we're iterating over these items um we're going to use the label and the HF so here I'm going to say item. label when we're rendering it out and instead of specifying uh a color we're just going to get rid of that and the href can actually just be item. href like that but now now I also want to use this

array of items uh when the mini bar isn't collapsed and you can see right now these are kind of just hardcoded in so essentially I need to iterate over them in the same way but instead of rendering navbar menu items I just need to render navbar items so let's do that so right in here we going to paste this but instead of a Navar menu item it's just going to be a Navar item like that and then we can get rid of these hardcoded ones save and now we have two links home and profile and then when I Collapse we also have those two links inside of there sweet so one thing I noticed is that uh these navigations are actually full page navigations instead of like single page application navigations once the app has loaded and we can actually fix that with next UI so in the next UI docs if we look at the routing section they talk about how to set this up with the router so that way whenever navigate gets called on the built-in link component for next UI it actually will use router. push from next which will make it behave as like a single page application page load so let's get this set up so if we head over

Chapter 38 45:27

NextUI Routing Setup

to our provider inside of here we can use the router and make sure you pull in the one from next navigation that is the latest one and then we can pass it in here so we can say navigate is router. push now right now I'm actually getting a type error because I set up typed routes in my next config so this is a setting that we set earlier if you look in here you can see we set typed routes to true and essentially what's happening is uh the router. push is expecting those paths to be real pasted within our application whereas the navigate function on next toi provider is just expecting it to be a string I'm not going to worry about fixing this right now um and in other scenarios where I want type DRS I'll probably use the built-in link component instead of the link component provided by nexi but for now I'm just going to do a TS expect error so that way it's not throwing a typescript error anymore and then I do have to enable this with es lint so if you press command period on any one of these errors you can say disable this es lint error for this one line and so we are explicitly ignoring that error which should be fine essentially we just won't

have a type completion whenever we're using the link component from next UI but that should be completely fine and then one last thing is because we're using us router this can only be called inside of client components so now our provider's component here is going to be a client component so I'm going to just say use client like this now if we head back to our app we can test it out so if I try going here and then navigate back you can see that those errors stick around so it's actually using that built-in navigate function now one thing to note is there's actually a bug with the navigate function here in next DUI provider I'll link this issue in the description but essentially I think it boils down to using different types of package managers they actually for whatever reason when they get bundled that navigate function isn't your working in the correct way but the one place where it does work is with pnpm and so because I'm already using in pnpm I'm not running into this issue but if you run into issues with their built-in link component or anything that's using that navigate function check out this issue it might have to do with the package manager that you're using and it also could be fixed by the time that you watch this video but just note that there is an issue there at this point I

also want to change the name of the app here and then also add like a logo so let's do that if we head back over to our navbar right here instead of saying Acme I'm just going to say nextjs starter that looks good and then I want to add an icon and for that I'm going to install an icon library now there are a million in one icon libraries but the one that I have really liked and has had many of the icons that I need is a library called Tabler icons and they actually have a react Library you can install that will give you uh react components that wrap these specific icons so we're going to do just that let's set it up if we head over to the documentation and then head down to the section for the react plugin we can get a specific install command so I'm just going to grab this install we'll run it here and now we can start using icons and so every icon inside of this package starts with capital I icons so we can just search for that and then automatically import it so let's do that uh essentially right here I want to add my logo before it so I'm just going to say icon and then you can see we have all of these icons from Tabler and I

Chapter 39 48:05

Tabler Icons

know that they have a package icon so I'm going to do this so icon package and now look at our app got a nice little package icon sweet but essentially anytime I need an icon I'm just going to pull in that component from Tabler icons all right at this point you probably notice that every time I go to the page it's like blinding me cuz it's like really bright and white let's enable dark mode in our Dark theme and also add like a theme switcher in the Navar so if you head to the next UI docs they have a section on dark mode and specifically they let you know that you can set it up with a package called Next themes so that's what we're going to do we'll grab the install command here and then and then we can add the next themes provider inside of our providers component so if we pull open providers we can then import these and then we're going to wrap our next themes provider in our children here great but now that things have been switched around we do need to pull this spinter air back down to be right above the navigate command there and you can see in their documentation they also set attribute to class and then they set a default theme I'm not

Chapter 40 49:04

Dark Theme / Light Theme Toggle

going to set a default theme because I want to actually use the users system theme but we are going to set attribute to class because that's how we have it set up inside of Tailwind so I'll set attribute class now let's create a theme switcher component essentially I want a little button that I can toggle and that'll change the theme between dark and light you can see they provide us a simple example one here let's just grab this and then we'll modify it so in our codes in the components directory I'm going to add a new file called theme switcher and then throw this code inside of here now you can see that it's pulling in use theme from next themes and this essentially gives you what the current theme is set to and then a function to change that theme and when a user specifically sets their theme this library is actually going to set it inside of local storage so it always has their preferred theme when they come back to your website but if they haven't set a theme then it will actually pass in the system theme and so we actually want to look at this as well and I'm actually just going to log out what these are when the component loads so we can see them and then write the code to work accordingly so now that I have that let's actually bring the theme switcher

into the nav bar and for now I'm just going to render this out right after after these items here so I'm going to add a navbar item and then add the theme switcher inside okay so now you can see that the current theme is set to system and if we look at those console logs you can see that theme is set to system and then the system theme is dark so essentially what I want is when the user comes to our website I want to show them their preferred theme I don't want them to have to toggle to dark mode or always default to dark mode so let's actually create a custom hook for that because I don't want to have custom logic in here every time I call this use theme function so in my codes here I'm going to create a directory called Hooks and then I'm going to create a file called use system theme then we'll export a function and essentially what we'll do inside of here is we'll grab the theme the system theme and the set theme function from the Ed theme hook that's provided by next themes so we'll pull this in we're going to grab all those same things and then we can see I have a linter error so I completely forgot that I enabled the Kebab case Rule and so I

Chapter 41 51:26

create useSystemTheme hook

actually do need to name this use system theme and that's actually a lot more readable than the the C case version at least I think again it comes down to preference okay so now inside the hook if the theme is set to system we want to return the value of the system theme otherwise we want to return the value of the theme so for this I'm actually going to use a use memo and I'm just going to return a use Memo from react that is dependent on all three of those values and here we're going to return an object that has a theme property which should be some value and it's always going to have the set theme value on there now theme needs to be the system theme if theme is set to system so right here I'm just going to have an inline Turner so we'll say if theme is equal to system then we want to return the system theme otherwise we want to return the theme itself now if we look at the return value of this function we can see that theme is either string or undefined and then set theme takes in a string but I want a little more type safety here so I'm going to create a type where the theme can only be dark or light so let's

do that I'm going to have a type called theme this will be dark or light and then I also want to have a set theme type that takes in that theme instead of taking in a string so I'm going to copy this type here we'll call this set theme it'll be this I need to bring these in from react and then instead of a string here we will set this as theme but now we can use these types so right here I'll say We'll return this object but theme is of type theme and set theme is of type set theme like that and so now anywhere I use this hook we're going to have a nice typed value where theme can only be dark or light and set theme is a Setter function that can only take in dark or light so now let's use it inside of our theme switcher so instead of calling use theme here we're actually just going to call use system theme and Pull It in from our hooks directory and now we should specifically have a theme value that is either dark or light and so instead of having these two buttons

Chapter 42 53:33

Theme Switch

let's actually Add a switch or a toggle component that will allow us to toggle back and forth between light and dark theme so if you look at next UI they have a component that is called switch and this is exactly what we want you can actually see they have an example with icons that is almost exactly what we need which is like light and dark theme so let's grab this code and then we can change the icons that we specify so here we're going to add the switch component pull that in and then instead of sun icon let's pull this in from Tabler icon so if I say icon Sun they have an icon Sun there we go and they very likely have an icon Moon as well so I'll grab icon Moon and that's com in from Tabler icons as well so let's see what we get look at that we have a nice little toggle button so let's actually make it work so you can see in their docs they have this controlled section where essentially you can specify is selected and what happens on onv value changed so is selected should be true if the theme is light so let's set that up let's say is selected

and this is going to be if theme is equal to light and we get this type completion which is nice so select it if it's light and then we can specify on value change which will explicitly call our set theme function so on value change we'll say um if theme is equal to dark then we're going to set the theme to light and otherwise we're going to set the theme to dark like so so now we should be good to go by default let's see you can see that it has selected dark mode and then if we toggle it it turns on light mode very good we have a a nice little switch U I'm actually going to hide this label here um but let's actually just say this is called theme and and I want to also include this switch inside of my collapsed items here um but I only want to show the label if it's inside of the collapse item if it's in the Navar we're actually going to hide that label so let's take in a prop that is just show label and this is going to be a Boolean and if show label is true then

we'll actually show this label here so we're going to wrap this in that and we'll just say show label and that and let's actually make it so that this CR is not required we're going to set this as optional like this and that'll make it so that by default it's not going to show the label but then you can pass in show label as true Okay so we've got the theme switcher here I also want to add it here inside the collapsed menu so we'll just grab this and inside the collapsed menu I think I want it at the top instead of at the bottom and this will actually be a navbar menu item instead so we'll save that and in this case when it's in the menu I do want to show the label okay so by default it's here we don't see a label and then when it's collapsed we do see a label sweet now I have actually been ignoring this warning here but let's take care of it now so you can see that whenever the page renders it says extra attributes from the server class and style and this actually has to do with the fact that whenever next themes kicks in it actually sets a class attribute on the HTML element so if we look at the inspector here we can see that our HTML

Chapter 43 56:24

next-themes suppressHydrationWarning

element has the class dark and then everything else can actually use that so Tailwind uses that next UI uses that and it's all based on that class name being dark but when we render it from the server it doesn't have this class name dark so we need to to take care of that and if we take a look in the next themes GitHub repo in their readme they talk about this so right here they're saying that theme provider is a client component and not a server component and if you do not add suppressed hydration warning you're going to get warnings and um this is actually pretty scary to do because it's like wait if I'm adding this at my top level so if we go over to our app and then layout they actually want us to add this suppress hydration warnings there on the HTML element but it's important to note that this only applies to this of components if you have any hydration warnings lower level down in the tree like inside of other Pages or components you're still going to see that hydration error which is a good thing so this is essentially just suppressing that hydration error for the HTML element because when it renders on the server it's not going to have that class element and so now if we reload

the page we don't get that hydration error and our theme still works next up I want to create a basic layout so that the main area here always takes up the full container and also will make it look nice with like a background image so what we need to do and first I'm going to turn on dark mode cuz I'm blinded right now is uh we have our body here I want my body to take up the full viewport width and height so inside of our layout on the body I'm going to add some Tailwind classes we're going to say we want width screen and height screen and these will respectively set 100 view width and 100 view height and so now if you look at the body it's taking up the full viewport next I need this first child here to take up the full width and height height of its parent the body and this div is actually created by the next UI provider so if we take a look in our provids component this is the element that's creating that div so really all I wanted to have is a full width and height so let's add a class name we're

Chapter 44 57:46

App Layout

going to do width full and height full and now this element takes up the full width and height of the parent from there I want the nav bar to always take up the amount of space that it is and then I want the main element where all the children are going to be rendered I want that to always take up the rest of the space inside of the container so to do that I'm going to set this UI provider div to be a flex box and make it so that the main element with the children is a flex grow so on this element we're going to just say Flex that'll give it display Flex we'll do Flex column so that way it's vertical and then in the layout we'll create a top level element that will take up the rest of the space so right below the Navar I'm going to add a main element we'll throw children inside of there but now main should have Flex to grow so we'll add the class flex-grow which sets a flex of one and now we've got our body which takes up the viewport we've got our UI provider which takes up 100% width and height then got our navbar and then we have our main element which grows to the size of

the rest and then any page is going to be rendered right inside of that main element so let's update our main page to not just be a button let's actually add some content so if we go to our index page here I'm actually going to render out a card so card comes from next UI and then inside of there I'm going to have a card body and then I'll add a title and I'm just going to call this the dxjs starter and below that we'll add a little description we'll say a simple starter for nextjs o and so just like that we've got a nice little card but I don't want the card to always take up full width and for that let's just set a Max width on the card here so I'm going to set max width and we'll use medium which is 28 rims cool so got a nice little card there and then I want this to be centered on the page so I can do MX Auto so that's automatic margin in the x-axis great uh let's make this look like an actual title so on the H1 we'll give this a text 5 Excel nice and then I

also want this to be centered we're just going to Center all of the text so on the text body let's give this a class name of text Center and that looks good and I want to increase the font size of the little paragraph tag here so let's give this a text Xcel great now lastly I want to set a full page background image on that main element so no matter what page on it always has a background image this is just a style that I want for my site you don't have to do this uh but for this I'm actually going to use a background generator so if you haven't heard of it there's this site called f Fuel and it has a bunch of cool little CSS and canvas tools and SVG generators and specifically I want to use this generator it's called M moti and um I'm going to generate a nice background here so let's actually increase these these little boxes and then let's make these dark so I'm going to generate two different images I'm going to generate an image for dark mode and that should be like that so I can copy as SVG and then inside of my app I'm just going to

Chapter 45 1:00:58

Generate background image

throw this SVG in the public folder so let's create a folder called public and then inside of there I'm going to create a file called dark bg.svg and then throw the SVG code inside of there cool and then let's do the same thing but we'll save a light version of this for whenever we're in light mode and how about e that looks good so let me copy this one and I'll save this as light bg.svg throw the codes in there and now I want to set these as the actual background image so over in our layout on our main element here we can set a background URL and I it's going to be dynamic because I want to specify the URL specifically to be that image so inside of here I can say URL and then because I put those svgs in the public folder they're always just going to be served from the rout so so here I'll say uh light bg.svg and let's save that cool uh so let's go to light mode so we can see what this looks like so by default you can see down there at the bottom it's repeating it's really just set to the top left quarter so first if we do

BG cover that should cover the page instead of repeating it awesome and then we'll do BG repeat and then let's actually see what this looks like if the content of the page has some scroll to it so if we go to our main page for now I'm just going to add some fixed height on this so I'll do height and let's do 2,000 pixels so let's see what happens here so yeah you can see that it like blows up the image I don't want that so first of all if I set overflow to Auto that should fix the scroll in the x axis yeah so now it only Scrolls in the y axis awesome and that looks good to me if I zoom way out the background still looks fine if I zoom way in the background still looks good yeah so this this is pretty much what I want so now I can specify what the background image should be whenever we're in dark mode because right now it's always going to be that same SVG with intell end you can use the dark selector and we'll say that when we're in dark mode basically I want to change the url to be that dark background so we'll set that here dark

BG and now when I go into dark mode it changes the background image sweet uh one last little bit of cleanup let's remove this uh massive height on this div and also give it a little bit of margin on top so if we head back over to the page let's remove that height and then just set a margin top of four nice we have a wonderful landing page that looks good in dark mode and light mode sweet now one of the last things I want to do here is set up an error page because right now the error page is just the built-in one so you can see if I go to the profile page it's not found and if we look at it in light mode it doesn't look that great because it's just using these default Styles so let's set up a not found page so in nextjs there's a convention if you create a file called not- found this will be used if there's ever a 404 and that page can't be found so here I'll just export a component and I am going to just use a card from next UI we'll throw in a card body and then inside of here I'll have a paragraph tag that says this page cannot

Chapter 46 1:03:59

Not Found Page

be found like that uh let's set up some Styles let's just give it a Max width let's do medium and then an automatic margin like so now that we have that file it actually uses this error page let's adjust the Styles a little bit let me set it to text Center and then I'll also increase the font size here let's just do text uh to Xcel like that cool that looks better and then we want a little bit of margin on top so I'm going to do a margin top of four nice and so now if we ever come across a page that isn't found we're going to get that custom error message and when we're in light mode it's still using our Styles one more thing is I want to add a little icon there so within Tabler icons there is an icon called uh file unknown or something like that let's just search for Icon unknown yeah un icon file unknown let's throw that in there nice uh but let's just Center everything so that way the icon is right next to to the text so if I make this a flex boox and then do items Center that and then also justify Center like that great but

that means we actually don't need text Center anymore and then I can add a gap of two so there's a little separation between the icon and the text awesome so that looks good in light mode and dark mode great now in the next part of this video I'm going to be setting up environment variables and also authentication but if you'd like to just use the next UI starter that I've created here this is going to be on a branch called Next UI in the starter kit repo that is linked in the description next up I'm going to set up working with environment variables in a type safe way so by default nextjs will detect your EnV files and load them in so you can access them from process. EnV but it's possible that you might be missing an environment variable or sometimes you want some environment variables to be numbers like when you're dealing with ports and for that we can use something like Zod so Zod is a schema validator and essentially we can use it to to read in the EnV and then work with it in a types safe way now you could use Zod directly but there is this package called T3 EnV this is built on top of

Chapter 47 1:05:58

Typesafe env Setup

Zod but it has some nice things built in so that when you're working inside of nextjs you do things in the right way because especially if you're dealing with environment variables on the client you actually need to include each one of those public environment variables otherwise won't it won't get included in the build and there's some nice built-in type safety here that ensures that you do that so let's get it setup we're going to run this command to add it and then from there I'm going to create a server EnV file now it's possible to have a single file that specifies both your client and your server but I like to have two separate files and make it so that my server environment variables can only be imported by files that are going to be running on the server so in my source codes I'm going to create a directory called EnV and then inside of there I'll create a file called server.

TS and then we can copy their example here now when this code is running on the server as as long as you're using a version of nextjs greater than 13.4.2 you don't have to specify every single one of your environment variables you can just pull those in dynamically from process. EnV so that will work for us now for now we're just going to have an environment variable called node EnV and this will be an enum that is either development or production and if you check out the T3 EnV docss they actually have a setting that says throw an error if the environment variables are empty because it's possible that you could specify in variable but just set it to nothing but we actually want to throw an error even if it's empty so if you check out customization there is a setting here called empty strings as undefined we're going to set that to true so that way even if it's specified in the EnV if it's empty we still want to throw an error to make sure that we set that before our application starts up and so now to actually validate our EnV whenever the app starts up we are going

to modify our next config so inside of here we can pull in our EnV that'll run the Zod validator and if there are any missing environment variables the application will not start at all and this is a good default to have because if there are any missing environment variables in production you won't even have to track that down literally the application will not start unless those environment variables are set so if we look in their docs here they mention we can use this package called jitty because essentially this file is a Javascript file it's not a typescript file but we want to be able to import in this typescript file whenever the application is starting up so jitty just does a just in time uh transpilation of that file so it can actually run even though it's running inside of a Javascript file so we need to add JY great and now inside of our next config we can run these codes so up at the top here throw that in but we want to pull this in from Source slvs server. TS we'll save that if we

kill our server and then restart the app starts up just fine that's good but let's actually take a look at what got parsed here so if we log out this EnV value when the app starts up we can see that no EnV is set to development so by default when you're running in Dev mode it's already set to development so the EnV was parsed everything was good to go but let's actually try adding another value here and it should crash because that value doesn't exist in our do EnV so let's just do a database URL and set that to a string like that and now if we restart our application it immediately crashes and says we have invalid environment variables the database URL is required and so now we must specify that in ourv so if I go over specify a env. loal file inside of here I can set database URL to let's just set it to something for now and if we do that we should be able to start up our application because it's able to read in that database URL but we are using Zod so we actually can even do further

validations right so inside of Zod on strings you can actually specify that it's a URL and if we do this now when we start up our application we can see that database URL is an invalid URL so this is really great especially if you're working on a team and you're trying to onboard someone they won't even be able to start the application until they can get all of those environment variables set so for now I'm actually just going to remove this extra value here and once we start setting up all of our other libraries for o and our database and everything we'll gradually add more values here so I'm going to go ahead and just get rid of everything in here and now we'll be good to go for any library that needs an environment variable now another thing I want to do is instead of spitting out this giant error here I kind of want to just clean this up and only show that there were invalid environment variables and So within t3v there is an option to customize what happens when there is a validation error so we are going to grab this throw it in here we'll import Zod error from Zod uh but now instead of throwing an error we're actually just going to exit so if

I do process. exit with an exit code of one now it's not going to log out that whole error but it'll still stop the app from starting if there were any invalid environment variables so now if I run this you'll see it says invalid environment variables and it's a bit easier to parse we don't have to scroll through the whole stack Trace there awesome so let's just make this a valid database URL real quick so the app actually starts up now if we start it up we're good to go now let me remove this console log and now that we have this way of accessing environment variables in a typesafe way I actually want to prevent anyone from using process.env directly so let me show you what I mean let's say we're inside of a component like this page. PSX here and let's just say we try to access one of our environment variables and so in this case I'm just going to log out process.

Chapter 48 1:11:41

process.env Linter Rule

env. database URL now I want to prevent any piece of code from directly using process. EnV except for my actual EMV parsing file and so I want to see a linter error here and make it so that anywhere in my codebase the only way to access the EnV is to import that pars inv validated EnV file and for that there's this plugin for eslint called eslint plugin in that includes a bunch of extra ra rules that you can enable inside of your app so let's install this as a development dependency so we'll do pnpm add- D es lint plug-in in and now inside of my eslint RC we can enable this rule so first of all we're going to add into the list of plugins so we add in and then the rule we want to enable is called No process EnV so I can do in/ no process EnV we're going to set that to error and now if we take a look back at page you can see that we get a lter error so unexpected use of process.env and so this is great because now anywhere in my code if someone maybe

they're not familiar with my codebase they try to use process. EnV they're going to get a linter error and so in order to fix this we actually should use EnV directly so I need to import EnV server and that works just fine but over here in my server file I do have a lter error but this is going to be the one place that we are able to use process.

EnV so we're actually going to just disable that rule for this one line because this should be the only only place in my application where I actually use process. EnV okay so I'm going to remove all of this stuff that has to do with database URL we're going to set that up later because there's going to be more that's involved uh we just use that as an example but let me clean all of this up and in the next part of this video we're going to actually set up our database and off and everything else next up we're going to set up authentication and there's a lot of ways to go about this if you look in the nextjs documentation they actually have an entire article on setting up off with sessions from scratch so you can definitely check that out and Lee has actually done a video walking through this process and talking about all the concepts involved with o honestly if you're brand new to O I highly recommend checking this out and also going through this article because it explains everything you would need to know about o um but you don't always want to implement it from scratch so there are solutions out there where you don't have to implement it from scratch and specifically there is next off now in the world of nextjs next off is probably

Chapter 49 1:13:43

Next.js Authentication Options

the most popular package for implementing authentication and this is what we're going to use in this starter kit now we're use version 4 which is technically the older version of next off because the team is gradually working on a thing called OJs and this is essentially next o recreated to work with many different backend Frameworks not just nextjs however it's still experimental and right now the V5 is in beta so we're going to stick to V4 and use the next off package there's also a library called Lucia and they have documentation on how to set this up with nextjs as as well now you could use a hosted service for authentication and these are great especially if you have a smaller app or you're just getting started because they have a lot of extra stuff built in like password reset emails and being able to do like oneclick email logins without having to set up your own email provider they also have like user management so they're pretty nice but they typically start to charge more as you get more active users

so I typically try to avoid services like that because NEX doth or libraries like Lucia are usually all that I need for the kinds of applications that I'm building and because these libraries integrate with just a various amount of databases um you can pretty much store your users wherever you're already storing the rest of your data as well which is one thing I really like so let's get this thing set up so if we head over to the documentation and then the getting started section here on next off we can install the next- off package and then from there we need to set up an API route and since we're using the app router we can actually use route handlers so if you look at this section here it talks about how we can specifically export a git function and a post function from next off so this is what we're going to do so we need to create this directory here inside an API folder inside of our app directory so in here I'll create a new folder throw that in there so now we have app API off and

Chapter 50 1:15:37

Next Auth Set Up

then a dynamic route segment So within nextjs this essentially will allow any request that's coming to API off to go to this specific Handler and inside of there we need a file called route. TS so I'll call this route and within that file we can export the handlers like so now next off takes in some configuration options but I'm actually going to Define this in a separate file because we potentially need it in multiple places so I'm going to pull this out things are broken for now but inside of my source directory I'm going to create a directory called config and inside of there I'm going to create a file called off. TS and this file will export the options that we can then pass into the next off Handler and so for my application I'm actually just going to have login with Google I'm not going to do username password or anything like that it's just going to be ooth with Google a user will click get redirected to Google choose their account get redirected back to my app so if you take a look at the providers section you can see all of the ooth providers that they have built in and we specifically are

Chapter 51 1:17:07

Set Up Google Auth Provider

going to pull in the Google one so our settings are going to look like this I'll throw this in here and this is going to be in an object called options and object it looks like this and in order to get some type checking here we can specify the type of options to be next off options like that and then we'll export options as the default export so export default options like that now we need to set up our Google client ID and our Google client secret so we're going to add these inside of our server EnV so over here I'm going to throw throw these in and say that they both need to be a string like that and now I'll have to specify these inside of my env. looc file great now to get these values I'll need to create an oo client in the Google console now within the Google console I'm going to create a project I'll just call this the nextjs starter and then from the dashboard under apis

Chapter 52 1:18:00

Create Google OAuth Client ID

and services we can go to the credentials section now within here we'll create some credentials we'll choose ooth client ID and we'll have to configure the consent screen and so this is the screen that people see whenever they're logging in with your app so this is an external app I'll fill out all of these settings grab my client ID in secret and then we'll head back over to my app and when we're setting up Scopes we want to make sure to choose that we can view the user's email address and then also open ID so these are the minimum Scopes needed whenever we're using ooth if you're integrating with Google services and like using the users info and access token to do things on their behalf you'll have to choose other Scopes as well but these are the minimum Scopes that we'll need now before you can actually push any of this to production um you actually have to get it approved and so you're going to want to have test users and so I'm just going to add some other accounts here so that way I'm able to test it without being logged into this specific account and so now that we've set that up we actually can create some client credentials now so I'll choose oo client ID and we're going to choose that this is a web application and I'll give it a name of nextjs starter and so if you take a look

in the nextjs documentation you can see that this is what our callback URL will be so I'm just going to throw that inside of here now right now I'm just running in development so this is fine but once you deploy your application you'll need to make sure that you add the redirect URI with your deployed domain as well so I'll create this and now I can copy my client ID and client secret into my EnV file and now with those values set in my env. loal file those should be loaded in and I can actually pull them into my o option so now instead of pulling these from process. EnV just going to pull them in from EnV and we'll import that there and so now it has those specific values now I need to pass these options into my next off Handler so if we head back over here we can pull in our options that get imported from config off now we're getting a linter error because of the Kebab case rule that we set up so let's see if we can actually disable that rule whenever we have a dynamic route path because when we're setting up API routes we might need to use Dynamic and have like the the square brackets so let's

Chapter 53 1:19:58

update kebab-case linter rule to allow dynamic routes

update that rule in our eslint RC so here if I say not something that starts with a square bracket followed by anything else let's see yeah so that fixes the rule here so this should be good to go we've created our Handler we're passing in the options and then those options are specifying that we're using the Google provider Now by default nexto actually doesn't require a database it can do everything in memory and store the sessions inside of Json web tokens so this actually is ready to go to test to see if we can get logged in so for that let's add an off button in our nav bar so if we head to the components folder and we can add an off button here now because the off button is only ever going to be used by the navbar and also the theme switch is only ever used in the navbar I'm going to restructure things here so that I have a folder called app navbar and then everything related to the nav bar is going to live inside of there so and yeah we'll update our Imports we'll push this into there and we'll actually

Chapter 54 1:20:40

auth button / sign in / sign out

rename this to index. TSX and so when you're working in a larger code base and you have more and more components if a component is only ever used in like one specific spot I like to group those together inside of a folder that way it's not crowding up the components folder so this should be good let me just double check my layout to see that uh yes we've got that the import is broken uh but if I reload VSS code loading loading okay it can find it now awesome so uh now that we have that folder inside of there I'm going to create a component called off button we'll export a function and for now we'll just return a button that says sign in and we're going to pull this in from next UI and set the color to uh danger because uh it's red and Google's colors are red I'm going to set the variant to uh ghost and then now let's bring this button into the Navar so here in the Navar I want to show that off button uh right after the theme switcher so we'll add another Navar item and then

pull in the off button like that and so now we have a nice little sign in button sweet um and then of course we want to have that in our collapsed menu as well so I'm going to throw this at the very bottom and uh this will be a navbar menu item like that and so now whenever this is collapsed we should see that signin button there cool so when this button is clicked we want to log in with Google o and there's a built-in signin function that comes from next off so let's set that up on click we're going to run the sign in function so we can import that from next off react and then we can pass in the provider that we want to log in with in this case which is Google just like that so now when I click the button it should redirect us to Google the user Will consent and then redirect us back to the app uh but let's actually detect if the user is loged Lo in so next off also provides a hook called use session and here we can grab the data which is the session data and then also the status which is if it's loading or if

we're authenticated or not now in order to use this hook this actually does need to be a client component so we're going to say use client here and then lastly to be able to use this hook we actually need to be inside of the session provider so yeah we're getting an error right now that says the use session should be wrapped in a session provider so if we head over to our provider component we can actually wrap all of this in the session provider so we'll add the session provider here which comes from next off react and then move all of this inside of there awesome and so now it's not complaining anymore it has access to that use session value so now let's handle uh what happens if the user is logged in um or if it's loading so here we'll say if status is equal to loading we're actually just going to show a circular progress and so there is a component called circular progress built into xui react so we'll add that there and so if it's loading we'll show that and then if the status is

authenticated that means we're signed in so we actually want to show a sign out button so here copy this button but instead of sign in it'll be sign out and when you click it we'll call sign out which comes from next off react like that and uh let's not forget a return here so if we are authenticated show the sign out button if we're not show the sign in button okay moment of truth I'm going to click sign in we get redirected which is great I'll click my user account and then we get redirected back and it says sign out sweet so we have that information about the user now let's add a little drop- down menu that like shows the user Avatar and has like a a sign out option under their Avatar and also let's show a Google icon on the button here so right here we're going to add icon Google icon brand Google throw that here back here that looks good and whenever we are in the collapsed menu I actually do want it to just be this button so I'm going to add an option to

this component called minimal so if it's minimal just show the button but otherwise we're going to have like an avatar with a drop down in a menu and stuff like that so this component will take in a minimal option and this is just going to be a Boolean and we're going to default this to true and so if we're authenticated then if we are min minimal we're going to return this button but if we're not we're going to return a nice little uh drop down menu okay so this should still work but now let's take a look at the next UI docs and find uh how we can do like a drop down so if we take a look they do have a drop down component uh which looks like this but they also have a section called custom trigger so you can actually make it so that an avatar triggers a menu and this is basically what we want we want to show the users's image up in the top right and then when we click we'll have a menu that has like sign out inside of it and I just want the first example I don't want to have the text beside it so we'll grab this first drop down all the

way up to here and let's use it so uh if this off button is not minimal then we're going to return this dropdown let me import all of these things I'll import all of those and for now we're just going to have one option here which is uh sign out a key of sign out and we'll set an on click here so when this is clicked we want to run sign out and now we can specify the users email so we pulled in data from use session we should have our email on it so let's specify that here so we're going to grab data. user. email and then now on this Avatar component we will specify the user's image so right here let's specify data. user. image like so and then the Avatar component in next UI has a fallback option so um we'll set show fallback to be if uh data. user. image is not defined um otherwise this will

just be empty string okay let's see what we get ah but when we're in the main Navar I don't want this to be the minimal one so if we head back over to the Navar um we can see that we're actually missing the uh minimal prop let's set minimal to be optional it's optional but it defaults to true so now when it's in the collapsed menu it'll be minimal but now when it's in the navbar we're going to set minimal to false we should see our Avatar sweet and so now we have a little Avatar with a dropdown we can see who we're signed in as and then we can click sign out that signs us out sweet we can sign back in and if we're in the collapsed menu we can see the sign out button there as well awesome now one last thing let's set it up so that the profile page actually shows the user info and we don't show this profile link unless the user is actually logged in So within the app directory I'm going to create a folder called profile and then inside of there we'll create a page page. TSX and we'll export a component and so when we're in

Chapter 55 1:27:38

Profile page

a server component we can get access to the session with a function called git server session that comes from next off and we should pass in our off options so this is why I defined it in a separate file is now I can import those off options there and pass them directly into get server session and so now I can grab the session by calling this we'll make this an async component and now I can use that session data to display the user info so for now let's actually just return uh the Json data of the session so I'm just going to do json.stringify of session and let's see what we get so if we head to the profile page we can see that it is null and I actually forgot to do one thing so if we look at the errors here uh we can see a warning that says we have no off URL and no secret so let's actually set this up so here in the docs you can see that it's just your your base domain and so let's set this up in our EnV and then also our

Chapter 56 1:28:37

setup next-auth environment variables

EnV local file so here we're going to say that next doth URL needs to be a string and it is a URL like so and then the other thing we need is the next off secret and so this is what's used to encrypt the Json web token and this is going to be a string so we'll set this to z. string and then now we can specify these inside of our env. local no I'm not going to show you this because it has my client ID in secret but next do URL is just going to be Local Host 3000 and then I'll show you how we can generate a secret so you can see in the next docs there's a command you can run with OP SSL that will just generate a random value this is what you can use as the secret so from the terminal if we run this we just get a long value and this is what I'm going to set as my secret in mymv file so now that I have those values set let's restart my server and reload the page here great um so the session was created before I had the secret so let's actually sign out and then sign back in so let's sign in there

we go so now we have the user value there we can actually display their info on this profile page so on the profile page I'm just going to return a card with a card body and next UI has a component called the user component that will just display right there on this card so let's grab this code going to put it inside the card and the name here will be session.

Chapter 57 1:29:59

Profile page user card

user.name our description will just set as the email and we can specify the avat hard props here so this will be session. user. image uh and if that isn't defined just the empty string and similar to how we set up that uh drop- down button in the Navar we can also set the show fallback option to be session. user.

image if that is not defined then we should show the fallback image okay so just like that if we head to the profile we now have the user info there and a profile card so let's set a Max width on the card here set to medium and then we'll give it some automatic margin in the x-axis and a margin top of four cool so there's a little user card there obviously in a real world application we might show show more info about the user profile okay uh one thing I want to do is uh if the user is not logged in they shouldn't be able to go to the profile and they shouldn't see the profile Link in the nav bar here so if we sign out we can see we just see like this fallback but I don't want the user to be able to go to this profile page at all so first of all let's update our signin and sign out functions so if we head to the off button we can specify where we should send the user when they're done logging in or when they're done logging out so when a user logs in I want them to be

Chapter 58 1:31:05

authorization redirects

redirected to the profile page so here we can specify a uh callback URL and I'm going to specify that as SL profile so when you log in after the login is done go to the profile page and when you log out I want to go back to the homepage so I'll specify that in our sign out function so this also takes a callback URL and we're just going to go to the index um and we actually have two methods that are calling sign out I'm going to actually Define this in a function so we can reuse it let's actually pull this out to like sign out click and then we'll Define a function called sign out click that's equal to that and we can pass this same function into this other button like so okay so now when a user signs in it should redirect them to the profile and when a user signs out it should redirect them to the home page awesome that's the behavior that we want but the other thing is in the Navar we don't want to show the profile link if the user is not logged in So within the nav bar we can

Chapter 59 1:32:27

Session aware navbar

also use the session and not display that item uh if they're not logged in so let's grab the session and we're just going to use the status so if the status is authenticated we're going to push this profile link into the Navar so we'll say if status is equal to authenticated then and we'll say uh menu items. push we're going to push in this object but it won't be in there by default like that so now if the user isn't logged in we do not see a profile link this also should work inside of our collapsed menu because it's using that same array but if the user is logged in then they should see that profile link awesome so this looks good now the one thing is uh even if they can't see that link they can still go to it so watch this if I sign out even though I can't see that profile link technically I can still go to SL profile and we don't want that so to prevent this we're actually going to use a middleware So within next off they have a built-in middleware that

Chapter 60 1:33:29

Next Auth Middleware

we can use and just specify which routes should be protected by authentication so I'll grab this code here and then we need a middleware file so in our application the middleware dots file needs to live right next to the app folder it can't be inside the app folder so we're going to put it in the source directory I'll create a file called middle wear. TS and then throw this inside of here but we actually want to protect SL profile like so so now if someone tries to go to SL profile if they are not logged in they'll get redirected to the default not logged in page um and yeah this looks good here let's see what happens so let's try refreshing this page boom you can see that nexo actually redirects us back to this like a standard login page which is great we can actually change where the user gets redirected to um if they are not logged in and that middleware kicks in so if you take a look in the next o documentation and then look in

configuration and Pages you can see that we can specify uh where they should go if there was an error or where they should go to sign in or sign out and so I'm actually going to override the signin page because that's where we're getting redirected to so if we go to SL profile you can see that it's taking us to API off signin um and because next off supports a lot of different signin methods like email password word and oo and just email magic links this page is nice because if you set all of that up it's going to automatically show all of those signin options uh but if you want more control you can just send them to your own page and so I'm actually just going to send them to the homepage and display that error there so here I'm going to say sign in is just on the homepage because that sign-in button is always in the navb bar and so now if I try to go to/ profile I just get redirected back to the homepage and this is good enough for now of course you can modify this further you can Define custom Pages for each one of these options but for this simple app this should be fine now one more thing we

Chapter 61 1:35:29

Layout Suspense Boundary

should do is actually set up a suspense boundary uh because this code here is running on the server and it loads pretty quickly but what if it doesn't and let's actually uh emulate what happens if this is a really long request so I'm just going to await a promise two seconds like this okay so let's see what happens if we try to visit the profile page and for whatever reason like getting the session or reading from the database or something like that is taking a really long time so first of all let's sign in and I think we saw it happen but let's actually try it in a brand new tab so in a brand new tab if I try to go to SL profile you can see that we're literally waiting that entire time before we see the page itself and nextjs has a way of handling this using a suspense boundary so if we go to our layout here if we add a suspense boundary around our children this is where the page is getting rendered and the shell of the application can actually load first before showing the rendered page so if we wrap this in

suspense like so now you can see the overall shell of the page loads and then we're kind of just waiting for the rest of the page to load so let's start it in a in a blank tab you can see that it loads and then finally it kicks in and so to augment this we can also set up what should be displayed if we're loading an async component so inside of here we're going to set up a loading.

Chapter 62 1:36:40

Loading page

TSX file and essentially this is what will show if some asynchronous component is in the the process of loading and so here I'm just going to return a circular progress element of course we'll give it an ARA label and I'm going to just put this in the center with uh margin X Auto so now you can see if there's some long running process we actually see that loading indicator before the page itself loads awesome now I want that loading indicator to be even bigger and much more apparent so if we take a look in the next UI docs you can see under custom Styles we can actually specify how large that circular prog ress could be so let's pass in the width and height to the class names here so we can specify this let's see what we get nice so now that's a nice big loading indicator before it shows the page now before I forget let's actually just remove that timeout of 2 seconds and uh we can see that things are pretty instant but once we start getting a database involved and everything else we definitely will need that suspense

boundary for other async Pages now so far we don't have a database so this user actually isn't getting stored anywhere it's literally just in the session cookie but in the real world we actually want to put these users inside of a database so we can actually start associating data with them and everything else so in the next part of this video I'm going to get our database set up with Drizzle and then after that we can look at database adapters here inside of next off and get it connected up to our drizzle database now let's set up our database now there are a lot of options for this these days it kind of seems like people are basically choosing between an or called drizzle and one called Prisma uh but there are other options there's also this thing called micro RM and there is a package called Lucid which actually comes from the creators of adonisjs and all of these are omm um except for drizzle which also has like a query building syntax uh but there are other packages that people like to use as well such as keyley so

Chapter 63 1:38:14

Database Libraries

keyley is a query builder in that you write kind of like these chained methods that ultimately get turned into SQL queries but they don't have the higher level way of defining like models that correspond to your database and then of course there's connects which has probably been around the longest but doesn't have the greatest typescript support now drizzle popped up because there were actually a lot of issues with attempting to run Prisma inside of serverless environments or like memory constrained environments now more recently Prisma has actually fixed a lot of those issues so it works pretty well even in serverless environments um but one of the things that I really like about drizzle is there is no code code generation step so essentially the code you write to define a specific table is the exact same code you use to correspond to the type of the data inside of that table so there's no generation step whereas with Prisma you define your schema inside of a Prisma file and then anytime your Prisma file

changes you have to run generate which actually generates typescript code uh which is fine especially if your database isn't changing as often but I really like drizzle tight integration with typescript and that there's no generation step basically I can Define my table and then I have a type that I can instantly use that corresponds to that table and there are really cool built-in helpers that can basically take that same table definition and instantly turn it into a Zod validator again with no generation step uh there are similar tools that exist in the Prisma ecosystem but again there's a generation step so anytime your schema changes it would need to regenerate those Zod validators but that's why I've decided to use drizzle in this this starter kit so let's set it up now one of the interesting things about drizzle is they actually have different connectors depending on the type of database that you're connecting to so they support both postgress MySQL and SQL light but for each one of those there's a lot of different ways that you could be connecting to one of those databases specifically I'm going to be using

Chapter 64 1:40:25

drizzle set up

postgress and we're going to be using the postgress JS client so locally when I set everything up we're going to be connecting to a postgress database that lives inside of a Docker container so this driver will work but when we deploy we might need to choose a different adapter like neon or versel postgress and when we come to that point we could potentially write code that chooses the correct connector depending on where the code is running but locally I'm going to go ahead and set this up for postgress JS so we'll run these install commands and then we'll create a file which is our connection to the database so I'm going to create a folder in Source called DB and inside of there I'll create my index.ts and we'll Define this codes inside of here now I specifically just want to export my drizzle connection from this file so I'm going to get rid of all this stuff that has to do with migration and we're going to set that up in a separate file and so with this I'm just going to export that DB as default now let's set up some environment variables so you can see by default it's just passing in a string here we want this to actually

come from our EnV so if we head over to our server EnV there's a few things that we're going to need here now we will have a database URL environment variable but because I'm going to be using Docker and I want these settings to sync between them I'm actually going to have a separate environment variable for every part of the connection string so first up we need the DB host and this will be string then we're also going to need the DB user this will also be a string of course we need the DB password this will also be a string then we need the database name we'll need the port and Port should always be a number so we can actually do a z. coers and then use number so in our EnV the port is actually defined as a string but whenever we parse it we're going to turn turn that into a number and then lastly we want the overall database URL so it'll just be a string and we can also make sure that it's a valid URL now let's define these inside of our env.

looc file and because we're going to be using Docker all of this is going to be running on Local Host so I'll set DB host to Local Host the user I'm just going to set to next starter and the password I'm going to set to super secret and the DB name I'll set to next starter and the port will be the default Port 5432 now the database URL is essentially a combination of all of these other variables and so we can actually use environment variable expansion to combine all of those together so the database URL is postr SQL col slash user password host port and then database name now that we have these environment variables let's set up a database running inside of Docker now if you're new to Docker definitely check out the crash course video that I have here on the syntax Channel I dive deep into what Docker is how to set up compos files how to build your own images so if you want to learn more about Docker definitely check that video out I'm going to show you the basics for getting a postgress database up and running and it's actually pretty simple so if you check out Docker Hub they have an image

Chapter 65 1:43:11

docker postgres set up

available for postgress and then they have a command we can run to just start a postgress database but I don't want to have to run this command every time I need the database so I'm going to Define what's called a compose file so within my repo here I'm going to define a file called docker-compose.yml and inside of here I can Define my various services and our only service right now is just going to be DB and I'll give it the name DB and then I can specify the image here the image is going to be postgress this image name comes from Docker Hub here now if you do this it's always going to be the latest version but let's lock it down to the latest stable version which is 16.4 so I'm going to say colon 16.4 now you can see in their command here there are some environment variables that we can pass in like postgress password and we essentially want to use the values that we defined in our own EnV file and pass those in here so within our Docker compos there's a section called environments and here we can specify each of those so so want my postgress

password to be equal to the DB password that I set inside of my EnV and then we also need to set up the user and the DB name and if we look in their documentation here we can see have some other environment variables available to us like postgress user so I'm going to set postgress user equal to DB user and lastly we need the database name and so this will be postgress DB so here we'll say postgress DB is DB name now by default if I spin this up there will be no way to connect to it so essentially what I want to do is I want to map the port of the database running inside that container to my local machine so right here we can specify ports and I can say map the port that I specified in my EnV to 5432 running inside the container so if on my local machine for whatever reason like Port 5432 is taken technically I could go into my V here and change this to something else and I'd still be able to connect it to my database now the last thing we want to do here is make sure there is some

persistence because every time we spin up and spin down a container all of the data is lost unless we specifically put it inside of a volume so if we look in their docs they tell us where the data inside the container is stored and we want to map that to a folder on our machine so right here I'm going to specify volumes and we'll pass this value in here and I'll just specify a folder inside this current directory so I'm going to do Docker data/ DB and essentially all of the data associated with that postgress database is going to be stored on my local machine so if I ever get rid of that image or delete it whenever I spin it back up I'm going to have that persistent data because it's going to map it back to the folder inside of this repo now I would never want to push this up to get or anything like that so I want to make sure that Docker data is inside of my G ignore so if we head over to our G ignore just make make sure we throw this in here so we're not accidentally committing all of that postgress data to our git repo so there's one issue I accidentally said

environments instead of environment um and then the other thing is Docker actually doesn't look for env. loal it just looks for a EnV file so we we could point it to env. loal but I'm actually just going to rename my local EnV file to EnV because nextjs should still pick that up but now Docker will pick that up automatically so with that if I run Docker compose up it should see that EnV file load those environment variables pull the postest image and start it up awesome so I have a postest database running on my machine and my app is ready to connect to it and so now here inside of my drizzle client instead of passing in a hard-coded string we should be able to pull in our EnV and then pass in database URL and now to see if this is working if it can actually connect to my Docker container that's running let's just import this file into my homepage so to test this out I'm just going to do a simple query that lists all the information in the PG catalog PG tables

Chapter 66 1:47:04

drizzle configuration

uh but if it can't connect to the database this will error out and if it can we should at least see some info printed out here so let's try it out if I refresh the homepage there we go it was able to uh spit out some info which is great um so yeah there's all that internal information now if it wasn't able to connect to the database we should see an error so let's actually do this if I kill the docker container and then refresh the page here we get an actual error that was thrown that deals with the fact that it couldn't connect to the database let's start the docker container back up and then if we refresh the page again good to go so now let's actually Define our own tables and schema and then get that run against the database so for this I'm actually going to use the schema that's provided for us by next off that gives us basically our users table and our accounts and our sessions table and then we'll modify it slightly so if we look in the next off docs take a look at the postgress schema this is going to be what we need ultimately I really just want the tables

Chapter 67 1:48:02

Defining drizzle schema

here and I'm going to show you how we can actually Define these in separate files and make it a little bit more maintainable when we have a bunch of tables in our database so I'm just going to grab these table definitions and then in the folder here inside of DB I'm going to create a folder called schema and the way I like to set it up is to have an individual file for every table sometimes if if the tables are related I'll maybe put those in the same file but my database grows I don't like having all of those tables defined in a single file so let's actually just start with the users table so if I create a file here called users. TS let's actually throw all of that table definitions in there and then get rid of everything except for the user definition now I need to import all of this stuff from PG core and then we can import these from PG core as well now you can see the schema that they provided for us is actually using a text data type for the ID column and then they're using the crypto function here to generate a uuid hostress actually includes the ability to generate uu ID

so I want to do this inside of the database instead of inside of application code so instead of making this text I'm going to use uid and you can see that we can import that in from PG core and so now this column type is going to be uuid and now the default function here instead of calling crypto do random uid we can actually call the internal post grass function and let's find that in the drizzle docs so here in the docs you can see some examples where they're using that uid type and there actually is a built-in function called default random that comes off of uuid that under the hood is going to call genin random uu ID which is a built-in postgress function so instead of calling that we can just say default random like so now it's going to be a uu ID and the database will handle automatically generating that whenever a new row is inserted for a user now we could use text for the name and the email but I'm actually going to use varar so that way we can limit the length here and so for name we'll use varchar which comes from PG core and this is the one issue you might run into when you're using drizzle

is because all of these things are defined in separate libraries make sure you're importing from PG core and not MySQL core so we want varar and then here we can specify the max length and I'm just going to set this to 255 and then for the email we'll set this to varchar as well and then I actually looked up what is the maximum length of an email I came across this stack Overflow post talks about 254 characters some people are mentioning use 320 then there's like this RFC but I will set this to 320 the other thing is I'm going to add a constraint on the email that says it cannot be null as well and then we'll bring time stamp in from PG core and then I'm also going to set this as not null uh and then lastly we have our image so also set this to a varar and then let's look up what the longest possible URL could be so there's not a straightforward answer but it seems like search engines like URLs less than 2048 and certain browsers might certain older browsers might have a limitation of like 2 83 so we're going to go with 2048 as

the max length on this URL and then we're also going to set this to not null awesome so got our our basic user table set up and I'm actually going to export this as the default export so export default like so now we're going to define the rest of the tables as well but the other thing that I want to do is create an index schema file that exports all of the tables that I defined so I'm going to create an index file in here and I'm going to say export default as users from from that users file there and so every table I Define I'm going to export it from here and now I have all of my tables defined in a single place so I can use this schema in the database connection and also in our drizzle kit config which we'll configure in a little bit and then now let's define our accounts table so in the schema folder I'm going to create a file called accounts. TS throw this in here we'll import this from PG core import this from PG core and then go through and update this stuff so uh user ID uh which

references users. ID this actually should be a uyu ID column because that's what we set in the users table and then I can import the users table inside of this file so if I import users uh this is how we set up forign key references so we've defined the user ID column and it's referencing users ID column um and then we need to import adapter account type that looks like it comes from here but it's not defined it's actually adapter account and we'll use that value here now I'm not sure what the max size of these could be so we're just going to leave those as text uh we'll import integer from PG core and then everything else looks good and then down here is where we can Define further constraints and so this is actually defining a compound key where the provider and provider account ID are unique so for any given user from Google there can only be one Google user that has one specific Google ID great so now let's actually just export this as default and then we'll export it from our schema as well so if we head over to the index

we're going to export default as accounts from the accounts file and then the last table we need is the sessions table now there are these two other tables they're only needed in certain scenarios like verification tokens is used if you're using like email magic links and then authenticators I think is a new thing in OJs but we just need the sessions table so I'm going to grab sessions and we'll create a file here called sessions. TS pull in these Imports we'll import the users table here but again because we defined their ID as a uyu ID we're going to specify this as a uu ID and then we'll pull in timestamp from PG core this looks good to me and then we'll export this as default now in our schema file we will explicitly export the sessions table as well great now I'd like to take this schema and actually push it to the database so actually create these tables and their corresponding columns in the postgress database that I have running inside of Docker and to do that we're going to use drizzle kit so if we take a

Chapter 68 1:54:20

drizzle kit config

look at the D drizzle kit docs you can see that we can define a drizzle config so we'll grab this and then in the root of our project we're going to create a drizzle.

config.txt just like that and then another option I want to specify is where to put the migration files and I like everything to live inside of this DB folder so there's an option called out and I'm going to specify this as Source DB SL migrations like this and then we can specify the database connection with this DB credentials so I'm going to get rid of this option there and the URL should be from our EnV file so I'm going to pull in EnV from there and we'll grab that database URL string so now I'd like to generate the migration files so migrations are just SQL file files that will be the data definition language for actually creating these tables that we have defined here now some people don't like to have a migrations folder some people will typically just use DB push which means write these changes directly to the database I do like migrations But ultimately I don't like a lot of migrations so typically when I'm early in development I'll be iterating on my database a lot and I really won't generate a migration until I know the

structure of my database is in a stable state but for now these are our initial tables so I'm okay with a migration that def our initial tables once I start actually building out my application I would want to make sure that I've gotten my tables defined in the right way before I create another migration but let's try to generate some migrations so if I do an MPX of drizzle kit generate we do get an error that says the database URL is an invalid URL my suspicion is that it's not properly expanding the value here so we might have to bring in a library that does that for us but let's just log it out so inside of our EnV before we parse it let's literally log out uh process. env. database URL and then if I run this again you can see that it didn't expand the environment variables here so to fix that I'm going to bring in a EnV package that will expand those values before actually loading them into to our EnV schema so for that we need a library called uhv

and then another one called EnV expand and now inside of my EnV file I'm going to make sure that we run EnV expand before actually parsing the EnV so here I'll import config from EnV and then we'll import expand from EnV expand like so and then I can call expand with config like that now let's hope for the best if I try to generate uh this is good and it didn't say invalid URL but it does say that we need our node EnV because right now our code is running outside of the context of nextjs so node V isn't actually set so let's make sure that we set that in our EnV so here I'm just going to set node EnV to development and then try running generate please install the latest version of drizzle om so I did some debugging there actually is an open issue over on the drizzle repo and what seems to be the issue is I am running npx drizzle kit generate but this user

says if you run npm or pnpm in my case drizzle kit generate that will work which I don't understand why but that works and so that actually generates our migration file Force so if we take a look this actually generated a folder called migrations and inside of there we have a SQL file that defines all of our tables as we Define them in our typescript schema files so now that we have a migration SQL file we actually want to run these against the database so let's set that up in our DB folder let's create a file called migrate TTS and we can see in their docs that there's a migrate function function that we can bring in and we can actually execute that against the database so I'm going to copy this codes here and paste it so first up if I want to use top level of weight I have to set Target to es 20107 or higher in our TS config so let's do that if we look in the TS config uh Target isn't actually set so we can just set this to like es2020 that

Chapter 69 1:58:08

drizzle migration set up

should be compatible with most places that I would choose to deploy this okay awesome uh now I don't actually want to redefine my connection in here here I want to import it in but you'll notice the one thing is we do want to pass Max one as the option when we're defining our post grass connection so I'll do that but I want to get rid of this and this and I want to import DB from the other file that we defined it in so let's just import DB from that file there and you'll see here that it was trying to call the connection. in so we'll need to export the connection as well so if we head back over to our main file we actually want to export the query client as well and then we need to pass in that Max one option there but Max one should only be set if we're migrating so we'll set up an environment variable for that but now we're exporting the query client and I'm going to rename this to client and since we're exporting it we'll import it in our migrator file and then we can call client. end there so we'll import DB and then we'll also import that client and

here we can say client. end now to determine if we are migrating or not let's create an environment variable that will set only when we're migrating so if we head over to our EnV file and so here we'll create a variable called DB migrating and this needs to be a booing but when we're reading in the EnV everything is a string so if you look at the docs for this Library uh it has a recipe here for reading in strings and turning them into bullings and essentially we specify that it can only be true or false and then after that if it's equal to true then DB migrating will be equal to True otherwise it'll be equal to false and now when we're creating the connection we'll look at that value to set the max number of connections so if we head back over here we'll set max equal to 1 if env. DB migrating is true then it will be one otherwise it will be undefined and so that way we won't set max connections when we're not migrating the database so that looks good uh the other thing is inside of the migrating file we don't

want it to run unless DB migrating is set to true so let's actually exit early here so we can say uh if we are not migrating and also we'll need to import our V like that so if we're not migrating we are just going to throw an error you must set DB migrating to True awesome so if we're migrating Max connections will be set to one we'll then pull that connection in and the last thing is we want to point to the correct migrations folder uh we could hardcode it in but let's actually import it from our drizzle config right because we specify it here I don't want to Define it in multiple places so right here I'm going to bring in my drizzle config and then we can specify config do out like that now uh config dotout can be undefined but I know that it's not so I'll just do exclamation mark so that tells Ty script that hey I know that that's not going to be undefined so this is looking good now let's create a script in our package.json that specifically sets DB migrating to true and then runs this migration file here

so now in our package.json we can set up a script I'm going to call this DB migrate and here we want to set DB Myra to true and then run drizzle hit migrate like that so now let's try running this task so if I say npm run BB migrate it says migrations applied successfully awesome so now uh if we go back to our homepage where we're listing out the table schema we should actually see these tables that just got created uh but one thing is our EnV file says that DB migrating is required but in this case we want it to be optional because it's not it's only ever going to be defined if we're actually running migrations so in our EnV let's actually set this as optional so I can do z.

string etc etc do optional and so now we should be able to start up the app cool and if we visit the homepage we should see all those tables listed out in the schema awesome so we see drizzle there we see account session and user so those tables are living within our database awesome now one thing we can do is we can also spin up the drizzle kit studio and that'll show us our tables as well so if I do mpm drizzle hit Studio that launches it and if we open it up we can see that we have an account table a session table and a user table awesome so at this point we now need to link these tables up to next off so it's actually writing data to these tables and one thing we should do to make sure that this code works on other operating systems as well is we can use a package called cross EnV to make sure that like if somebody is running this code on Windows it's still able to set environment variables there because technically this Command right here will only run on Linux and Mac so we're going to install the cross EnV package so I'm going to install as a Dev dependent

cross-v and you can see to use it we just need to specify cross EnV before our actual command so over here I'll specify cross EnV and that should work just fine so I can try running those migrations again and in this case didn't have any migrations to run but it was still able to set that environment variable and run the script so to connect this up to next off we can bring in the drizzle adapter so let's actually install o/ drizzle adapter and then now when we're defining our next off options we can pass in the drizzle adapter so here in our config and then off we'll set the adapter as the drizzle adapter so I'm going to import drizzle adapter from o drizzle adapter and then I can import my DB from at/ DB now you can see in their docs if your tables are potentially called something else you can pass them in here and set which table is which from your schema uh but by default if the tables names are users accounts and sessions they will all hook

Chapter 70 2:03:41

next-auth drizzle adapter set up

up automatically whenever you pass in that database connection there now we are getting a type error and this is because we're using the drizzle adapter which is technically for next off version 5 we're still using version 4 so in this case we're just going to have to ignore this typescript error so I'm going to say TS expect error and then of course we'll have to disable our linter error there so now next off we'll actually use this database connection to put users into the database and create sessions and different things like that we head back over to our app I'm going make sure that I delete all of my cookies and everything else cuz this was before we're actually storing anything in the database so let's just delete all my local storage all my cookies do a hard refresh here let's also get rid of this query that's in the main page so if we go to our app and then page. TSX let's just remove uh this table query here cool and now let's try signing in so if I click sign in it redirect us back to an error let's take a look at

the console see what went wrong okay so I found this issue open on nexo that talks about how well by default on the initial insert it is null but then it gets updated afterwards um technically we can tap into like the profile call back I'm not going to bother with it I'm just going to update my schema so if I head back over to my user table instead of setting email verified as not null we'll allow it to be null so that nexo can do its own thing whenever it's inserting that user now I don't want another migration just to change the field from non-nullable to nullable so I'm literally just going to delete this migrations folder and I can also just do a push which will change the schema in my running database so let's try that if I do mpm drizzle hit push so that updates the database to remove that null constraint and then I'm just going to regenerate those migrations so if I do npm drizzle hit generate that should recreate the migrations from scratch and

now I have a migration where the email verifi doesn't have that notnull constraint so that should be good now let's try logging in again I'm going to click sign in and it worked we're actually logged in you will notice that I didn't get redirected to the profile page but we need to fix that and I'll talk about why in a second but to see the data actually in my database let's start up drizzle kit studio so if I do mpm drizzle kit studio if we take a look we should have a user in our database we do so we have the CJ user here it has its account set up here and there is one session in the database here awesome now if you remember earlier we actually set up a middleware that should redirect the user if they are not logged in and if we take a look at the docs for this middleware there's one caveat it only works with the JWT session strategy and so by default whenever you add a database adapter it sets the session strategy to database and so the built-in middleware is actually not at all

Chapter 71 2:06:52

next-auth middleware issue

compatible with session strategy where it's storing the sessions in a database now I've actually debug this a ton locally trying to create like my own middleware function that like pulls in the session and it's not ideal and so we have two options we could make it so that we don't store the sessions in the database so if you go to your next off options here you can set session and then there's a strategy option and you can set this to JWT instead of database and so if we set that and then we log in again you can see that we actually can get to the profile page uh but at this point that just defeats the purpose of even having our sessions table uh cuz if we if we clear out this sessions table and then log the user out and then back in you'll see that with the JWT strategy we aren't storing sessions in the database at all so if we refresh over here yeah there are no sessions in the database um and I want my sessions to actually be in the database so here's

what we're going to do I am going to leave the session strategy as database and I'm going to get rid of the default middleware that we have defined here now I will point you to the docs over on OJs that talk about the the problem here where essentially because these middlewares are running in the edge run time they potentially don't have access to the database adapters and they tell you how you can set it up but ultimately you do have to set your strategy to JWT but we don't want that so what I'm going to do is just create a helper function that will check to see are we logged in and if not we'll redirect the user and any page that needs to be authenticated is always going to have to call that function at the top of the component so let's do this in our source directory I'm going to create a folder called utils and inside of there I'll create a file called require off then we'll export a function and here we'll use that g server session function that comes from next off we'll pass in our off options and we'll grab the session here by

awaiting this we'll have to set this as an async function and now we can check so if session. user does not exist we're going to redirect them and so we'll pull in redirect from next navigation and in our case we're just going to redirect them back to the homage um otherwise we just allow the rest of the code to run so we're not going to return anything or do anything else and so now any page that needs to make sure a user is authenticated is always going to have to call this as the very first thing in the page so that they get redirected if they're not logged in and so to see this in action let's call require off in our profile page so if I go to profile here right at the top before I do anything else I'm just going to await require off we'll import that in and now let's try logging out and then we can try visiting the profile page so if I go to SL profile you can see that we get redirected back so it's a little more cumbersome but basically any page that needs to make sure you're off we're going to have to call this function here now one thing we

can take into account is if I've already determine that the user actually is logged in then this session will not be null so I can take advantage of that here so basically I can use typescript and say hey I know that session's not going to be no because I already checked for it and then down here I don't have to check to see is session undefined so that's one nice thing about checking for the user being logged in first so at this point we have a pretty decent setup right users can log in we have a database it's storing all the user info and sessions uh now we're ready to start actually working on features and so one thing I want to do is just set up a basic guest book so anybody that's logged in can add a message to the guestbook and now in nextjs we can use server actions so essentially we can Define functions with the Ed server directive and actually call those directly from either a user action like a button click or like a form submission and so if you look at the nextjs docs they show you how you can implement this but there are some nice libraries out

Chapter 72 2:10:53

Next.js Server Action Libraries

there that make working with server actions a whole lot nicer and one of them is called Next safe action and this makes it really easy to work with in a typesafe way and also to ensure that you're working with validated data so this library integrates with a lot of different validation libraries and it makes it so that when you're defining a server action you can actually specify a schema and that will always be validated when that action is being called and then you can write your code inside of your action here and then inside of your client components you can directly call that action like so so this library is really great um and it also has Integrations with things like react hook form and so if you're using react act hook form to do form validation they have an adapter here where you can actually hook it up to work with next safe action so you have your schema and your action defined here but then you can use their built-in functions to help get like validation errors for your form so this is pretty cool and one of the things about next safe action is they

also have this idea of just direct execution of those actions so they don't necessarily have to be called in response to a form submission the way that we have this set up you can literally call these functions and return anything you want from those functions now there is guidance from nextjs that says you shouldn't use server actions to like query for data but technically you can but ultimately nextjs wants you to only use actions for mutations and another library that I came across is called conform and it's similar in that it allows you to define a schema in this case with Zod but I found it typically requires a whole lot less code especially if you're trying to do like in-depth form validation and has like graceful fallbacks so if the user's device doesn't support Javas script it's still able to call the serers side action and there's a whole lot less required to actually hook up these inputs to use the form itself so I really like conform I can see a scenario where you're potentially using both of these libraries in an application uh but for the simple guestbook that I'm about to implement I'm going to use conform

Chapter 73 2:13:10

Building a Simple Guestbook

for that so inside of my app I'm going to create a folder called guestbook and inside of there I'll have a page we'll export the guestbook function and then I'm just going to return a card here so we'll pull that in from next UI give it a card body and we'll give this a Max width of medium automatic margin and then we'll say uh welcome to my guest book and then we'll set this H1 to have uh some larger text so we'll say this should be text 5 XL like that and then let's add this page to the Navar so if we go to our components navbar we can if the user is authenticated we're also going to push in the guest book page like that and so now I have a link to the guest book and we can get to the guestbook cool I'm actually going to make this a little bit wider by default so let's do Max width large cool and then let's put this text in the center that looks good to me so right below this let's create a form where the user

can type their message so in next UI they have this text area component which is what we'll use just for that and so right below this I'll have a form and I'll put the text area inside of the form pull that in from next UI the label is going to be message and then it'll say enter your message we're going to set this to have full width so we'll do uh width full so it should fill up the card and let's see what we get yeah that looks good to me let's just add a little bit of margin on top of the form sweet and so now a user can enter your message like hello world and then we need a submission button which will then send it to the back end we'll validate it put it into the database and show it on the page so let's add a button here says create import that and I'm actually just going to set this form as a flexx box so that way I can put some gaps between my elements here so I'm going to make it a flex Flex column and give it a gap of two so that should give some spacing between the elements and also now the button takes up full width which is cool um and now that I'm thinking about it let's add a little bit of margin on top

of the card as well so we'll give this a margin top of four sweet so if you take a look at conform you can see that we first Define a schema and then we can use that schema inside of our action and then also use that schema when defining the form itself uh but what I'd like to do is actually Define a database table and then use drizzle Zod to get a schema according to the database table that I Define so let's do that we'll head into our database schema and I'll Define a file called guestbook entry and so I'm going to have a table where we'll store every single entry in our guest book U now I'm actually just going to grab the sessions table as a starting point because it has a lot of the columns that we need like user ID so every entry in the guestbook table needs a user ID which is good and then we'll have a created at date and in our DB we'll call it created at and then we need a column for the message itself so we'll say message is just a text column called

message and this cannot be null like that now of course we should rename it so this is guestbook entry entries and we'll call this guestbook entries and so that looks good to me now we need to export this from our schema so up top we'll say export uh uh default as guestbook entries from our guestbook entry file and now that I'm thinking about it we should probably pluralize the file name too just to be consistent so over here I'm going to rename this to guestbook entries cool and then this not happy let's just do a Reload okay everything's happy now we actually want to get a Zod schema that corresponds to this specific table and for that we can use drizzle Zod so we can install it with npm great and then they provide these two functions where you can pass in the table and it'll give you back a Zod schema so let's use those and I'll Define an insert guest book entry schema and this is going to be a uh

Chapter 74 2:16:39

drizzle-zod

create insert schema from drizzle Zod and then I can pass in the table guestbook entries and so this actually gives me back a Zod validator that will specifically look for user ID message created at awesome now when I am actually validating the data that's being sent to my server I really only want them to be able to send the message right because in terms of security I'm going to set the user ID on the server side to be the logged in users ID and then also created app will get set on the server side as well and actually now that I'm thinking about it we can set this to default now so that way whenever a guestbook entry is created it automatically sets that created at date um and so basically for my insert schema I only want the message property and so we can actually chain this and use the omit function so this is just built into Z Zod and then we can specify that I want to omit the user ID and I also want to omit the created at so now I have a Zod validator that's going to validate that an object has a message property

now for this example it's very contrived because I have a single field here but you can imagine for more complex tables this is really nice because you can basically strip out the specific fields that you don't want the end user setting and you don't need to validate those because they're going to be set automatically um but you can get your schema accordingly so let's make sure we export this and now let's use it whenever we're setting up our action with conform so I'm just going to grab this example action Here and Now inside of guestbook I'm going to create actions. TS and we've defined this here awesome um and I also need to install conform so if we look at their introduction we can specifically add conform to react and conform to Zod so we'll install those and now we can import that Zod schema from our table definition so I'll pull this from DB schema guestbook entries and we want specifically the insert guestbook entry schema uh and so now this action I'm going to call it uh create guest book

entry it is going to parse the incoming form data and it's going to use that specific Zod validator to parse that data and if there were any validation errors it's going to respond accordingly and if not we can redirect in this case we're just going to redirect right back to the guestbook page and we'll also revalidate this path so that way nextjs knows that it needs to requer the database once we have all that hooked up and now once we know that it is a valid guestbook entry we can actually insert it into the database so I'll need to import DB and then we can do db. insert we pass in the table that we're inserting into in this case it is the guest book entries table so we'll import that in and then we can specify our values in this case submission should have our value which is the validated value which just contains the message string so let's use that in our insert we're going to say the message is submission. value. message great uh but drizzle is complaining because we need

to specify the user ID and so we can grab the user ID from the current session and so one thing I'll do to make sure that the user is logged in we'll call that require o function that we defined earlier and so now if someone attempts to call this action and they're not logged in they're going to immediately get redirected uh but if they are we're going to validate it and then we can grab their session information to grabb their user ID so here we'll say the session is get server session pass in our o options and then we can specify the ID as session. user do ID which we don't have access to but we want access to it so let's actually modify next off so that way it includes the users ID in the session so we can do that by heading into our options and So within these options we have access to what are called callbacks and so we can actually tap into when that session is getting created so yeah we get access to the session and then these prams will

Chapter 75 2:20:36

Add user id to next-auth Session

include the session itself and then also the user from the database and so essentially what we want to do is we want to set the ID on the session to be the user ID so we'll say session. ID is user. ID like so and then we'll return the session here now we get a type error because the built-in session type doesn't have that ID property so we need to actually overwrite it so in our app we can define a custom type that overrides the session we'll create a folder called types and inside of here we can create our next o.d. TS file and then we can actually override that session type now to do this we can declare a module that is the next o module and then in here we can override that session interface so I can define an interface called session and a session has a user property and we want that to have an ID property which is a string in our case like a u ID now we also want this user to have all of the default properties of a session so we can actually import that in and extend

it so if we join this type with default session which we can get from next off we'll grab specifically the user property inside of there so now user will have all the properties of a default session but we're also adding ID onto it and now that we've defined this type over here if we give it a Reload um it doesn't stop complaining because actually we don't want to set it on the session we want to set it on the user and then set their ID to be the user's ID awesome so now whenever a user logs in that ID property is also going to be on the session which means over here we will get access to it but again inside of this action because we're requiring oth we can basically say that we know this session is not going to be undefined and we can pass it in here uh but actually this needs to be user ID okay so that should do it so essentially as long as the user is logged in and they've sent us a valid submission that has a message property we'll then insert it into the database and then redirect them now let's get the form submission

working so here inside of conform you can see that the form has to be a client component because of the hooks that it's using so let's actually Define a client component here inside of our guestbook page so in here I'm going to define a file called page. client. TSX and I will export a function from here we'll call this the guestbook client and then we're going to put the form inside of this client so I'm actually just going to grab this form here and return it we'll import these components and then on the main guestbook page we're going to add that guestbook client right there awesome so at this point we can start using the hooks provided by conform so I'm actually just going to copy this example and then update accordingly let's update these Imports and then we'll import our action so our action is actually called create guestbook entry and so we import that in there awesome me remove these comments and now we can pass in the schema as well and so in this case the schema is that insert insert guestbook entry schema so we'll import that in and now we can hook up

the form so if you take a look here on the form itself we specify the form ID we can use onsubmit which get passed in and then also pass in the action so I'll just copy all of this and we'll add it to the form like so then we can specify the values here so we really only need to specify the key and the name on our text area so the key here is going to be fields. message key and then the name will be fields. message. name so that hooks those things up and then we can display any validation errors below it so if we look at next UI let's see if they have an error State yeah so with an error message we can see that we specify the error message property and we pass in is invalid as true so let's do that here we'll say error message which is fields. message. errors awesome and then we'll say is inv valid is going to be

fields. message. valid and we'll say if it is not valid like that cool so now this will automatically hook up validation on blur and on input so if I Tab out of this text area the validation should run we should see that uh error if there was one and then whenever I click submit it's also going to run the validation on the client and then after that it'll call the action on the server call that validator put it in the database etc etc so let's try it out if we head back over to the page uh our page. client needs to be marked as a client component of course we forgot to do that but this should be a use client like so and now if we head over to the guest book and I Tab out we can see that the field is required that's awesome but check this out if I disable um the on validate function here we can send it to the server without actually validating it on the client so let's do just that I'll refresh the page let's take a look at the network and so if I try submitting with an empty message nothing

happens um I believe we need to set the button type as submit that doesn't get set by default in next UI okay so we'll do that and now if I click submit it actually calls our serers side action and then our action responds with the errors and then those errors get displayed here so it's important to note that we're actually not even doing client side validation here it was able to receive those errors from the server side and then display them on the form so now if I try putting it into the database uh we actually haven't created that table yet so we should run into some kind of weird like database era yeah gu guestbook entries does not exist so let's actually create the migration run it against the database and then we should be able to insert guestbook entries so here I'll do mpm drizzle kit generate that should generate the migration file and then I'll do npm run DB migrate and that will create that table in our database awesome and now we should be able to create some guestbook entries so for that I'm just going to reenable the client side validation

and then on our guestbook page let's display the actual guestbook entries right below that form there so here I'm going to grab the entries and this will just be from dbquery do some table name. find many something like that um but one thing I I forgot is in our database connection we can actually pass in the schema and then we can use this query syntax here so if we head back over to our database and then where we Define the database here we can actually pass in some options where we can pass in the schema itself so if we import all of those tables so import Star as schema from our schema file now we should be able to query against the database because it knows about all those table names so right here if I do db. query dot you can see we have access to those tables and I specifically want guestbook entries and then we want to find mini like so we're going to make this an async function and then for now just to see them on the

page let's actually just show the Json um so I'm going to do a json. stringify of our guestbook entries with some spacing great okay Moment of Truth uh by default you can see there's nothing in the database and then I can send a message hello world click create it got inserted and now we actually see it on the page that's awesome so I can add as many as I want like it works sweet um we see there are some errors happening though um parse with Zod is not defined ah uh the the import got removed um earlier when I commented out this code so we need to just make sure that all of this gets imported okay that looks good refresh and we'll try again sweet so at this point let's clean this up a little bit let's actually show like the message box and then maybe we have like the user info below it so for that I'm actually going to set up a relationship between the guestbook entry table and the user table so if we head to the definition for the guest book entries we can actually Define our

Chapter 76 2:28:36

Defining table relations with drizzle

relations here and we'll call these the guest book entry entries relations and we can define a relations here from drizzle omm so we pass in the table which is going to be our guest book entries table and so I'm going to grab an example here from the drizzle docs and just kind of fill it out with my own stuffs so here we're saying that we want a user we'll say one users which is specifically our users table and the field is going to be uh guestbook entries. user ID and it references the ID column in the user table so this sets up the relationship so that I can query for a guestbook entry but also include the user object along with it now I'm going to export this and then also export it from my schema definition so over here in my schema we're also going to export uh guestbook entries relations uh from that file as well and now whenever we query for guestbook entries we should be able

to include their user info so if we head back over to our guestbook book right here we can pass in a with option and here we're going to say we want their user tro and so now whenever we query it's going to attach that user object so we can like show their name and and show their Avatar so we can see here that now when this page loads we get the message info but we also get that related user info as well and so to display this uh let's actually just use a card from next UI they have this cool little example here that uh kind of looks like a user card with their info we'll probably do this but then also have like the message and then like the created at date right there so let's copy this codes and then we'll here we'll iterate over the guestbook entries and actually display out this info so we'll say entries. map that's going to give us each guest book entry and then for each one of those we want to render out a card like so which is going to come from entry but now I'm realizing we forgot to put an ID column um on the guest book entry table so let's do that um it should be a pretty

easy change uh if we head back over to the database uh we can copy the ID field from the user table we'll just throw that into the guestbook entries table we'll then generate this migration pool and then we'll apply the migration and um now I'll actually I'm just going to use uh drizzle Studio to just go in and delete those existing guest book entries that don't have an ID uh so let's run jel studio so in here if we look at guestbook entries oh that's awesome um apparently the IDS were able to be generated after running the migration beautiful okay we don't have to do anything so at this point we just need to render them out cool so if I head back over to the page let's import all of these missing components and then uh get rid of this is followed stuff uh but now I'm realizing I actually want to put these inside of the card body here okay that's better and now we should be able to get rid of that Max width on these

individual cards cool and now we'll just set some margin around each of these cards so let's just give this a margin of two that should give some spacing above and around sweet and now let's get rid of all the extra stuff and and fill in our info so the Avatar source is going to come from entry.

user. image and then we can specify their name here which is going to be uh entry. user.name wrapped in quotes and then let's throw their email right here so entry. user. email sounds good and right here we can throw the actual message so this will be entry do message and uh we'll get rid of this extra stuff here so this is looking good and then down here we just want to put when the message was created so I'm just going to do that with this item here let's get rid of this extra stuff and then right here we'll throw the created at date so we'll do uh entry do created at um yeah and so this is a date object I'm just for now just going to say to to local string and that way it'll just render out the overall dat late sweet we have a guest book that has the users the message and the date when it was posted and so we can try again wow so cool your

site is great and create it ah there it is yeah and I guess another thing we could do is we could sort these where the most recently created is at the top so let's do that in our query here we can specify order bu and we'll return operators. uh descending based on the create date I think yeah so descending uh fields. created at that should work yes so now the most recently created are always at the top awesome now before I commit this I actually want to consolidate my migrations down to a single file uh and this is what I was talking about like during development there's lots of things that I forget or that I potentially change like in this case I forgot to add that ID column and now we have a single migration that that literally just adds an ID column But ultimately I want that to be all part of a single migration because it's all related and I haven't deployed to production yet so all of that to say I'm just going to literally delete this migrations folder regenerate it so that way I have just a single migration and

Chapter 77 2:33:27

Consolidating migrations during development

now this is going to be what I'm going to commit to the repo because this has all of my default tables and and it makes more sense to have this in a single migration versus like multiple small migrations now before I forget one thing you should always do when you're setting up a template repo like this is have a sample EnV file so I'm actually going to duplicate this file and call it env. example and now any user that clones down this repo knows all of the fields that they need to figure out and of course I'll remove the actual secret info cuz that's up to the devs to specify themselves like so now that's all the time I have for in this video but stay tuned because we're going to be using this starter kit that I've created to build other applications and also show you how to do things like deployment and work with more complex schemas and more complex page structures and explore a lot of the other features of next s that we haven't explored yet now if there are specific things that you do inside of your nextjs starter kits or inside of a xjs app that you spin up I'd love to know about it let me

Chapter 78 2:34:10

Create sample env

Chapter 79 2:34:32

Thanks!

know down in the comments and also if there's anything in particular that you'd like me to explore more or dive deeper into let me know in the comments as well all right that's all I have I'll see you in the next one [Music] oh

Quote it with credit and a link. Quoting Syntax