In Nextjs with the experimental app directory I want to specify a layout, error, loading, …ect for the entire app and then have a layout, error, loading, …ect for the home page that is unique to the home page. This can easily be done with every other page in the app by just creating a folder and then placing those files in it. But I cannot seem to figure out how to specify a folder for the home page. Everything for the home page is just at the root of the app directory which is used by the entire app as well as the home page. It seems like you should just be able to specify an index directory and treat it like any other page in your app but this is not the case. I can’t seem to find any kind of documentation on how to handle this. Is this just a feature of Next13. If so it seems a bit strange that you can specify route specific pages, layouts, errors, …ect for every page in your app but not the home page.
So how do you go about specifying a directory for the home page in Nextjs 13 with the app directory file structure?
3
Answers
You can use an
getInitialProps
function in_app
page to redirect all input to specific page to what you want:The idea is to have layout (only with html and body tag) and error page in /app directory (to serve / index page), and everything else in a routing group.
For your home page, you should not use
layout.tsx
for your other elements other than just the html and body tag, you can put your layout in page.tsx (or import as component).Redirect method
Or simply redirect home page to a specific folder
Do remember /app directory is still in beta, so many issues are still being ironed out. Requests or bug reports should be sent to their repository.
Check out the Nextjs routing groups Nextjs Routing Groups. You can make a routing group just for your home specific stuff. Routing groups are defined by making a directory with parentheses around it. So you can make a directory called
(home)
and movepage.js
in there and then you can make anotherlayout.js
in that directory also. like so:So Nextjs will first check the root of the app directory and load the
layout.js
found there. Then it will travel to the(home)
directory as a child of the root to load your page and layout for the home page.