Repository navigation
Description
Describe the problem
Page endpoints have been a popular addition to SvelteKit, despite a few lingering bugs. Since before they landed, people have (quite reasonably) been asking why we don't have layout endpoints.
The biggest reason, frivolous as it might sound, is naming. 'Layout' is very much a UI concept, and so a __layout.js file that is solely concerned with loading data feels a bit weird.
Describe the proposed solution
As part of a wider overhaul of routing (follow-up issue to come, which will address pathless routes and granular layout resets) I propose changing __layout.svelte to __section.svelte and adding a corresponding __section.js (or .ts, etc) endpoint. 'Section' feels like a sufficiently agnostic word β it leans towards UI terminology, but it doesn't feel weird to talk about a 'section endpoint', as in 'the endpoint for the blog section' or the admin section or whatever.
Just as page endpoints expose their data as a virtual child __data.json route, section data will need to be exposed, perhaps by appending __section.json (i.e. src/routes/foo/__section.js is exposed as /foo/__section.json).
One major difference between section endpoints and page endpoints: since sections don't 'own' a specific URL, it doesn't make sense to be able to POST to them etc. I'd therefore argue that non-get handlers should be forbidden in section endpoints.
Alternatives considered
Other frameworks like Nuxt and Remix think about nested routes differently to how SvelteKit does it. Consider a route like /settings/notifications/email where email is nested within the notifications section, which is nested inside the settings section.
In SvelteKit the filesystem would look like this:
routes/
βββ settings/
β βββ billing/
β βββ βββ [files]
β βββ notifications/
β βββ βββ desktop.{js,svelte}
β βββ βββ email.{js,svelte}
β βββ βββ __section.{js,svelte}
β βββ __section.{js,svelte}
Instead of having something like __section, Nuxt and Remix use a filename with the same name as the directory:
routes/
βββ settings/
β βββ billing/
β βββ βββ [files]
β βββ notifications/
β βββ βββ desktop.js (or desktop.vue, in Nuxt's case)
β βββ βββ email.js
β βββ billing.js
β βββ notifications.js
βββ settings.js
(In both cases, /settings and /settings/notifications routes can be added with index files.)
I don't think one of these approaches is unambiguously better than the other, but we can enumerate some pros and cons of the SvelteKit approach. Pros:
- Things are appropriately colocated β all the notifications-related code lives together, rather than being split between
notifications/andnotifications.{js,svelte} - Renaming 'settings' to 'preferences' happens in one place, not two
- If you expand a folder like
settingsin your editor, the breadth of the folder is capped atn+2rather than3nwherenis the number of nested sections (i.e.billing/,notifications/,__section.jsand__section.svelterather thanbilling/,notifications/,billing.js,billing.svelte,notifications.jsandnotifications.svelte) - It's arguably more explicit
- If you needed
/settingsto have a completely different layout than/settings/*for some reason, it's easy β you can haveroutes/settings.{js,svelte}. If that file is instead used for layout,/settings/index.{js,svelte}must inherit from it unless you add a new convention for exempting it, like Remix'sroutes/settings.index.js(I've also seenroutes/settings+index.js), which feels less than 100% intuitive to me
Cons:
- The Nuxt/Remix convention is arguably more aesthetically pleasing than
__section. Though as an aside, we're using the__prefix convention anyway for__error.svelte, and we'll likely add directory-scoped__middleware.jsat some point settings.jsis a more descriptive basename than__section.jssettings.jsandsettings/notifications.jslend themselves more easily to endpoint URLs (though we would need a way to disambiguate betweensettings.jsandsettings/index.jsendpoint URLs in any case)- We're going against the grain. (Same as it ever was.)
In summary, I lean towards the __section proposal, but I would be curious to hear any arguments in favour of (or against) a more Nuxty/Remixy approach that I haven't considered here.
Importance
would make my life easier
Additional Information
No response
Activity
vwkd commentedon Mar 8, 2022
+1 on the name change as layouts can be more useful than only for UI.
The name βsectionβ is a bit confusing to me as it doesnβt imply that it wraps the page, rather even the opposite. Some alternatives could be βtemplateβ, βextensionβ, βframeβ, etc.
Rich-Harris commentedon Mar 8, 2022
You could argue that 'section' is topologically ambiguous, since it makes sense to talk about an 'outer section' that surrounds an 'inner section' (e.g. blocks of seats in an auditorium). But even without that, you could think of 'section' as representing the subtree rather than the wrapper β e.g. the 'blog section' comprises
/blog/*as well as/blogkelvindecosta commentedon Mar 8, 2022
How about
__group?rmunn commentedon Mar 9, 2022
On forbidding
postand other non-getmethods in section endpoints, what is the expected behavior if a POST is sent to an endpoint that the section handles?Looking at a concrete example will help me explain what I mean.
In
blog/__section.js, there is agethandler that sets up some server-side things common to the whole blog section, e.g. looking up theauthenticatedUserobject fromevent.locals(which was set up by ahandlehook) and setting apermissionsobject inlocalsso that other handlers can just check thepermissionsobject.Now, that works fine for
GET /blog/3. But what aboutPOST /blogto create a new blog post? That's something that only certain users have permission to do. What happens when a POST is send toroutes/blog/index.js? Specifically, what (if anything) is run in__section.js? I see two possibilities:__section.js'sgethandler is run for every request to/blog/whatever, includingPOST /blog.__section.jsruns the same handlers as the handlers in the endpoint that's ultimately being called.In case 1, the
gethandler for__section.jswould run, then theposthandler forindex.js.In case 2, the
posthandler for__section.jswould run, then theposthandler forindex.js.My preference is for case 2, because I could easily see it being very confusing to someone why a
getmethod is being run for a POST request. Plus, not all section methods would be suitable for all use cases: sometimes thegethandler in__section.jsshould NOT run for a PATCH request down the tree. If so, then omitting apatchhandler in__seciton.jswould get the desired behavior.Thoughts?
Rich-Harris commentedon Mar 9, 2022
Good question @rmunn, I should have elaborated on that.
The way that
POST /blogworks today if you have ablog/index.jspage endpoint is that theposthandler runs, then (as long as it didn't redirect or throw an error) thegethandler runs, so that/blogis rendered with data from both handlers. We can't not run theget, because then the page will have data missing. (Obviously if thepostsucceeds, it will likely redirect to the new page, short-circuiting this process, but if it returns validation errors then you need to render them and whatever other data the page depends on.)The analogous behaviour with section endpoints would be to first run the
postfromblog/index.js, then rungetfrom__section.js, thengetfromblog/__section.js, thengetfromblog/index.js. It wouldn't make sense to run apostinside the root__section.jsfor anyPOSTrequest anywhere in the app, when the job of__section.jsis to supply data to__section.svelte. We do always need to run thegethandler in a__section.js.Of course, this means you can't use the
blog/__section.jsto do auth stuff. Which makes sense in my mind: responsibility for that belongs tohandle, not the request handler itself. Right nowhandleobviously runs for every request, not just theblogscope β I'd like us to have a scoped middleware solution, but in the meantime you could put the scoping logic insidehandle.rmunn commentedon Mar 9, 2022
Ah. With that understanding in mind, then I see why it makes sense not to allow
postand other methods in section endpoints, and I agree. And yes, middleware will be the answer to the use cases I was envisioning.stephane-vanraes commentedon Mar 10, 2022
Would this effectively enable what is described in #2847 ?
Rich-Harris commentedon Mar 10, 2022
@stephane-vanraes it would, yes. There is a wrinkle we need to consider though β if you have files like this...
...and you visit
/foo/bar/baz, there are two possible things we could do: run the endpoints serially, or concurrently.If we run things serially, we introduce a waterfall (which is already present with
loadfunctions, because they inheritstuff, though you can work around it by returningprops: Promise<Props>rather than awaiting the props). If we run them concurrently,foo/bar/__section.jsandfoo/bar/baz/__section.jsneed to account for the possibility that__section.jsorfoo/__section.jsreturn a non-2xx response.Personally I'm more inclined towards serial behaviour despite the waterfall, because otherwise it defeats the object of having a guard. We can at least coalesce endpoint responses during client-side navigation so that the waterfall only happens on the server, where the damage is minimised since server-to-server communication is less costly (particularly if everything is running in the same region/data centre). We could also do the same thing we do with
loadfunctions β allowbodyto be aPromiseif you're okay with a generic 500 if it rejects.rmunn commentedon Mar 14, 2022
Would it be an error for a
__section.jsfile to exist but not export agetfunction? Or would that section be treated as having a no-opgetfunction, that does not modify the request in any way?I could see arguments for either one, but I think I'd lean towards a warning, but not an error, if a
__section.jsdoes not export agetfunction. Because there might be times when you want to comment out thegetfunction during development to test something, and it would be slightly easier to comment out the whole function than to replace it with a no-op. But maybe we want to make it an error, because the more common mistake by newbies will be to forget to writeexportin front ofasync function getand we want to push them into the Pit of Success.This thought was triggered by seeing #4316, where a
postbut nogetin a page endpoint is causing a 404. That made me wonder whether that was intended, and also whether section endpoints would have the same requirements, or whetherget-less endpoints are allowed for pages but not sections.stephane-vanraes commentedon Mar 14, 2022
I feel this is a bad reason for renaming, if anything
sectionfeels even weirder. At least withlayoutyou can argue that is naming consistency between different features, especially considering that most developers will likely encounter this in the context of layouts and not of standalone pure data endpoints.Those are more of an advanced topic, at which time you got used to the naming. That it is not "100% semantically correct" can be easily handwaved away at that point and I doubt many users would make a big deal out of it.
Saying that
layoutdoes not refer to data is ambiguous on it's own, you could very well argue that you are 'laying out data'1Furthermore looking at #4275 I believe that
named layoutsare easier to understand thannamed sections,Finaly with sections (especially named sections) I would expect to be able to designated different 'sections' in a page (like header, footer, ...) similar to how slots work.
Footnotes
actual argument left to the reader as an exercise β©
brittneypostma commentedon Mar 14, 2022
I very much agree that
sectionfeels stranger thanlayout, alsolayoutfeels more familiar back to Sapper days. A Layout wraps a page and can have data with it. A section feels like you should have multiple per page.I like
templatebetter thansectionif renamed, but again it feels almost like a breaking change just for the sake of a convention.Rich-Harris commentedon Mar 14, 2022
Yeah, we had a discussion about this in the maintainers' chat and concluded that keeping
__layoutis probably better on balance. A key realisation for me was that you wouldn't want to get the data for a layout/section individually, i.e. there'd be no__layout.jsonor__section.jsonβ instead, a page's__data.jsonshould include the layout data as well as the leaf data. Otherwise you'll find yourself making unnecessary round trips.[-]Rename `__layout` to `__section` and add section endpoints[/-][+]Add section endpoints[/+]8 remaining items
jason0x43 commentedon Jun 18, 2022
@Spenhouet That should already work; this issue is specifically about endpoints for
__layout.svelteroutes, which don't currently work. Make sure your endpoint exports agetrequest handler function (notload, as I tried the first time I implemented a page endpoint π).Spenhouet commentedon Jun 18, 2022
@jason0x43 Sadly it's not working for me. I have other endpoints running which use the typical routing pages but for components it's not working for me. Just to make this clear, with component I mean that it is imported somewhere and is not loaded via sveltes routing.
In my case I'm importing it in a Header component like this:
Which itself is imported and used in
__layout.svelte.Before I create a separate bug report and before I chat here about it I opened a thread on the Svelte Discord: https://discord.com/channels/457912077277855764/939868205869072444/987845135129796659
MadeByMike commentedon Jun 19, 2022
Seems to me that another possible solution could be to expand the
ResolveOptionsand then you could put data in a hook.Something like:
jason0x43 commentedon Jun 20, 2022
@Spenhouet Ah, sorry, I missed the fact that you were talking about non-route components. Never mind me... π
jason0x43 commentedon Jun 20, 2022
Just out of curiosity, how would a page endpoint work in the case of a non-page component? Like, what would be its expected behavior? A page endpoint is called when a route is accessed to supply data to the associated page, but that doesn't seem applicable to a non-page component.
Spenhouet commentedon Jun 20, 2022
Like in my case, I'm adding a search bar to the header. The search bar is basically just a combobox showing data filtered based on what one entered into the search bar.
The underlying data needs to come from somewhere.
Writing an endpoint for that seems straight forward to me. In my case
search.jswhich is supposed to load the data for the search bar component.One can use this to load data for any form of sub component.
So would you consider this to be an extension of this feature request or a separate "component endpoints" feature request?
jason0x43 commentedon Jun 20, 2022
For the search bar, I would think a standard endpoint, like
/routes/api/search.js, would be the way to go. A page endpoint provides data to an associated component when that page is loaded, but a search bar doesn't seem like it would need data at load time (unless the search is entirely client side). Rather, it would need an endpoint to send queries to.Spenhouet commentedon Jun 20, 2022
@jason0x43 Did I mention that the page is static? So yes, it's purely client side.
jason0x43 commentedon Jun 20, 2022
That does seem like a reasonable use case for a non-page component endpoint.
madeleineostoja commentedon Jun 21, 2022
I feel like general non-route endpoints for any old component is a very slippery slope, and could add a lot of complexity to Sveltekit's data layer without a much gain over just using a standalone endpoint and
fetching it in the component.If you needed server fetched data for a component, you could just get it in a __layout endpoint (the focus of this issue) and throw it in
$page.stuffhomerjam commentedon Jun 30, 2022
+1 for
__middleware.ts+__layout.svelteI think removing the ambiguity about what goes where is helpful (it's always bugged me that I have arbitrary setup code in layout which should be strictly for the template IMHO).
Rich-Harris commentedon Aug 16, 2022
Closed via #5778