Skip to content

Protect a Page and Route

This guide shows the core pattern you will use in a real application:

  • protect a frontend page with auth state
  • protect a backend route with role checks
  • use the admin dashboard to change a user’s role

The specific example is a small /chat page, but the pattern applies to any protected product feature.


End Result

  • a protected /chat frontend route - a protected backend /chat endpoint - role-based access using the team role

In your frontend app, add a new /chat route and render it inside the authenticated application shell.

The key idea is:

  • use AuthProvider at the app boundary
  • use useAuth() inside the page
  • gate the page based on isAuthenticated and role data

If you want the React package context first, see React SDK.


Inside the page, check the current user’s roles.

Example pattern:

const { isAuthenticated, hasScopedRole } = useAuth()
const hasAccess = hasScopedRole('team')

Use that to:

  • block unauthenticated access
  • show a “missing role” state when the user is signed in but not authorized
  • render the protected UI only when the required role is present

Your backend still needs its own authorization boundary.

Typical shape in an Express app:

app.post('/chat', requireAuth({ cookieSecret }), requireRole('team'), (req, res) => {
const { message } = req.body
res.json({
reply: `Echo: ${message}`,
})
})

That keeps authorization explicit on the server even if the frontend also hides the feature.

If you want the package-level backend view, see Server SDKs.


With a normal authenticated user who does not have team:

  1. sign in
  2. open /chat
  3. confirm that the page stays blocked or limited
Chat example page with restricted access
The route is authenticated, but the role is still missing

Log in as an admin and open the users screen in the admin dashboard.

Then:

  1. select the user
  2. edit the user record
  3. add the team role
  4. sign out and sign back in as that user
Admin portal user edit modal
Roles can be updated from the dashboard

After the role is present:

  1. sign back in
  2. open /chat
  3. confirm the protected UI renders
  4. submit a request to the backend route
Chat example page with access granted
The protected page is available once the role is present

The pattern is always the same:

  • auth state on the frontend
  • role checks in the UI where helpful
  • authorization enforcement on the backend
  • role management through explicit user/admin flows