6th Practical Class:
Auth on FrontEnd
Better Auth Client
The auth client exposes asynchronous methods for:
- sign up
- sign in
- sign out
- e-mail verification
- request password reset
- update password
In quacker, we add an additional "role" field to the user model, so we have to do the same on the frontend to get the correct TypeScript types.
Sign Up (register)
Sign Up in Quacker
Quacker uses a custom GraphQL mutation to sign up so we are able to do additional logic on the server (set role and save the profile picture).
See the method in .
Sign In (login)
Sign Out (logout)
Optional property to handle redirects.
Use Session
This hook makes an API request to the backend to get the logged in user based on the session token stored in a cookie.
Due to the asynchronous nature of the hook, the property is always when the page is loaded, even if the user is logged in. This is not ideal for scenarios where you want to redirect the user back to the sign in page if they are not authenticated.
Custom Hook in Quacker
Our custom hook that handles the issue with async session fetching.
It uses the browser's local storage to cache the user object and return it before the session is fetched from the API.
User Schema for Local Storage
Since you can only store string values in local storage, we will need to stringify the object using .
To be able to validate the parsed JSON when we read it back from local storage, we define a Zod schema for the cached user object.
❗Note that we only do not include the "role" field in the cached user object. Local storage can be easily edited by anyone, so we don't want people to be able to change their role.
User Getter and Setter from Local Storage
Custom Hook to Get and Set User from Local Storage
- The initial value of the user is fetched from local storage.
- The function updates the user in the local state and in local storage.
Save the user in local storage after sign in:
Clear the user from local storage after sign out:
Synchronize the cached user with session data:
Return the user from local storage while the session request is pending:
Protected Routes
Some parts of your app might require user authentication.
To redirect back to the home page if the user is not authenticated, you can create a component:
Then in you can use it like this: