T
TanStack7mo ago
harsh-harlequin

Layouts in file-based routing: can they be nested inside folders?

Hi! I have a question about TanStack Router and file-based routing. If I use file-based routing, do layouts always have to live at the root of the /routes folder? For example, in Next.js, you can organize files like this:
/app
layout.tsx
page.tsx
/dashboard
layout.tsx
page.tsx
/app
layout.tsx
page.tsx
/dashboard
layout.tsx
page.tsx
Currently, I'm trying to do the same thing on Tanstack Start like this:
/routes
__root.tsx
index.tsx
/_dashboard-layout
_dashboard-layout.tsx
dashboard.index.tsx
/routes
__root.tsx
index.tsx
/_dashboard-layout
_dashboard-layout.tsx
dashboard.index.tsx
In this structure, each folder can have its own layout.tsx scoped to its pages. Is a similar structure possible with TanStack Router, or do layouts need to be declared only at the top level? Thanks a lot!
4 Replies
rare-sapphire
rare-sapphire7mo ago
you can nest layout routes yes maybe i am misunderstanding the question but you can just do
/routes
_foo.tsx
/_foo
_bar.tsx
/_bar
hello.tsx
/routes
_foo.tsx
/_foo
_bar.tsx
/_bar
hello.tsx
harsh-harlequin
harsh-harlequinOP7mo ago
Ah, thanks, that's kind of it, yes. I would have liked _bar.tsx to be inside the _bar/ folder. But at least it's not at the root, that's what I wanted to know, because having multiple layouts at the root is confusing me! Thank you.
rare-sapphire
rare-sapphire7mo ago
you can also add a route.tsx inside of _bar folder serves the same purpose as the _bar.tsx outside of it but you can just do
/routes

/_foo
route.tsx
/_bar
route.tsx
hello.tsx
/routes

/_foo
route.tsx
/_bar
route.tsx
hello.tsx
and if you really want to mimick nextjs, you can configure the "routeToken" to be ... "layout"
harsh-harlequin
harsh-harlequinOP7mo ago
Oh thank you very much, I'm not particularly trying to imitate Next, but just at the beginning, I thought that we had to put all the layouts in the root of /routes, and therefore it became very cumbersome! I think this route.tsx is very interesting

Did you find this page helpful?