User Authorisation in Next.js + tRPC + Prisma + Postgres + JWTs. Pt-2

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right and now that we have the back end part or we can say the server part of our application ready the next thing we will do is create our front end part of our application open up the terminal and run the command pnpm at 10stack SL react D query then we will have 10stack react query dep tool also we will have an excellent public query then we will have react hook form then we will have hook form resolver then Tailwind Dash merge react hot toast then we have trpc SL client then we will have trpc react query these are all of the dependencies that we are going to need to build our frontend part of our application we are adding react query version 4.8.0 from the 10 stack it is a powerful library for managing and caching state in react application making it easy to fetch and update data additionally we are including the react query Dev tools a developer tool set for debugging and inspecting react query in the browser it is also going to provide us insight into queries and cache status and then we bring in the sent plugin for react query it is a linting plugin that helps enforce best practice and cash potential issues when using react query in our codebase we also have react hook form with its resolver from the hook form it is in library for handling forms and react application and it will provide us a convenient way to manage form State validation and submission for styling we of course incorporate a Tailwind merge package it is a utility for merging Tailwind CSS classes dynamically also we have a react hot toast it is a convenient toast notification message it is is very simple and it is customizable toast notification library for react application then finally we include trpc client and trpc SL react query for trpc integration with react query it is libraries for implementing type safe remote procedure calls in react application that's it and now let's update the tailin CSS configuration file over here we will remove this background image and we are going to customize our theme to extend its default setting we will start by adding a custom font family called Poppins and we will configure the container to be centered with some padding and specific screen with limits on larger screen it is going to be 1,125 pixel and on Xcel and 2 XL it is also the same so let's save this file all right let's now move on to setting up react query and the trpc client within the next Js project first we will need to initialize the trpc client so to do that navigate to the utils directory and inside this we will create a file named trpc dots in this file first we are going to import the app router type from the trpc router in our project next we bring in create trpc react from trpc SL react D query then we create a trpc instance for react by calling create trpc react with our app router basically this script is creating a trpc instance for react using the trpc react function it uses the app router type to define the trpc router for the application this instance will allow us to make types safe remote procedure calls in our react components using the defined routes in the app router now we want to set up a a query client from react query which will create a new instance that will manage data caching and fetching in our application so create another file in the utils folder and name it as query-specific react query finally we are going to export this created query client instance to be used throughout our application and as all the components that we have inside this app directory are now server components by default and since we want to render the trpc and react query providers only on the client side we need to create a client component in the next J this is achieved by including the use client directive at the top of the file so in the utils folder let's create another file named trpc provider. TSX in this file we start by declaring use client directive at the very top then we import necessary dependencies like query client provider and various utilities we also import our trpc instance trpc and the query client we created earlier additionally we are importing the react query def tools for debugging purpose now we Define a react functional component drpc provider that reps our application with drpc and react query providers inside it we determine the URL for our trpc request based on the environment next we use the UST State hook to create a trpc client with specified links and configuration inside it we enable logger link for login purposes next we configure the HTTP bet F link so that it can handle trpc request with the specified URL and fetch option then let's utilize the get fetch function to obtain the default fetch function and also we make sure that the credentials are included in the request for authentication we also use super Json as the transformer for serialization and deserialization of trpc data next we prep our application with the trpc provider and query client provider we also render the child components and including react query dep tools for debugging now we want to invoke the procedure on server so that we don't need an HTTP request this is going to be a server side function it is going to utilize create Asing color function we created before inside the util directory let's create one more file which is get o user. TS in this file let's start by importing the necessary dependencies and utilities then we Define a function get o user that fetches authenticated user information now we create an asynchronous drpc caller using Create async caller and then we use the trpc caller to fetch users information we are also going to handle cases when the user is unauthorized and if the user is unauthorized we redirect them to the login page and should redirect set to true and also we return null if there's an error or the user is unauthorized so in summary get o user is going to use trpc to fetch authenticated user information it will also allow for optional redirection to the login page in case of unauthorized access the function will also then return the user data if successfully feted and it is going to return null if there's an error or the user is unauthorized with the option to redirect them if needed perfect now we proceed to create reusable components that can be utilized in various sections of our application we will start by creating a header component which will render navigation links dynamically based on the user authentication then we will fetch users data on the server and render the links based on the information so we will convert our header component into a server side component so to start off let's create a component folder into our root directory and inside this component folder let's create a file named au- menu. TSX so in this file first off we are importing the necessary tools and utilities we import query client from the utils query client then we import trpc from utils trpc we also import link from next link we are also going to use use router from next / navigation we also need a toast from react hot toast then we Define the O menu component inside it we grab the nextjs router using use router within this component we will have a log out function called logout FN that comes from the trpc instance if something goes wrong during the logout we show an error toast and if log out was successful we do few things on success first we clear the react query cache then we show a success toast log out successful and then we redirect the user to the login page now let's return the jsx for rendering the pro page link and log out functionalities inside this we are going to use nextjs Link to create a link to the pro page and then we have another list item which is like a button for logging out when click it will trigger the log out function so in short AU menu component is a small menu just for authenticated user it provides a link to the pro page and a button for logging out the log out button is going to trigger the logout user mutation from trpc and if log out was successful it is going to clear the react query cache and it will show us the success toast and if any error occurs during the logout process we display an error toast and next now we are going to create a header component in this component we will use get o user function to fetch users data by invoking the get user trpc on server now we will create a header component in this component we will use get o user function to fetch user data by invoking the get user RPC on the server so in the components directory let's create another file named header. TSX first up we import some Essentials like link for nextjs routing o menu for the user menu and get o user to check if someone's logged in then let's declare the header component inside it we check if there's a logged in user using get o user now we are going to customize our header so in the return statement we will have a navigation inside this we have one link Allstar at the top left of the page then we also have a link to the homepage and if there's no one Lo loged in we will show links for registration and login and if there is a logged in user we will bring the Au menu for propage and log out link lastly we are going to export the header component so now that we are also done with the header. TSX file let's save this file now we are going to create two components a spinner and a loading button that uses the spinner component so let's open this and in this component we create a new file named spinner. TSX this is a react component which is going to bring a loading animation first we start by importing react and tww merch from Tailwind merch and then we have props for the spinner it's withd height color and background color set all of it to string then we have the spinner component it's width set to 1.25 FR height also set to similar then we also have color and background color this spinner component itself is an simple SVG based spinner it is going to provide a pleasant visual cue for loading State the SVG structure start with the role classes Dimension and other attributes and here we are using Tailwind CSS utility tww merge to handle the dynamic classes color and background color are dynamically applied based on the props then we have two parts that are going to define the Spinner's circular motion and shape finally we are going to export this Nifty spinner component and now that we are done let's save this file and you don't need to copy all of these values I'm just going to provide a repository for this project so you don't need to worry okay so save the file and next up we are going to create a loading button component so inside this component folder let's create one another file named loading dasb button. DSX this is going to be a versatile button with the built-in loading State handling it is going to offer a very nice experience during async operations so we start by importing react DW merge and Spinner then we Define the loading button prop types that allow customization of button color text color and loading State the loading button component itself is a react functional component that is going to render our button and loading is set to fall the buttons appearance is determined by the Tailwind CSS utility class making it easily customizable we use tww merge function that is going to combine the dynamic Tailwind classes based on the prop and the content inside the button changes based on the loading State when it is loading a spinner and a loading text will be displayed and when it is not loading the original button text will be displayed and that's the loading button component with loading indicator so let's save this file also next we want to create forms our application is going to have two different forms one for the login and second one for registration so in the components folder let's create another file and name it as formin dosx inside this file we start by importing react from react we also import use form context from react hook form use form context it's a hook that provides access to the form contacts including methods like register for form registration and validation and be set types for every form input the form is going to receive three props label name and optional type for the input field and all of these set to string then we set form input to render a styled input field along with the label and error message if there's any validation error we are then destructuring form related methods and error from the from the form context and then in the written statement we are going to have jsx structure it is going to represent a labeled input field with the dynamic styling and validation error handling here we are displaying the label for the input field then we use an input field with the tailin CSS and we use register for form integration and here input type is set to type and we are also going to display any validation error if they exist so now that we are also done with the form input element let's save this file also next we are going to create our homepage the main landing page of our application so navigate to the app directory and inside this open this page. TSX file so in this file here we start off by importing header component then we have the home component that itself is a functional component which renders a header and the main content section so we start by including the header component for a consistent navigation then we have a main content section with the dark background and minimum screen height inside it we are going to have one div which is going to show you the welcome to Allstar page all right and then down here as you are seeing here we have several divs which is basically showing us the blogs but these are not blogs okay these are just a specific div but here you can include your own blog component instead of just writing out a specific divs just like this so these are all of the images that we still don't have in our application so what we will do is we will open this public folder and I will bring all of these four images in it and there we have all of the four Images right now so let's save this file also that's the home component it is going to provide a clear and style introduction to our application now that we are done with our homepage what we are going to do is we are going to start the dev server by running the command pnpm de and then our application is started on Local Host 3000 so Control Plus click on this and there we have our application running on Local Host 3000 pretty amazing isn't it but you can see here that we didn't got image for this so let's check what's the error so head back to the vs code and there we have this error which says that the requested resource isn't a valet image this one where is it okay over here so we have this fotus over here heck one over here John one over here here and then this okay so I will bring in this image okay I didn't brought this image over here head back to the Local Host and refresh this and there we have our image now all that is done when you click on this register it is not going to take you to any page because we still haven't created it so now the next step is to create a register form right so the user can register themselves on our application so for it in this app component we are going to create one another folder and name it as register inside this let's create one file which is register D form. DSX form validation is done by react hook form and of course Zod so we of course start by importing necessary dependencies like use form submit Handler form provider and many more we also import Zod resolver from Hook form resolver Zod also we import you state from react link from next link toast from react hot toast use router from the next SL navigation we also import create user input and create user schema from user schema then we also import trpc from utils directory first we set up some State variable using reacts UST State hook submitting keeps track of the form submission status and router will help us in navigation next we Define a mutation function for registering a new user we use trpc do register user.use mutation to handle the registration process this function set submitting to True when the mutation start and false when it is done form validation is done by react hook form and of course Zod because we Define validation schema with Zod right now let's define a mutation function for registering a new user we use trpc register user. use mutation to handle the registration process this sets submitting to true on mutation start and set submitting to false when the mutation is done and if any error occurs we reset the password and password confirm and display the error message but if everything was perfect we send success message and we redirect user to the login then we are going to define a submission Handler to call the registration mutation function this Handler is going to be triggered when the form is submitted now let's render the registration form we wrap it in the form provider to provide form methods to child components inside the form we render various form input components for different fields like full name email password and password confirmation we also include a link to the login page for user who already have an account finally we render a loading button that that displays registered text and shows a spinner when the form is submitting so if you want to look at the Tailwind classes here it is I will just close all of this to make the screen size bigger but you don't need to worry because I'm just going to provide a repository on my getup so you can just go ahead and watch it over there also now I'm getting an error over here this for form input let's hover and see what it is saying that it has no default export okay so in this form Dash input I think we forgot to export yeah so let's export this default form input and save this and then we have this error gone so let's save this file also now we want to create a page component that will render account registration form that we created just now so in the app directory inside this register folder let's create one another file named page. TSX here we start by importing the header component to include the side header this component will be defined as an asynchronous function we have this page divided into two main section the header section that will include the side header which is imported from the header component second we have the main registration section it is like a grid based section that vertically centers it content this is going to contain a heading which is welcome to Allstar register and then we also have heading which says that sign up to get started then we render the register form component that we created so let's check in the terminal if the dev server is running and yes it is running on the Local Host 3000 we will head back to the Local Host 3000 and then we will click on this register link over here okay and here we get this error which says that cannot destructure property client of used cont text as it is null okay so now after a few moments of checking what was wrong with the code I realized that we haven't wrapped the trpc provider client component that we created earlier around the child component which is present in the layout component in the root directory and because of which we are getting this error so basically when we wrap the trpc provider around this children prop in the layout file we ensure that all the client component within the component Tre have access to both the trpc and react query clients so in this layout file we start by importing the trpc provider functionality and we also bring in the toaster component for displaying toast notification and then the root layout function here receives children as a prop right so what we will do here is we will rep the children prop inside the trpc provider and we will have a div inside which we will have our children prop and then when we head back to the Local Host 3000 for/ register we have our form ready over here amazing isn't it and one thing that I realized over here is that this header background color is different than this so for that what we are going to do is we are going to go in global. CSS file and right over here we will remove this linear background color and we will paste this which is similar to the BG grade 950 Tailwind class all right so let's save this file and also remove this and now save this file and when we head back to the Local Host we have this properly okay and now as we are also done with the user registration let's start with creating a login form now because when you come over here it says that 404 because we haven't created it yet so let's start doing that log Lin form will have two input Fields email and password so what we are going to do is we are going to create a login folder inside this app directory and inside this login folder we will create one file which is named as login Das form. TSX so in this file we start off by importing various dependencies like use form submit Handler we also import Zord resolver we import use state from react link from next link and then login us user input and login user schema from user schema and many other things which we have already worked on with then we are going to have our function which is login form it is going to use react hooks to manage State and form submission it is structure to provide a user friendly login experience so we start by defining State variables using the use State hook the submitting State tracks the form submission status the used router Hook from nextjs is imported to handle navigation and we also have the use form Hook from react hook form which we will use it to manage form State and validation it is configured with a zort resolver for schema based validation we then have the methods object obtained from the use form that will provide the form method like reset and handle submit we also declar the login function mutation from trpc which is used to trigger the login process it's configured with call backs for various mutation States like on settle on mutate on error and on success then we declare the onsubmit Handler function to handle form submission it invokes the login function mutation with the form values and the final step is to declare the jsx structure that will render the login page so our form will be repped inside the form provider and in this form we have two form input one for email one for password then we also have a div it is going to contain a text which says forget password then we have the loading button component which will be used to render the login button with the loading State additionally it will provide a link for the user so that they can navigate to the registration page and now as we are done with this let's save this file now the next thing is to create page. TSX file for this login so in the login folder let's create create another file named page. TSX so now that we have login page created successfully we want to render that to the client right so in this file we start by importing the header and the login form components the login form component is used to render the actual login form here we bring in the header into our login page because we need that navigation page on our login page also right the next thing is we create a section with a div inside which we we have an H1 heading which says welcome back and then you have another heading which will ask you to log in to have access the login form component is placed within the section that is going to Center its content both horizontally and vertically and below this we are going to have login form so let's now save this file also and head back to the Local Host 3000 and when you come back over here and you will find this page which is Perfect Isn't it just we have one step remaining that is we want to create our Pro page which is very important so let's now create a server component that will utilize the get o user function and will retrieve the authenticated user information and based on it it will display the page the pro page okay if user is authenticated the pro page will be shown and if the user is not authenticated they will get redirected to the login page so for it what we are going to do is in this app directory we are going to create one folder named Pro page and inside this Pro page folder we are going to create page. TSX file so here we start by importing the header component and the get o user function for authentication additionally we will also import the image component from next for/ image to display the images the pro page function is then marked as async because it is going to await the authentication status of the user inside the jsx structure of the component first we bring up our header component because we want to show that navigation at the top and followed by we have the section which is going to display various images and captions basically this is our block section but here just like this div I will have another three divs but you can create a pro block component over here instead of just copy and pasting this div same times but here is the thing that we don't want to render this divs for Block we want to create a block component so now that is up to you you have to create a blog component okay and then import that blog component over here and after the header you will show your block component over here this get Au user function is used to authenticate the user and if they are authenticated only then we will show this page Pro block page okay so after all is done let's head back to the Local Host 3000 and what we will do is we are just going to register a user right now so we are going to provide full name as admin email as admin admin.com then let's copy this and paste the password and confirm password similarly like this and then let's hit so we got another error which says that database server is not running on the Local Host 6,500 so the error was because we didn't have a PG admin running but now we have it and if you face the similar problem what you will do is you will go to the Local Host 5050 SL browser and then here login with the credentials provide in the EnV file and let's now try registering the user so put the password over here similar to the email and then let's confirm password then let's hit register and then we will have the school animation for this loading button and there we have this toast message which says registered successfully and it then took you to the login page so here we will provide the same password for and let's hit login and there we have this login successful amazing isn't it the link change from home register log to home propage logout so let's go go to the pro page and see if this gives us so yes we have we do have our Pro page over here but these are just the Dives rendering over here you could do more okay so and with this our video wraps over here I hope you enjoyed it and learned something new if you did then please don't forget to like this video and also do considering subscribing thank you for watching this video and I'll see you in the next one till then bye-bye and happy cing
Info
Channel: FEWV
Views: 309
Rating: undefined out of 5
Keywords: Next.js, trpc, Prisma, Postgres
Id: 97FVgRzMksc
Channel Id: undefined
Length: 32min 31sec (1951 seconds)
Published: Sun Feb 18 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.