skip to Main Content

I am trying to create an admin section with a different layout than the one used in all the pages, but instead, I am seeing them combined.

This is my file structure:

  • src/
    • app/
      • page.tsx
      • layout.tsx
      • admin/
        • page.tsx
        • layout.tsx

My intention is the layout.tsx on the admin folder should be different than the one on src/app/layout.tsx but instead, I am seeing both of them.

According to the NextJS documentation, the src/app/admin/layout.tsx should be applied to the src/app/admin/page.tsx file automatically.

This is the code of the /admin/layout.tsx file:

import AuthContext from '@/context/AuthContext'
import { Session } from 'next-auth'
import { headers } from 'next/headers'

async function getSession(cookie: string): Promise<Session> {
  const response = await fetch(`${process.env.NEXTAUTH_URL}/session`, {
    headers: {
      cookie,
    }
  })

  const session = await response.json()

  return Object.keys(session).length > 0 ? session : null
}

export const metadata = {
  title: 'My App',
  description: 'My App',
}

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const session = await getSession(headers().get('cookie') ?? '')
  return (
    <html lang="en">
      <body>
        <AuthContext session={session}>
            {children}
        </AuthContext>
      </body>
    </html>
  )
}

What should I change to make this work?

2

Answers


  1. Looking your code, you problem can be on the name of your nested layout /admin/layout.tsx

    try change your
    export default async function RootLayout({
    to
    export default async function AdminLayout({

    Hopefully this will solve your problem

    Login or Signup to reply.
  2. you’re not utilizing the getLayout pattern properly

    Define a getLayout function in your admin page

    // src/app/admin/page.tsx
    import AdminLayout from './layout'
    
    export default function AdminPage() {
      // Your admin page component code
    }
    
    AdminPage.getLayout = function getLayout(page) {
      return <AdminLayout>{page}</AdminLayout>
    }
    

    Similarly, define a getLayout function in your main app page:

    // src/app/page.tsx
    import AppLayout from './layout'
    
    export default function AppPage() {
      // Your app page component code
    }
    
    AppPage.getLayout = function getLayout(page) {
      return <AppLayout>{page}</AppLayout>
    }
    

    Then use the getLayout function

    // pages/_app.js
    function MyApp({ Component, pageProps }) {
      const getLayout = Component.getLayout || ((page) => page)
    
      return getLayout(<Component {...pageProps} />)
    }
    
    export default MyApp
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search