bootsaas logo

How to protect access to pages

There is a built in hook useAuthGuard() that you can use to protect access to pages.

It's very simple to use, take a look at it's props interface:

interface AuthProps { middleware?: "auth" | "guest"; redirectIfAuthenticated?: string; }

And here you can see what it returns:

const useAuthGuard: ({ middleware, redirectIfAuthenticated, }: AuthProps) => { organization: Organization | undefined; user: User | undefined; login: ({ setErrors, props, }: { setErrors: (errors: HttpErrorResponse | undefined) => void; props: any; }) => Promise<void>; logout: () => Promise<void>; mutate: KeyedMutator<...>; }

It returns a user, an organization the user belongs to, login and logout functions and a mutator function.

It's using swr under the hood, you can safely use this hook wherever you need the user info, without worrying you'll be making too many requests to get user session.

There is also a version that you can use for server components called getServerSession which has exactly the same interface and behaves the same way.

So for example if you put this guard in a dashboard layout, all the dashboard routes will not be accessible unless the user is authenticated.

bootsaas logoCopyright © 2024 - All rights reserved