Modern web app development
Before we dig deep into Svelte, or any other JavaScript framework for front-end development, it helps to take a quick trip down memory lane and look at how we arrived at modern web app development, and the role that frameworks play.
How the web became static…again
When I built my first website, in 1999, it was just like what you would expect: rich in flashy GIFs, scrolling texts, and eye-hurtlingly bright colors. It was also served by static hosts that were essentially the Italian equivalent of GeoCities.
I had built that website using the most advanced tools available for webmasters at the time: WYSIWYG editors (which stands for What You See Is What You Get): for me, that meant Microsoft FrontPage.
FrontPage worked just like Wix.com and other similar services of present day, where you build your website visually and the code is generated for you. It differed in that it was a native desktop app and, in the middle of the first browser war, it outputted code that ignored web standards and was optimized for Internet Explorer. Of course, all those websites were fully static. (In case you're wondering, I eventually "graduated" to Macromedia Dreamweaver, which was more standards-compliant; Macromedia was later acquired by Adobe, and Adobe Dreamweaver is still maintained today.)
Ten years later, in 2009, I was still building websites, but then I was making them dynamic, with server-side generation in PHP. Those were the days of "rich internet apps," where users could interact with a website, and "web 2.0," centered around collaboration and user-generated content.
Generating web pages on a server was not a novel concept per se: Java EE was released in 1999, Microsoft created ASP in 1996, and the original PHP came out in 1994! However, it was only in the second half of the '00s that those technologies became more accessible to small teams and individual developers, first of all thanks to new, simpler frameworks: for example, Django and Rails were both released in 2005. Additionally, in those years, we started seeing increasingly cheaper options for hosting web applications that require server-side rendering, especially with PHP.
Around the same time, interactivity started to appear in frontends too.
Developers had been building apps that run within browsers for a long time, leveraging plugins such as Java Applets, ActiveX objects, or Macromedia Flash (later, Adobe). Those were plagued with issues ranging from poor performance to serious security flaws, and they always ran almost completely isolated from the rest of the web page and the DOM. JavaScript was mostly considered a tool for designers to add small bits of interactivity to web pages and other gimmicks – just like its creators had originally meant it for.
Then, Google released Gmail in 2004 and the next year, they built Google Maps, and those were among the first large-scale applications to run primarily within the browser itself (any browser) without plugins. They popularized a new way of building web apps, where data is loaded dynamically in response to user action: this technology was then called Asynchronous JavaScript and XML (AJAX). The foundation for AJAX was the XMLHttpRequest API, which existed in Internet Explorer as an ActiveX object and was later implemented by other browsers in a compatible way too.
Another relevant change for JavaScript developers at the time was the creation of libraries such as Prototype in 2005 and jQuery the next year. At a time when browsers were still running JavaScript based on the ECMAScript 3 standard, these libraries provided great help by offering convenient features to web developers, such as easier ways to access and manipulate the DOM. They also helped by abstracting away the complexity of targeting all web browsers, including the then-dominant Internet Explorer 6 and its poor support for web standards.
With the help of AJAX and libraries such as jQuery, it became clear to developers that apps could run within a browser itself, and the amount and sophistication of web apps started growing.
Fast forward to 2020, and browser-based web apps are the new norm, to the point where we can often replace native, desktop apps with web ones running inside the client: from spreadsheets, to photo editing tools, to complex 3D video games.
The last decade brought along a set of innovations that helped make front-end development simpler, more accessible, and more powerful.
This included innovations in browsers, with faster JavaScript engines, and in the standards themselves. New HTML5 and CSS3 specifications added a bunch of new features, including the <video> tag that killed Adobe Flash for good, the last standing of the plugins. As for JavaScript, ECMAScript 2015 (ES2015, often called ES6) was finally released in 2015, after a much-troubled process (which is an interesting story in itself). Innovation is continuing, with technologies such as WebAssembly posed to completely rethink the way we build apps too.
As for the developer experience, a new class of front-end frameworks started to appear with AngularJS 1.0 being released in 2010, whose goal was to make it easier to write large-scale apps in JavaScript, avoiding the creation of unmaintainable "spaghetti code." We'll look a bit deeper at these frameworks and how they work, and how they compare to Svelte, later in this chapter.
Eventually, in what could be called a clear example of Nietzschean eternal recurrence applied to software development, we're back to building web apps that are completely static, and they have never been more powerful. (We're also using a very large number of GIFs once again, but at least we're doing it ironically this time!)
Building apps with the JAMstack
Along with advancements in the web technology and browsers, developers have been able to leverage new paradigms.
One of the most relevant to us in this book is the so-called JAMstack, an acronym of the following:
- JavaScript
- (Reusable) APIs
- (Pre-rendered) Markup
Inside the JAMstack
The JavaScript part shouldn't come too much as a surprise: in the JAMstack, apps are written in JavaScript and run within a web browser. You can interpret this more broadly to refer to all apps that run within a JavaScript VM in a browser, to extend the definition to also include apps that use WebAssembly.
More interesting is the APIs part. One of the most sought-after features of JAMstack apps is how they deliver a great end user experience by allowing interactivity. This is possible thanks to apps interacting with other back-end services through a set of predefined APIs:
The most commonly used APIs are RESTful endpoints that are accessed via HTTP(S), just like we'll be using in this book's sample app. More recently, developers have started to leverage GraphQL too as an alternative format, which is especially optimized for data that can be represented by graphs (GraphQL was invented by Facebook, as a matter of fact). Alternative transport protocols are possible too in certain scenarios, such as using WebSocket for two-way data streaming, or protocol buffers and gRPC for apps that need to transfer large amounts of structured data (although gRPC doesn't yet work natively within web browsers and requires a proxy).
Lastly, pre-rendered markup refers to how JAMstack apps are made of bundles of HTML, JavaScript, and CSS files, as well as assets (images, fonts, and so on) that are rendered at "build-time." Using tools such as Webpack, various source files are packaged together and minified. Text content can also be pre-rendered from Markdown documents, thanks to static site generators such as Gatsby, Hugo, and Jekyll.
JAMstack apps are "compiled" and packaged inside the developers' machines or, more commonly, in a continuous integration server. The final bundle, which contains only HTML, JavaScript, and CSS files, in addition to any static asset, is self-contained, and is often deployed to object storage services in the cloud, such as Azure Blob Storage and AWS S3. Because the applications' files are completely static, developers usually place a Content Delivery Network (CDN) in front of the object storage service: this caches the files in edge nodes around the world, delivering faster speeds and lower latencies to all visitors worldwide.
Benefits of JAMstack applications
JAMstack apps are enjoying well-deserved popularity, both with developers and end users.
For teams building and operating apps, the benefits of the JAMstack mainly fall into two categories: simpler operations and better developer experience.
The latter group enjoys a great user experience, being able to use apps that are interactive and yet run within a web browser. But, most importantly, JAMstack apps feel fast.
For operators
On one hand, operations are simpler and cheaper than for traditional web applications:
- Because JAMstack apps are just a bundle of static files, they can be deployed to object storage services on the cloud, which offer high availability and reliability, and are shockingly inexpensive: their billing model normally charges a few cents per GB stored per month. This is in addition only to the egress bandwidth cost, which you would be charged for regardless of the way the application is built.
- When deploying the application to object storage services, there's no need to maintain a complex infrastructure: teams don't need to deal with things such as containers and container orchestrators such as Kubernetes. There are also no servers to maintain, nor operating systems and application frameworks to patch.
- Because the apps maintain no state, replication, including geo-redundancy, involves just copying the file bundles to the separate locations and using a bare-bones load balancer.
- JAMstack apps can be deployed atomically by copying the new bundle of "compiled" files in a staging directory, and pointing the application to the new location, with minimum downtime.
- Lastly, as mentioned previously, apps can be cached by CDNs completely and effectively, offering faster speeds and lower latencies to your end users.
As a nice side benefit, serving your application's front-end and all static assets (scripts, images, and so on) from an object storage service and a CDN reduces the load on your infrastructure, which receives requests only for the data.
For developers
On the other hand, JAMstack apps come with a delightful Developer Experience (DX) too.
You might have noticed a similarity between the way JAMstack apps are designed and mobile or desktop ones. In both cases, the application is self-contained and runs entirely within the client, and it communicates with back-end services over the network:
- The first consequence of this is that there's a clear separation of roles and responsibilities. As long as they agree on a common set of APIs, front-end and back-end teams can work autonomously from each other. Both teams also have more freedom in their choices around technologies and stacks, not having to depend on both parties to agree on monolithic frameworks and their templating systems.
- The decoupling of the front-end from the back-end creates the by-product of reusable APIs that can be leveraged by other teams for their purposes, independently. For example, your organization might decide to build a native mobile or desktop app using the same back-end services, while another team could integrate the same APIs in a completely different product, and business users might even build custom interfaces, such as reporting using "no-code" solutions interacting with the same back-end.
- Even the life cycle of the various tiers of the application is decoupled. The front-end team can change their code and redeploy the application without impacting the back-end systems.
- JAMstack apps are normally "compiled" really fast, so developers can see their code's behavior in real time, often with Hot Module Reload (HMR) support too. The tools required to build and deploy applications are fairly standardized by now, so there are pre-made templates for most continuous integration and continuous delivery platforms.
- Lastly, because the front-end is fully independent from the back-end, frontend developers have the ability to experiment freely. Developers can A/B test various versions of their front-end code independently and safely. In many cases, notwithstanding policies saying otherwise, they might also able to point development front-end apps to production back-end services, with no risk to the availability of the live application.
For end users
As an end user of web applications yourself, this paragraph might be familiar to you.
JAMstack apps feel, and often are, fast. When users perceive your app to be fast, their satisfaction increases, and they are easier to retain.
This is made possible by having a separation between the application code and data, by doing most requests asynchronously and by caching data extensively:
- When requesting a JAMstack app, clients first load the app's shell, which consists of the app's code without any data. Because the app's bundle is fully static, this request can easily be served by CDNs: these have plenty of bandwidth and edge nodes in hundreds of places around the world. Users can fetch the app's shell faster, and the reduced distance to the CDN's edge node leads to less latency, which means that they start receiving data sooner. Additionally, browsers can store the app's shell in their own cache, so returning visitors might be able to avoid requesting it completely.
Even though your app's shell might be many kilobytes in size, thanks to the improved performance of the CDN and the extensive caching, the experience for end users is a positive one.
- Asynchronous loading of the data improves the perceived speed of your application. With JAMstack apps, browsers render the shell first, and then request the data asynchronously. Even as they wait for the data to load, users can see your app's interface and interact with it, making your app feel faster overall. This is in contrast with traditional apps, where browsers need to wait for the full HTML, both structure and content, before they can render the page and accept interactions.
- Because your server doesn't have to render full-blown HTML pages, page generation time is faster. But even more importantly, the amount of data transferred to users is smaller.
- Even more, by loading data asynchronously, apps can prioritize the content they're loading. For example, you could request and render the content for your app's main view before populating the sidebar.
Compared with desktop and mobile applications, JAMstack apps are delivered via a web browser using the Software-as-a-Service (SaaS) model, with constant updates, fixes, and new features, to the delight of your users.
Third-party APIs
I mentioned that the API part of the JAMstack is the most interesting one: in my opinion, this is where the biggest opportunities are.
In fact, as apps' tiers become more decoupled, you might even be able to build JAMstack apps that do not integrate with any back-end services that you (or your organization) manage.
Identity services
Perhaps the best example of this is authentication, where your app can integrate with external identity providers. There are multiple reasons why I consider this a good idea rather than rolling out your own identity system, starting from the obvious: that you have less code to manage – especially code that is usually outside your core business logic – to the fact that larger, more robust identity services can offer significant security benefits.
If you're building an enterprise application, it's likely that your organization's identities are already synchronized with Azure Active Directory (Azure AD) (for organizations that use Microsoft 365) or G Suite, both of which can be used by third-party applications too.
For consumer apps, using a social identity is often a convenient choice: Apple, Facebook, GitHub, and so on.
There are also other services, such as Auth0, Okta, and Azure AD B2C, that offer flexible, powerful options, including support for built-in accounts (users can sign up and create a new profile for your app) as well as integration with external services.
SaaS services
Aside from authentication, you can integrate with a very large number of APIs offered by SaaS providers.
For enterprise applications, you can get a vast amount of data by integrating with your organization's productivity suite, such as Microsoft 365 or G Suite. For example, you can access your users' calendars, store data inside their cloud storage space (OneDrive for Business or Google Drive), send and receive emails, create and share presentations and spreadsheets, make phone calls, and much more.
Consumer apps can leverage services such as Dropbox, Google Drive, or Microsoft OneDrive to store arbitrary, persistent data.
Besides that, you can find APIs online for literally anything, from showing maps to providing directions, from searching for images to collecting payments, and from tracking parcels to getting the status of a flight.
APIs for developers and integrations
In this far-from-exhaustive list of APIs, there are two more sub-categories of services that you could leverage in your JAMstack apps.
The first one is about APIs specifically meant for developers looking at integrating features in their applications. Examples of real API services include the following:
- Creating a thumbnail for an image
- Video encoding
- Converting files into other formats, such as creating PDFs from a Word document, or converting PNG images into JPG
- Detecting fraudulent activities
- Stopping bots – for example, with CAPTCHAs
- Triggering a software release with a continuous delivery pipeline
- …and many more!
The other group is about using "low-code" or "no-code" platforms to perform certain automated tasks for your application. Services in this category include Microsoft Power Automate, Azure Logic Apps, and Zapier.
These even allow connecting to resources (such as databases, ERP systems, and so on) that cannot otherwise be safely accessed by a front-end only app or performing actions automatically in response to events; for example, sending an email notification every time you receive a new tweet or recording an entry in a spreadsheet when someone presses a button in your web app.
In the consumer space, IFTTT offers a large amount of integrations, including social networks, weather forecasts, smart home appliances (for example, lightbulbs, thermostats, refrigerators, and so on), personal fitness solutions, and other consumer platforms and services.
Why use external APIs?
The most obvious reason why you might want to integrate external APIs is that you don't have to manage them. It becomes someone else's responsibility to ensure that they're available and scale, to apply security fixes, and so on.
Another benefit might be around compliance. For example, using an external payment platform, such as Stripe or Square, frees developers from having to build applications and infrastructures that comply with PCI-DSS. If your app doesn't store any user data, you might also have an easier time adhering to privacy regulations, such as GDPR, because the burden of compliance falls on the API service providers. (But confirm this with your legal team.)
JAMstack versus SPAs and PWAs
At this point, you might be wondering how the JAMstack compares with other trends in web app development, namely Single-Page Applications (SPAs) and Progressive Web Apps (PWAs).
SPAs are web applications where all the views are contained in a single HTML page, and routing happens inside the browser. This is in contrast to multi-page applications, where each view has its own HTML page, and clients navigate between views by requesting a different page from the server.
PWAs are web applications that have three features: they use HTTPS, have a manifest file that makes them "installable" in a client, and leverage the service workers APIs in the browser to cache data and provide an offline-enabled experience to your users.
All of these three kinds of apps (single- and multi-page apps and PWAs) can be built with the JAMstack, as long as they fit the definition. That means having the requirements of being built with JavaScript (J), interacting with reusable APIs (A), and using pre-rendered markup (M). In other words, they're JAMstack apps if they can be exported as static files and don't require server-side generation.
Important note
The demo app we're building is a SPA. However, you can use Svelte 3 to build any kind of app, including multi-page apps and PWAs.
Additionally, Svelte 3 can be used to pre-render content in a server-side application, so it could be used to build non-JAMstack apps. We will not cover such an advanced scenario in this book.