Blog>
Snippets

Nested Routes with Automatic Layouts

Create nested routes using the App Router and illustrate how Next.js 14 manages automatic persistent layouts for nested page components.
// pages/_app.js
import { AppRouter } from '@shopify/app-bridge-react';
import { Fragment } from 'react';

function MyApp({ Component, pageProps }) {
  return (
    <AppRouter>
      <Component {...pageProps} />
    </AppRouter>
  );
}

export default MyApp;
This sets up the main app component to use AppRouter, which allows nested routing. The AppRouter provides context for routing within the app.
// pages/layout.js
import React from 'react';

export default function Layout({ children }) {
  return (
    <div className='layout'>
      <header>Header</header>
      {children}
      <footer>Footer</footer>
    </div>
  );
}

Layout.getLayout = function getLayout(page) {
  return (
    <Layout>
      {page}
    </Layout>
  );
};
This is the layout component that is automatically applied to nested routes. The `getLayout` method of `Layout` makes it possible to wrap pages inside this layout without manually wrapping each page.
// pages/index.js
import Layout from './layout';

function HomePage() {
  // Page content goes here
  return <div>Welcome to the Home Page</div>;
}

HomePage.getLayout = Layout.getLayout;

export default HomePage;
This is the home page component. It utilizes the `getLayout` method from the `Layout` component, allowing Next.js 14 to automatically apply the layout to the home page when it is rendered.
// pages/about.js
import Layout from './layout';

function AboutPage() {
  // Page content goes here
  return <div>About us information</div>;
}

AboutPage.getLayout = Layout.getLayout;

export default AboutPage;
This is the about page component. Similar to the home page, it uses the `Layout.getLayout` method to wrap itself with the layout defined in the `Layout` component.