However, you picked up this book because you've heard of Svelte, and you've heard of it's growing in popularity. You've probably also heard that Svelte is different, and that there's something magical about it. I'm using the word magical on purpose: in fact, the original tagline for the Svelte project was "the magical disappearing UI framework."
You can use Svelte to build single, reusable components for projects of any kind, including larger applications written with Angular, React, Vue, or any other frameworks. Or, you can build entire web applications with it – just like we'll be doing in this book.
Throughout this book, I'll help you build your first, fully functional project with Svelte 3: a journaling app. We'll go from bootstrapping the development environment all the way to production with an automated continuous integration and delivery pipeline.
While building this sample app, we'll cover the majority of the features of Svelte 3. By the end, you should have a strong foundation to go and create your own apps with Svelte.
In this chapter, we'll cover the following topics:
- Modern web app development
- Why you should use Svelte
- Details on the app we'll be building
Modern web app development
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.
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.
XMLHttpRequest API, which existed in Internet Explorer as an ActiveX object and was later implemented by other browsers in a compatible way too.
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.
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
One of the most relevant to us in this book is the so-called JAMstack, an acronym of the following:
- (Reusable) APIs
- (Pre-rendered) Markup
Inside the JAMstack
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).
Benefits of JAMstack applications
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.
- 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.
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
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.
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.
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.
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
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.
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.
Svelte versus the other frameworks
Thanks to being pre-compiled, Svelte apps have a minimal overhead, both in terms of bundled code size and performance. Smaller bundles make your pages load faster, especially for users with slower internet connections. Additionally, by performing the bulk of the work in the compilation stage, Svelte does not need to include techniques such as the virtual DOM used by React and Vue: state changes in Svelte apps are reflected directly in the DOM, without extra overhead.
In a sense, Svelte is a response to the explosion of the size of web pages. According to the HTTP Archive reports (https://www.httparchive.org/reports/state-of-the-web?start=2015_03_01&end=latest&view=list), the median size of a web page was 1,280 KB in 2015, and that has grown to 2,080 KB in 2020. Large web pages take longer to load, increasing the likelihood of users leaving your site. But they also disproportionally impact users in rural areas, where internet bandwidth is more limited.
The Svelte project
Compared with the likes of Angular and React, Svelte is a relatively recent framework. It was originally created in 2016 by Rich Harris (https://github.com/Rich-Harris), a software developer and visual journalist.
The release of version 3 in April 2019 marked an important moment for Svelte (this is still the most recent branch as of the time of writing), as it was a complete rewrite that introduced a new, simpler syntax for writing Svelte components. With Svelte's third release also came a real uptick in the adoption of the framework.
Today, Svelte is maintained by an active community that is organized around the project's GitHub repository, and builds new releases with bug fixes and new features regularly.
It is also used by hundreds of organizations around the world, including The New York Times (where Harris is employed), 1Password, Rakuten, Philips, and GoDaddy. A list of users is maintained on the project's website.
- 88% satisfaction among developers; that makes Svelte the second most popular framework behind React (with 89% satisfaction).
- Svelte ranked first among developers' interest, at 67%.
- Nevertheless, a fifth of Svelte users reported working in a company with over 1,000 employees (the same as React), indicating how the framework has gained momentum in more mature organizations too.
Building a journaling app
- The starter view is a list of all the journal entries for a given day; a date picker lets users select the day.
- Users can add new content using a form that lets them type it in freely.
- Content is presented to users when they select a journal entry, rendering the input text as Markdown.
The app requires authentication before users can read or write any journal entries, and it uses OAuth 2.0/OpenID Connect to achieve that.
Data is stored inside a back-end service, which runs separately from our application (remember that we're building a JAMstack app!), and our front-end communicates with the back-end service via RESTful APIs.
While this proof-of-concept app has simplified, limited functionality, it does help us learn all the core capabilities of Svelte 3 (and a few other things too). The concepts we'll be exploring are applicable both to internal, line-of-business applications, as well as external-facing ones.
The back-end service
In order to keep this book focused on front-end development using Svelte 3, we'll be using a pre-built back-end service that provides persistent storage for the data, as well as identity and access control.
To make your life simple and to let you focus on the front-end, I've built a small service that provides the required endpoints. This is written in Go and is available on GitHub at
PacktPublishing/Svelte-3-Up-and-Running or https://bit.ly/sveltebook. You can download the pre-compiled binary for Windows, macOS, and Linux, and launch it on your laptop (usually by double-clicking on the executable) to instantly have the required APIs available for your front-end app to interact with.
Besides being a cheap workaround to the complexity of requiring you to build a back-end, this approach reflects the way modern web applications are built. As the developer working on the front-end portion of your app, you will need to interact with a service using predefined APIs that are maintained by a different team.
You might not have knowledge of how the back-end service works (and, truthfully, you might not want to either), and the service might be written in a completely different stack, just like this back-end app is written in Go. As we saw in the previous sections, in fact, many JAMstack applications interact with services that are maintained by completely different organizations within the company, or even different companies.
The source code for the back-end service, written in Go, is available on GitHub for you to look at and modify as you please.
The service includes common RESTful endpoints to store, retrieve, and search objects (journal entries).
It also features a mock OAuth 2.0/OpenID Connect implementation to provide identity services. This was built from scratch, but it includes just the bare minimum features to support the needs of the sample front-end application.
While the back-end service is functional, because its purpose is just to aid the development of the front-end application in this book, it is full of sub-optimal practices. In short, do not use this app or any of its code in production as is. This is especially key for the access management part, which is likely unsafe for any real-world applications; instead, you should rely on your organization's directory or, if building a consumer-facing app, on trustworthy identity service providers.
In this first chapter, we learned about the Svelte 3 framework and what makes it magical compared to other alternatives for front-end development.
We also did a retrospection on modern web app development, looking at concepts such as JAMstack apps and their benefits to developers and end users.
Lastly, we looked at a description of the application we'll be building throughout this book, which is a journaling app running entirely within the web browser and developed with the Svelte 3 framework.
In the next chapter, we'll start getting our hands dirty and begin building the sample app. We'll begin by setting up all the required tools and scaffolding for our project. At the end, we'll be ready to run a "hello world" app with Svelte 3.