Next.js 13.4 App Router中如何让Auth页面排除根布局?
在Next.js 13.4 App Router中让认证页面排除根布局的方法
要让认证页面及子页面不应用根布局的全局内容(如导航栏、页脚),可以通过路由分组+根布局路由判断的方式实现,具体步骤如下:
1. 用路由分组整理认证路由
将所有认证相关页面移入app/(auth)目录(括号是路由分组的标识,不会影响最终路由路径)。例如:
app/(auth)/auth/page.tsx(对应路由/auth)app/(auth)/auth/register/page.tsx(对应路由/auth/register)
2. 修改根布局,跳过认证路由的全局UI
在app/layout.tsx中,使用usePathname()判断当前路由是否属于认证路径,仅在非认证路由下渲染根布局的全局内容,认证路由直接渲染页面内容:
// app/layout.tsx import { usePathname } from 'next/navigation'; export default function RootLayout({ children }: { children: React.ReactNode }) { const pathname = usePathname(); // 根据你的实际路由调整匹配规则,这里匹配所有以/auth开头的路径 const isAuthRoute = pathname.startsWith('/auth'); return ( <html lang="zh-CN"> <body> {!isAuthRoute ? ( <> {/* 根布局的全局内容,仅非认证路由显示 */} <header>全局导航栏</header> <main className="main-content">{children}</main> <footer>全局页脚</footer> </> ) : ( {/* 认证路由直接渲染页面内容,跳过全局UI */} children )} </body> </html> ); }
3. (可选)创建认证专属布局
在app/(auth)/layout.tsx中定义认证页面的通用布局(如统一的登录注册容器样式),该布局仅作用于认证分组内的页面:
// app/(auth)/layout.tsx export default function AuthLayout({ children }: { children: React.ReactNode }) { return ( <div className="auth-container"> <div className="auth-card"> {children} </div> </div> ); }
为什么之前改auth为(auth)无效?
路由分组的作用是让目录不成为路由路径的一部分,不会自动脱离根布局的包裹。必须配合根布局中的路由判断,才能跳过根布局的全局UI内容。
内容的提问来源于stack exchange,提问作者Ali Aref
相关产品推荐
相关产品推荐

