Routing in Singularity React with Next.js App Router
Singularity React employs the Next.js 13 App Router to manage application routing. This advanced, file-system-based routing system, built on server components, supports layouts, nested routes, loading states, error handling, and additional features.
For in-depth details on the Next.js App Router, consult the official Next.js documentation.
Key Concepts
1. File-based Routing: Routes are established based on the file structure within the app
directory.
2. Layouts: Common UI elements for multiple pages are defined in layout.tsx
files.
3. Route Groups: Group routes without impacting the URL structure by using parentheses in folder names.
4. Dynamic Routes: Define routes with dynamic parameters using square brackets, such as [id]
.
Using MainLayout in layout.tsx
Singularity React offers a MainLayout
component for use in layout.tsx
files to organize the overall structure of your pages. This component allows you to control the visibility of various sections of the main theme layout.
Below is an example of implementing MainLayout
in a public layout:
import MainLayout from '../../components/MainLayout'; function Layout(props: { children: React.ReactNode }) { const { children } = props; return ( <MainLayout NavigationBarSlice={false} toolbar={false} leftSidePanel={false} rightSidePanel={false} footer={false} > {children} </MainLayout> ); } export default Layout;
In this example, the NavigationBarSlice, toolbar, side panels, and footer are hidden for all routes within the (public) group.
Route Access Restriction with AuthGuardRedirect
Singularity React provides an AuthGuardRedirect
component to limit access to specific routes based on user roles. Below is an example of its use in a control panel layout:
import MainLayout from 'src/components/MainLayout'; import AuthGuardRedirect from '@auth/AuthGuardRedirect'; function Layout({ children }) { return ( <AuthGuardRedirect auth={['admin']}> <MainLayout>{children}</MainLayout> </AuthGuardRedirect> ); } export default Layout;
In this case, access to all routes under the (control-panel) group is restricted to users with the 'admin' role. Users lacking the required role will be redirected.
Best Practices
- Organize routes logically using route groups (folders with parentheses) without altering the URL structure.
- Apply shared layouts for related pages to ensure consistency and minimize redundant code.
- Use the
AuthGuardRedirect
component to enforce role-based access control for your routes. - Leverage Next.js 13 features, such as server components and streaming, to enhance performance and improve user experience.
By utilizing the Next.js App Router alongside Singularity React’s custom components like MainLayout
and AuthGuardRedirect
, you can build a robust, adaptable, and secure routing system for your application.