I recently started on NextJS and I'm bit confused. I’m working on a Next.js 15 project using the app folder structure (without a src directory). I requires two distinct navigation bars:
Public Navbar - Visible on the landing page (/) and login/signup pages. Authenticated Navbar - Displayed only after the user logs in (e.g., on a dashboard page).
How can I achieve this? Should I handle the logic in the layout.tsx file or create separate layouts for public and authenticated routes? Any code examples or best practices would be helpful.
I’ve attached a diagram for reference here.
I recently started on NextJS and I'm bit confused. I’m working on a Next.js 15 project using the app folder structure (without a src directory). I requires two distinct navigation bars:
Public Navbar - Visible on the landing page (/) and login/signup pages. Authenticated Navbar - Displayed only after the user logs in (e.g., on a dashboard page).
How can I achieve this? Should I handle the logic in the layout.tsx file or create separate layouts for public and authenticated routes? Any code examples or best practices would be helpful.
I’ve attached a diagram for reference here.
Seems a very simple change can fix this. Dependeing on your global state just use the existence of auth token to check if the user is logged it in the layout file.
If token exists, show logged in users' nav else show default nav
To show different layouts depending on an arbitrary state or context, you can create a Layout component such as:
Layout.tsx
import React from "react";
import { useAuth } from "../hooks/useAuth";
import AnonLayout from "./AnonLayout";
import AuthLayout from "./AuthLayout";
const Layout = ({ children }) => {
const { isAuthenticated } = useAuth();
return isAuthenticated ? <AuthLayout>{children}</AuthLayout> : <AnonLayout>{children}</AnonLayout>;
};
export default Layout;
Then in your main page, you wrap your content with <Layout>
.
const { isLoggedIn } = useAuthContext();
or whatever you name your context to conditionally render different content. Here's an example using Auth0 github.com/auth0-samples/auth0-nextjs-samples/blob/main/… – gunwin Commented Feb 3 at 16:55Layout
,LoggedInLayout
andAnonLayout
component, in theLayout
, use the context to decide whether to showLoggedInLayout
orAnonLayout
. – gunwin Commented Feb 5 at 22:53