Organize your components and layouts in your pages-based Next.js application this way.
When building a Next.js application, organizing your components and layouts efficiently is crucial for maintaining a clean, scalable codebase. In this blog post, we will look at a practical example of structuring your components and layouts using a page-based approach, inspired by Supabase’s codebase.
Next.js uses a pages directory where each file corresponds to a route in your application. This structure is intuitive, but as your app grows, it is very important to organize components and layouts in a way that promotes reusability and clarity.
Notice how the components and layouts are organized:
components/interfaces/SignIn/SignInForm: This directory holds the SignInForm component, specifically related to the Sign-In interface. By organizing components within a relevant interface folder, you ensure that related components are grouped together, making them easier to find and manage.
components/layouts/SignInLayout/SignInLayout: The SignInLayout component is separated into its own layout directory. This keeps the layout logic distinct from the individual components, allowing you to reuse the layout across different pages.
lib/constants: The IS_PLATFORM constant is imported from a centralized location. This is a good practice for managing global constants that might be used across multiple components.
One of the strengths of Next.js is its ability to define layouts on a per-page basis. The SignInPage component is wrapped in a SignInLayout that defines the overall structure of the page:
SignInPage.getLayout = (page) => ( <SignInLayout heading="Welcome back" subheading="Sign in to your account" logoLinkToMarketingSite={true} > {page} </SignInLayout>)export default SignInPage
Organizing your components and layouts in a pages-based Next.js application this way promotes a clean, scalable structure. By grouping related components and separating layout logic, you create a maintainable codebase that’s easy to extend as your application grows.
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.