Private Pages
Veloz provides some set of utilities function mean't to protect routes
either server or client from getting access. This utilities function / components can be found in src/lib/auth-helpers
folder.
Client 🖥
withAuth
withAuth
is a higher order component that can be used to protect client side routes from getting access. It takes a component as an argument and returns a new and modified component that can be used to protect routes.
When a user isn't authenticated, the component will redirect the user to the login page. If the user is authenticated, the component will render the passed in component.
Only use this HOC (High Order Component) to protect pages / components that are mean't to be accessed by authenticated users only.
withoutAuth
As the name implies withoutAuth
the opposite of withAuth
. It is used to protect client side routes from getting access. It takes a component as an argument and returns a new and modified component that can be used to protect routes.
When a user is authenticated, the component will redirect the user to the dashboard page. If the user isn't authenticated, the component will render the passed in component.
Only use this HOC (High Order Component) to protect pages / components that are mean't to be accessed by unauthenticated users only. for eg authentication route / page
Use Case
Assuming we have a page called dashboard.tsx
that should only be accessible by authenticated users only. We can use withAuth
to protect the page from getting access by unauthenticated users. We can also use withoutAuth
to protect a page that should only be accessible by unauthenticated users only.
Server ☁️
Protecting API routes / endpoints is quite handled differently from that of client side pages / routes. Endpoints are protected using isAuthenticated
middleware HOF (High Order Function) and can be found in /src/app/api/middlewares/auth.(ts)
file.
isAuthenticated
Use Case
Simply wrap your API route handler with isAuthenticated()
middleware to protect it from getting access by unauthenticated users.
Each time a request is made to the server for that specific endpoint and the user making the requests isn't authenticated, the server simply throw an error with status code 401
and message Unauthorized
.
More details about Error Handling, please checkout this 👉 section.