You probably don't need a SPA framework
Over the last months I’ve been building a bunch of hobby projects - an app to manage security infrastructure, a booking app for company resources (rooms, equipment, the usual stuff) and a customer portal for sharing non-public files - each time with a different backend (Express, FastAPI, even Spring), and every single one of them ended up the same way on the frontend: server-rendered HTML, a bit of htmx and a few lines of hand-written JavaScript.
Side note: a few years ago I probably wouldn’t have built half of these, because a side project with one person behind it hits the wall pretty fast when there’s no one to split the work with, no one to bounce ideas off and no one to tell you “dude, this is a bad idea” before you waste two weekends on it. LLMs in the state they’re in today changed that for me, since I now have a partner who’s available at 11 PM, writes the boring parts, argues with me about the architecture and doesn’t get offended when I throw the whole thing away and start over with a different stack, so I try a lot more things and in a lot more ways - but that’s a topic for a separate blog post.
Back to the frontend - I didn’t plan to end up with server-rendered HTML every time, I just kept noticing that the SPA part wasn’t giving me anything. Did I measure it? No, it’s an overall impression from using my own apps, but servers, networks and browsers are so fast nowadays that a server-rendered page swapping a piece of HTML feels pretty much the same as a React app doing the same thing, and the real difference is in how much code I have to write and keep alive. It’s also about cognitive complexity, because when an LLM is generating a good chunk of the code, keeping the whole thing in one place (one backend, one set of templates, no second app in the browser) makes it a lot easier for me to keep track of what’s actually going on, and as a bonus it’s more token efficient too, since the model has less code to read and less to keep consistent with every change.
I’m not trying to convince anyone here, this is just what I do now and why.
Most apps are systems of record
Most of the apps we build, at work and at home, are systems of record where someone fills in a form, the server checks it against some rules, stores it and shows you a list of bookings, tickets, assets, users or files, with the truth living in the database and the rules living on the server.
A SPA framework pulls part of that logic into the browser, and the browser doesn’t really need it there, but a client-rendered UI has to know which fields are valid, which buttons this user can see, which state changes are allowed and how to calculate the total in order to render itself. So you write those rules again in TypeScript and keep both copies in sync forever, and since you still can’t trust the client copy, the server stays the authority anyway.
The usual suspects that end up living in two places:
- Validation, like “end must be after start”, “max 8 hours” or “this field is required if that one is set”.
- Permissions, where you hide the button in the UI and still have to enforce it on the server.
- State transitions, for example a booking that can go from
pendingtoconfirmedbut not fromcancelledtoconfirmed. - Computed fields such as durations, totals and statuses derived from other fields.
The same form, three ways
Let’s take a “book a resource” form from the booking app, with these rules: end must be after start, a booking can’t be longer than 8 hours, the user has to be allowed to book that resource and the slot can’t overlap with an existing booking.
Server-rendered with htmx (FastAPI + Jinja)
All the rules live in one function:
def validate_booking(db, user, resource_id, start, end):
errors = []
if end <= start:
errors.append("End must be after start.")
if end - start > timedelta(hours=8):
errors.append("Bookings are limited to 8 hours.")
if not user.can_book(resource_id):
errors.append("You can't book this resource.")
if db.overlaps(resource_id, start, end):
errors.append("That slot is already taken.")
return errors
The endpoint returns HTML, so on error it renders the form again with the messages, and on success it returns a fresh form plus the new row, which htmx appends to the list out of band:
@app.post("/bookings", response_class=HTMLResponse)
def create_booking(
request: Request,
resource_id: int = Form(...),
start: datetime = Form(...),
end: datetime = Form(...),
user: User = Depends(current_user),
db: DB = Depends(get_db),
):
errors = validate_booking(db, user, resource_id, start, end)
if errors:
return templates.TemplateResponse(request, "booking_form.html", {
"errors": errors,
"form": {"resource_id": resource_id, "start": start, "end": end},
"resources": db.bookable_resources(user),
})
booking = db.create_booking(user, resource_id, start, end)
return templates.TemplateResponse(request, "booking_created.html", {
"booking": booking,
"form": {},
"resources": db.bookable_resources(user),
})
The template:
<!-- booking_form.html -->
<form id="booking-form" hx-post="/bookings" hx-swap="outerHTML">
<select name="resource_id">
{% for r in resources %}
<option value="{{ r.id }}" {% if form.resource_id == r.id %}selected{% endif %}>{{ r.name }}</option>
{% endfor %}
</select>
<input type="datetime-local" name="start" value="{{ form.start.strftime('%Y-%m-%dT%H:%M') if form.start else '' }}" required>
<input type="datetime-local" name="end" value="{{ form.end.strftime('%Y-%m-%dT%H:%M') if form.end else '' }}" required>
{% for e in errors %}<p class="error">{{ e }}</p>{% endfor %}
<button>Book</button>
</form>
<!-- booking_created.html -->
{% include "booking_form.html" %}
<div hx-swap-oob="beforeend:#bookings">
<li>{{ booking.resource.name }}: {{ booking.start }} to {{ booking.end }}</li>
</div>
There’s no client-side copy of the rules, no API contract to version and no JSON shape shared between two codebases, and the dropdown only shows resources this user can book because the server already knows that, so one script tag for htmx and you’re done.
React
const MAX_HOURS = 8; // must match the backend
function BookingForm({ onCreated }: { onCreated: (b: Booking) => void }) {
const { data: resources } = useQuery(["resources"], fetchBookableResources);
const { data: me } = useQuery(["me"], fetchMe);
const [form, setForm] = useState({ resourceId: "", start: "", end: "" });
const [errors, setErrors] = useState<string[]>([]);
function validate(): string[] {
const errs: string[] = [];
const start = new Date(form.start), end = new Date(form.end);
if (end <= start) errs.push("End must be after start.");
if ((end.getTime() - start.getTime()) / 36e5 > MAX_HOURS)
errs.push(`Bookings are limited to ${MAX_HOURS} hours.`);
if (me && !me.permissions.canBook.includes(Number(form.resourceId)))
errs.push("You can't book this resource.");
return errs;
}
async function submit(e: React.FormEvent) {
e.preventDefault();
const clientErrors = validate();
if (clientErrors.length) return setErrors(clientErrors);
const res = await fetch("/api/bookings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
});
if (!res.ok) {
const body = await res.json(); // server still validates (overlap, permissions)
return setErrors(body.errors ?? ["Something went wrong."]);
}
onCreated(await res.json());
setForm({ resourceId: "", start: "", end: "" });
setErrors([]);
}
return (
<form onSubmit={submit}>
<select value={form.resourceId} onChange={e => setForm({ ...form, resourceId: e.target.value })}>
{resources?.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
</select>
<input type="datetime-local" value={form.start} onChange={e => setForm({ ...form, start: e.target.value })} required />
<input type="datetime-local" value={form.end} onChange={e => setForm({ ...form, end: e.target.value })} required />
{errors.map(err => <p key={err} className="error">{err}</p>)}
<button>Book</button>
</form>
);
}
On top of that you need a JSON API on the backend that still runs validate_booking, a /api/me endpoint that exposes permissions to the client, Booking and Resource types that mirror the backend models, a query library, a bundler and a build step. The 8-hour rule now lives in two places with a comment begging everyone to keep them in sync, and the permission check lives in two places too, where the client one is basically decoration.
Angular
const MAX_HOURS = 8; // must match the backend
function bookingRules(perms: () => number[]): ValidatorFn {
return (g: AbstractControl): ValidationErrors | null => {
const { resourceId, start, end } = g.value;
const s = new Date(start), e = new Date(end);
const errors: ValidationErrors = {};
if (e <= s) errors['order'] = 'End must be after start.';
if ((e.getTime() - s.getTime()) / 36e5 > MAX_HOURS) errors['length'] = `Bookings are limited to ${MAX_HOURS} hours.`;
if (resourceId && !perms().includes(+resourceId)) errors['perm'] = "You can't book this resource.";
return Object.keys(errors).length ? errors : null;
};
}
@Component({
selector: 'app-booking-form',
templateUrl: './booking-form.component.html',
})
export class BookingFormComponent {
@Output() created = new EventEmitter<Booking>();
resources$ = this.api.bookableResources();
serverErrors: string[] = [];
form = this.fb.group(
{ resourceId: ['', Validators.required], start: ['', Validators.required], end: ['', Validators.required] },
{ validators: bookingRules(() => this.session.permissions.canBook) },
);
constructor(private fb: FormBuilder, private api: BookingApi, private session: SessionService) {}
submit() {
if (this.form.invalid) return;
this.api.createBooking(this.form.value).subscribe({
next: b => { this.created.emit(b); this.form.reset(); this.serverErrors = []; },
error: (err: HttpErrorResponse) => this.serverErrors = err.error?.errors ?? ['Something went wrong.'],
});
}
}
Add the template, a BookingApi service, a SessionService that loads permissions, the module (or standalone) imports and the same JSON API on the backend, and you get the same duplication with more ceremony.
None of this is bad code, it’s exactly what these frameworks ask you to write, but in a system-of-record app all of it is overhead wrapped around rules that already exist on the server.
Next.js and Nuxt make it worse
Next.js and Nuxt try to fix the split by running the same framework on both sides, which sounds great until you end up with a codebase where you constantly have to know on which side of the wire a piece of code runs - server components, client components, "use client", hydration mismatches, loaders, server actions - and that’s a massive amount of complexity that gives me very little for a booking form.
You also get locked in, because the framework’s conventions shape your routing, data fetching, caching and deployment, and some features work best (or only) on one specific hosting platform.
Then there are the dependencies, so run du -sh node_modules on any fresh Next.js or Angular project and compare it to the size of the app you’re actually writing, keeping in mind that every one of those packages is code you didn’t read, from people you don’t know, running in your build pipeline. If you ever had to answer a supply-chain question from a security team, you know this is not an abstract problem. 😉
What I do instead
I do server-side rendering in whatever backend fits the project, htmx for the parts that should update without a full page reload and a bit of hand-written JavaScript for the rest.
The browser itself can do a lot more than it used to with <dialog>, the Popover API, native form validation, fetch, CSS that handles most of the layout and transitions, and web components if I need something reusable, so a lot of the things I used to install a library for are now an attribute or twenty lines of JS.
This is also where LLMs changed the math for me, because hand-written code used to be expensive to write and expensive to maintain, and now I ask for a 40-line vanilla component that does exactly what I need, review it and own it instead of pulling in a 200 KB library for one feature. LLMs make it really cheap to take only the fraction of a big framework that your project actually needs and skip the fluff, and they’re pretty good at keeping templates and small scripts consistent across the codebase, which used to be one of the main arguments for using a framework in the first place. (I wrote more about treating prompts as part of the codebase in Prompts as a Code.)
Funny enough, we’ve been here before, since server-rendered pages with a sprinkle of JavaScript is how most of the web worked before SPAs were cool, except that now the server is fast, the browser is capable and the boring parts are cheap to write.
When I’d still use one
Some apps genuinely need to keep state in the browser, like a collaborative editor, a design tool, an offline-first app, a canvas that updates many times per second or anything where the client is the source of truth for a while, and for those a SPA framework 100% earns its weight.
But most of what I build, and most of what I see being built at work, is forms, lists, detail pages and rules, where the server already knows everything, so I just let it render the HTML, and every time I’ve tried it, it was simply the easier path.