33

I'm learning to use NextJS and I'm using the latest version with App Router, I'm currently stuck on how to do routing, such as where to put the register and login pages, and its' folder structure in general, where I put components and how to group other related components together, can you shed light on this topic, and please make it as simple as possible and maybe give some examples because I'm still learning, any help would be much appreciated, thankyou !

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Dead
  • 361
  • 1
  • 3
  • 6
  • Reference this article: https://stackoverflow.com/questions/53854104/is-this-next-js-folder-structure-recommended – Xuân Cường May 10 '23 at 02:42
  • It's personal preference, but a common pattern is a `components/` folder at the same level as `pages/` (pages is used for routing). That structure is implied here https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts – Andy Ray May 10 '23 at 02:43

5 Answers5

48

I think reading this section in Next docs help you organize the project folders:

https://nextjs.org/docs/app/building-your-application/routing/colocation

I tried with many different structures and I finally chose this one:

  1. Everything (all folders and files) will be in the /app directory because the /app directory accepts colocation and it's different from /pages directory which was only for routing purposes. In this way /app directory can be assumed the new /src directory.

  2. All the non-routes folders will be Private Folders by prefixing their name with an underscore (as stated in the link above). This tells the Next router that this folder is not part of the routes. (e.g. _components, _libs, ...)

  3. To this point we established that every folder with underscore (_) is not route and other folders without it are a part of the routing system (although having a page.tsx or page.js file in the folder is another condition for being a part of the routing system), but I used another Next 13 feature and it is Route Groups (as stated in the link above). It is wrapping a folder name in parenthesis, so that it shows the folder is for organizational purposes (grouping folders) and should not be included in the route's URL path ,e.g. (routes).

With these principles, I have all my required folders in /app directory, and with Route Groups all my routes are grouped in a "(routes)" folder, and with Private Folders by prefixing non-route folders with underscore, everything is isolated.

The image below is the summary of all the points above.

https://i.stack.imgur.com/wrJoY.png

Hope the link and my way of organizing project folders help you.

  • I liked this approach. but I don't know if the feature of some file with specific name can complicate this. For example, "error.tsx" or "page.tsx" outside of (routes) – Francisco Ossian Jul 21 '23 at 12:21
  • @FranciscoOssian As I mentioned in second point, all private folders (prefixed with underscore) are excluded from route system even if they have "error.tsx" or "page.tsx". The only place that can cause problem is the root of /app directory which these kinds of filenames should be avoided. It is just one place and easy to avoid IMHO. – Mahmoud Taghinia Jul 21 '23 at 15:02
  • 3
    I'm always confused what people mean by "component". I know generic reusable things like buttons, modals, etc. are components, but what about specific things? Say you have a route `/app/(routes)/login/page.tsx`. If you have a "component" that is specific to the login page, would it make sense to keep it in the login route folder? Or would you move that to the component directory and only keep page.tsx an layout.tsx files in the (routes) folder. – Joe Aug 05 '23 at 02:36
  • This make sense IF you're NOT using the `src` folder. If you use the `src` folder, go with @Yilmaz's answer below – NSjonas Aug 24 '23 at 15:29
  • @Joe if a component is only used inside a specific page or other component, I add it to a folder called components inside the folder for that specific page/component. If it is used in other places, I will move it out to a general components folder. – fredric Aug 29 '23 at 21:28
32

enter image description here

Some keep the components inside the app but I keep them outside to tell other engineers that app directory includes only page components. If you have similar routes that have shared layouts you can use () syntax inside app directory. For example

enter image description here

Inside auth folder you can have login and signup pages with the shared layout.

Inside the components folder, you can create sub-folders for providers, ui, or shared components.

Honey
  • 2,208
  • 11
  • 21
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
10

In version 13, Next.js introduced a new App Router built on React Server Components. Means whatever component you will place under the app directory will by default work as a server component. I will suggest to place components inside the /app directory if you wanna render the components on server side. You can also place the components inside the folders of any page.

/app
  /components
  /dashboard
    customComponent.tsx
    page.tsx
  layout.tsx
  page.tsx

