Clean front end architecture with SvelteKit
nikoheikkila.fi
nikoheikkila.fi
"I don't recommend having components responsible for querying data because their responsibility is already in presenting the data. More accurately, components need only receive data from view models, format it, and output it to the screen. Instead, I advise you to follow either of the three following ways:
Render the data on the server and pass it to components as a view model, as shown in this guide.
Use a state management library that supports dispatching actions (e.g. Redux or MobX), deriving view models from the state, and passing them to components as properties."
This is opposite to what Next.js new React Server Components stuff is advocating for in the new app/ dir structure. It expects every component to fetch the required data, and just cache any duplicate calls. It's probably good for a Serverless / Edge deployment but I much rather use a MobX store that takes care of state, fetching and mutations.RTK Query does something similar, offering multiple ways to initiate, update and use the data of the queries.
Here is some example code, and imo it‘s really greener than anything else.
async function getData() {
const res = await fetch('https://api.example.com/...');
if (!res.ok) {
throw new Error('Failed to fetch data');
}
return res.json();
}
export default async function Page() {
const data = await getData();
return <main></main>;
}They say there's a new `cache` function in React and they have patched `fetch` to use it by default (for GET requests).
Does this include a solution to the N+1 queries issue (container element requests a list of items, then item elements each request their details)? I see you can do pre-fetching, perhaps those can be batched.
EDIT: Found an example that uses DataLoader by "caching the cache". The src/api.ts module exports a cached DataLoader for characters, and src/components/CharacterAvatar.tsx imports and calls it during render simply like this:
const character = await characters().load(id);
https://github.com/AndrewIngram/next-rick-morty- react being the most popular FE library for time to come
- gain the user's mindshare as react being now a Vercel product (something which is becoming increasingly true)
- users attracted by react and next eventually becoming Vercel customers.
They have also tried or employed several other major library authors in order to position themselves uniquely at the crossroads of major FE software and thus be uniquely positioned to transform those users again in Vercel customers.
I don't judge any of this negatively or positively but that's the case I see.
I remember they got Sebastian :-) Who else?
- at least 2 (top #2) works at Vercel
- at least 4 works at Facebook
Edit: but this is just commits for facebook/react, reality might look differently :)
Whom React got from InfernoJS
In the rest of the world, SEO is the main use case, e.g. Company X (some kind of retailer) has invested in an SPA (when what they needed was an enriched MPA) and then found they were loosing their search engine rankings. Either they:
1. Render that in a headless browser, cache the results, and serve that to crawlers (non-optimal as detecting bots is hard); or 2. Rewrite their new website to be properly architected (at cost); or 3. Buy into server rendering to serve both normal visitors and crawlers.
I worked at a company that had _exactly_ this journey. Don't forget the non-functional requirements when designing solutions, kids.
The best such codebase I can think of might still have been better off overall as an enriched MPA, but given how few normal pages it had compared to the app-ish bits - thereby making staying on a single technology stack a bigger advantage - I'm not quite willing to say it -definitely- would've been better as an enriched MPA. Not quite ;)
In philosophy, the first thing to understand a philosopher's thinking (make a model of his mind) is to read his work but the second is to read who are his influencers.
No field is truly neutral or deeply agnostic (except reality itself which is The Great Equalizer).
But it can lead to defining asynchronous workflows through the nesting of components, controlled by their mounting/unmounting and other state. I much rather have something like RTK Query which lets me both use it in a hook for simplicity and in Thunks or Sagas for more complex things.
When developers talk about a "clean way" to do things, I immediately think of overconfidence. Can't help it.
YMMV.
https://redux-toolkit.js.org/rtk-query/usage/examples#svelte
We've also seen people use RTKQ with Vue and NgRx as well, like this:
Most of the websites I visit are static and when they are not their dynamic content is annoying. Look at new vs old reddit for a good example.
Most websites would be better off being statically rendered.
Being able to collapse a comment thread, or upvote a comment, or post a reply, without reloading the page, means the website is dynamic. Static only means that nothing changes without a page reload, which is thankfully long gone.
Also, the new and old reddit are exactly the same in terms of "staticity". It's just that the new design sucks.
Similarly I'm sure you'd qualify Facebook of being an evil dynamic website. But open Facebook and HackerNews side by side, the content on the former won't update dynamically more often than the latter.
No! That is interactive!
Dynamic means hot loading content without refreshing the page. I’ve been doing web dev since web 1.0 so again, no.
Interactivity = collapsing a thread
Dynamic = posting a reply and it being sent and displayed without reloading the page
FWIW, I don't believe Reddit does the latter.
I'm not sure if Reddit does it for messages but they do for votes for example. HN too.
Because frameworks are sets of premature abstractions it really depends on how they do it and how much of benefit they provide compared to other existing solutions. I think we came a long way and SvelteKit really does provide minmal bloat and redundant complexity.
I also see some straw man arguments, e.g.
> Developers dislike design because it's time-consuming.
I've never met a developer who doesn't like to design. I'd say the vast majority of developers even if tasked with something as simple as creating a button first try to craft a universal solution that can somehow be reused. Instead the correct design methodology most of the time is called KISS. You can always make it more complex later, but making it simpler is usually a lot more difficult.
For anything but a demo app with just a couple of routes it's a headache to navigate.
Edit: Another smell of the routing system to me is that you need to resort to complexity like this [1] to have anything but top down inheritance. I love Svelte btw and have used it in many projects.
[1] https://kit.svelte.dev/docs/advanced-routing#advanced-layout...
It might look complicated at first sight, but once you actually use it you really appreciate the way it's structured.
This whole file-based routing wasn't a great idea to begin with, as a general solution to routing. It works (up to a point) for a static site generator, but most SSGs provide a permalink setting so there's an escape hatch.
The whole thing gets even worse when you start introducing issues like having dozens if not hundreds of files with the same filename, weird characters in folder and file names, etc.
Plus I can't use it with Go, PHP, Ruby, Rust etc when it comes to SSR (without running multiple servers and handling deployment nightmares).
Something about this whole Node + SSR Front-end is smelly. (next, nuxt, solidstart) I love Svelte as a framework and a way of writing UI, but SvelteKit. Eh! Not so much.
SvelteKit is too much complexity for no reason. Goes opposite of what Svelte was meant to be: Simple and intuitive.
SvelteKit is a JavaScript framework, it makes sense that you can't use it with other languages. You can pair it with a backend of your choice of course, but to get the SSR benefits you do need to work within the framework.
There are other ways of using Svelte with other languages, I would take a look at something like Inertia.js [0].
Now, I am not specifically targeting SvelteKit to be fair. But the whole host of meta-frameworks like NextJS, NuxtJS etc which Vercel is pushing.
These frameworks in general are too much complexity added. SSR is hard and the best way to handle all of these is to not have a server layer at all. That is just abstract the rendering/routing part and leave the rest of the server stuffs to the user.
I want to simply write my Fastify/Express/Go-gin/Django app. Then add SvelteKit as my front-end with SSR support.
Right now, I first write SvelteKit and then think how am I going to integrate Express and Fastify to it (for a moment let's leave non-node solutions).
Trust me. If you simply leave the server out of SK and generate a simple API abstraction like `res.send(renderSKPath('/users/:id', { serverData }))`. It would have done the job.
I think its difficult to express what I want to say, but in short, remove the server and keep SK as a rendering layer only.
P.S. I know that there is an express adapter for SK. But that is not the point of this comment at all.
I've been using Svelte happily for years, but I won't be using SvelteKit. In part because of the routing but also because it doesn't really solve much in the backend.
It's amazing that all the full stack frameworks (Next, Nuxt, SvelteKit, Remix, Astro, etc) are investing so much effort into reinvent the backend and after years they still don't provide even basic backend functionality. For example, out of the box, Fastify gives you validation, sessions, CORS, cache headers, etc. Features that you need in probably all backend projects.
I started this repo to figure out how to integrate Svelte with Fastify using Vite. It has hot reload, partial hydration, etc. It's very quick and dirty code, but it works.
It's more than an aesthetic & workflow preferences. It's also a client management risk. Clients who have no development experience are often used to the same level of productivity to create the initial feature set. As development slows due to maintenance & performance issues, the client does not understand why. Clients also will use analogies, such as a mechanic overcharging for work & using words the client does not understand to justify high fees & billable hours...without understanding that changing a complex system with many undocumented & haphazardly implemented parts can create bugs.
Enter a maintenance project at your own risk. Due diligence of the business, codebase, and client's temperment, understanding of software development, decision making, & payment schedule can save you from headaches over the next few months.
Erm, how much of the web is still powered by Wordpress, again?