Next.js Discord

Discord Forum

How to set up protected routes based on roles in next?

Unanswered
Chartreux posted this in #help-forum
Open in Discord
ChartreuxOP
If in react I did it like this:
const AdminLayout = (props) => {
  const [sidebarOpen, setsidebarOpen] = React.useState(false);
  const openSidebar = () => {
    setsidebarOpen(true);
  };
  const closeSidebar = () => {
    setsidebarOpen(false);
  };
  return (
      <AdminRoute>
        <Navbar sidebarOpen={sidebarOpen} openSidebar={openSidebar} />
        {props.children}
        <Sidebar sidebarOpen={sidebarOpen} closeSidebar={closeSidebar} />
      </AdminRoute>
  );
};

Then I pass that layout as wrapper in Routes like
            <Route
              exact
              path="/admin"
              element={
                <>
                  <AdminLayout>
                    <DashboardAdmin />
                  </AdminLayout>
                </>
              }
            />

How can I achieve the same thing in next js?

16 Replies

@B33fb0n3 do it like [this](https://nextjs.org/_next/image?url=%2Fdocs%2Fdark%2Froute-segments-to-path-segments.png&w=1920&q=75)
ChartreuxOP
Where can I do the checking if a signed in user is an admin? Is it in page.js inside dashboard folder?
I expect this behavior, when a user with a role other than admin tries to access /admin, the site redirects them to the route they belong to
@Chartreux Where can I do the checking if a signed in user is an admin? Is it in page.js inside dashboard folder?
Use for example a middleware to check your user. Inside your middleware, you get the roles of the user and check if it's a protected route
@Chartreux I use both middleware and client side checking
And you check your roles inside your middleware?
@Chartreux yes
And you also check the protected routes there?
ChartreuxOP
what about this
I expect this behavior, when a user with a role other than admin tries to access /admin, the site redirects them to the route they belong to

how to do this in next js?
@B33fb0n3 And you also check the protected routes there?
ChartreuxOP
This is what Im about to do
@Chartreux what about this > I expect this behavior, when a user with a role other than admin tries to access /admin, the site redirects them to the route they belong to how to do this in next js?
So, when you check your user inside your middleware you can first check if he's logged in. If not, redirect to login page. If so, you get the roles of the user and check if it's a protected route. If it's an protected route, check if the user roles contains the needed role. If not, redirect him to login or 404 page or ... If the user roles contains the needed role, procceed.
@Chartreux solved?