For getting more of the File Conventions read this article: https://nextjs.org/docs/app/building-your-application/routing

Gilbish Kosma
  • 739
  • 5
  • 13
0

you can use various routing in latest App router version and even customise the routing to use your own customised routing.

Default Routing with Next.js App Router: for creating a page,you can directly create a folder with page name inside the folder for example about page,create about folder, create page.jsx(inside about folder,act as the index page for about i.e. can be accessed by URL/about) App /about page.jsx

2.) To implement custom routing

you can add in next-config

async rewrites() {
    return [
      {
        source: '/old-route',
        destination: '/new-route',
      },
      // Add more custom routes as needed
    ];

I have researched over the directory structure too when i started For Best Practices ,i directly create the pages inside the App directory.like all/products/page.jsx or app/about/page.jsx

for admin ui , i use app/admin/pagenameofadmin/page.jsx app/admin/page.tsx(admin home page)

for all other components use components folder,and create subfolders in components to find components easily

layout - for common and repetitive components like header/footer/sidebar auth - for login signup related components admin - for admin ui components pagename - for page specific component

can also create for folder for specific content type if you want to keep everything organised at next level, i recommend to use it for complex projects only product - for products realted components

keep apis inside app/utils folder.

Veer Pratap
  • 118
  • 2
  • 11
  • could you please describe more about this :::: can also create for folder for specific content type if you want to keep everything organised at next level, i recommend to use it for complex projects only product - for products realted components keep apis inside app/utils folder. – user8577431 May 18 '23 at 03:37
  • 1
    Instead of making different components for each type of content on different pages, you can save time and effort by reusing the same components for similar content types. For example, if you have products, categories, and blogs in your application, instead of creating separate components for each page (like a "productpage"folder for component), you can organize them in folders named after the content type (like a "product" folder). This way, you can use the same components across different pages, making it easier to manage and update your application. – Veer Pratap May 18 '23 at 07:44
-7

A simple folder structure example that you can follow:

  1. Create a pages directory in the root of your Next.js project. This is where you'll place your page components that correspond to different routes.

  2. Create an auth directory to group all authentication-related pages together inside the pages directory. For example:

     pages/
       auth/
         login.js
         register.js
    
  3. In the login.js and register.js files, you can create your login and register page components. For example:

     // pages/auth/login.js
     const LoginPage = () => {
         return <div>Login page</div>;
     };
    
     export default LoginPage;
    
  4. Next Create a page register.js:

     // pages/auth/register.js
     const RegisterPage = () => {
         return <div>Register page</div>;
     };
    
     export default RegisterPage;
    
  5. To set up routing, you can use Next.js' built-in App component and Router from the next/router module. Here's an example of how you can configure your routes:

         // pages/_app.js
     import { useRouter } from 'next/router';
    
     const MyApp = ({ Component, pageProps }) => {
         const router = useRouter();
    
         // Check if the current route is an authentication route
         const isAuthRoute = router.pathname.startsWith('/auth');
    
         // You can perform any common layout or logic for all pages here
    
         // Wrap authentication pages with a layout or authentication-specific logic
         if (isAuthRoute) {
             // Add authentication layout or logic here if needed
    
             // For example, you can add a common navigation component
             // or apply styles specific to authentication pages
    
             return <Component {...pageProps} />;
         }
    
         // For non-authentication pages, you can apply a different layout or logic
         // or simply return the component as it is
         return <Component {...pageProps} />;
     };
    
     export default MyApp;
    

In the above example, we use the _app.js file to configure the layout or logic for different pages based on the route. We check if the current route is an authentication route (in this case, starting with /auth), and based on that, we can apply a specific layout or logic.

Note: You can further customize the layout and logic in the MyApp component based on your specific requirements.

With this setup, you can access your login page at /auth/login and the register page at /auth/register.

Remember to run npm run dev or yarn dev to start the Next.js development server and navigate to the appropriate routes to see the pages in action.

This is a basic example to help you get started with the folder structure and routing in Next.js. You can modify and expand it based on your project's needs.

lareb
  • 98
  • 6