Blog>
Snippets

Building a Multi-layout System in Next.js 14

Provide code to manage multiple layouts such as public, authenticated, and administrative layouts to apply different wrappers based on page context in a Next.js 14 app.
import { useRouter } from 'next/router';

// Define your layout map
const layouts = {
  public: PublicLayout,
  auth: AuthLayout,
  admin: AdminLayout,
};

// Define a component that will wrap your page
const LayoutWrapper = ({ children }) => {
  const router = useRouter();

  // Determine the layout type based on the route
  const layoutType = getLayoutType(router.pathname);

  // Get the layout component from the map
  const LayoutComponent = layouts[layoutType] || DefaultLayout;

  // Render the children with the layout
  return <LayoutComponent>{children}</LayoutComponent>;
};

function getLayoutType(path) {
  if (path.startsWith('/admin')) {
    return 'admin';
  } else if (path.startsWith('/auth')) {
    return 'auth';
  }
  return 'public';
}

// Export the layout wrapper
export default LayoutWrapper;
This snippet creates a LayoutWrapper component that determines which layout to use based on the routing path. It exports this wrapper for use in the _app.js file to provide the correct layout based on the current route.
import LayoutWrapper from '../components/LayoutWrapper';

// Your custom App component
function MyApp({ Component, pageProps }) {
  return (
    <LayoutWrapper>
      <Component {...pageProps} />
    </LayoutWrapper>
  );
}

export default MyApp;
This snippet shows how to use the LayoutWrapper in the custom _app.js file, which is a part of every Next.js application. It wraps the page component with the desired layout based on the current route.
// Sample layout component for Public layout
const PublicLayout = ({ children }) => (
  <div className="public-layout">
    <header>Public Navigation</header>
    <main>{children}</main>
    <footer>Public Footer</footer>
  </div>
);

export default PublicLayout;
This is an example of a simple layout component for public pages. You would create similar components for AuthLayout and AdminLayout based on the specific needs of those sections of the application.
// Sample page that uses public layout
const PublicPage = () => (
  <> // React Fragment
    <h1>Public Content</h1>
    <p>This page uses the public layout.</p>
  </>
);

// Explicitly specify the layout type or let it default to public
PublicPage.layoutType = 'public';

export default PublicPage;
This is an example of a page component that would use the public layout. If you have different types of pages requiring different layouts, you can specify the layout type directly on the page component or rely on the default from the LayoutWrapper logic.