Route Guards
Learn how to protect your application using route guards.
Route guards ensure that specific sections of your application are accessible only to authenticated users. By implementing route guards, you can control user access to React Server Components, React Client Components, React Server Actions and Next.js Route Handlers.
Protecting Route Handlers
Create a route file in your application.
Navigate to the endpoint (or use fetch). The user (or null
) will be displayed in the
terminal console.
If the user is not authenticated, you can return a 401 status code, a message, or redirect to login page.
Protecting Server Actions
Create an action that will make use of getUserAction
to retrieve the user.
Create a client
page (or any component) and use the new action.
Navigate to this page and click the button. The user (or null
) will be displayed in the terminal
console.
If the user is not authenticated, you can return an error message back to the client.
Protect a Server Components
Create a page (without the 'use client'
flag).
Navigate to the page. The user (or null
) will be displayed in the terminal
console.
If the user is not authenticated, you can return a specific component or redirect the user to login page.
Protect a Client Components
Create a client
page (or any component).
Navigate to the page. The user (or null
) will be displayed in the browser console once the
component is mounted.
If the user is not authenticated, you can return a specific component or redirect the user to login page.