PWA Studio Best Practices for Beginners
This session is a beginner-friendly introduction to what PWA Studio has to offer.
Learn about the different PWA Studio libraries and how you can use them effectively in your storefront projects.
Join us for examples and demonstrations to see just how easy it is getting started and working with PWA Studio.
Transcript
Hello, and welcome to PWA Studio 101. I’m Andy Terranova. Presenting alongside me is James Kalkoban. This session will be moderated by Emma Lockwood. You can find her in the chat pod there on the right-hand side of your screen. We have a packed agenda today. I’ll start with an introduction to PWAs, PWA Studio, and Venya. And then James will go into how to create your own projects and some best practices for your storefronts. Finally, we’ll leave some time at the end there for questions and answers. There’s a Q&A pod next to the chat pod on the right-hand side. You can queue up your questions there. All right, let’s jump right in. What is a PWA? You probably already know that the acronym stands for Progressive Web Application, but what does that actually mean? Well, the best way to answer that question is to rewind to a world without PWAs. And I know that some of you might still be in that world. So imagine you’re developing a product and you have to decide whether you want a mobile app or a website. You don’t have enough resources for both. So which do you choose? Well, mobile apps have some advantages. They have a home screen presence. Your application is right there in front of users for easy access. They have push notifications and app badges for re-engagement, snappy UIs, GPS, offline mode, accelerometers, and more. You could add to this list from your own experience, I’m sure too. But then on the flip side, websites have some advantages. They’re cross-platform for a wider reach. You’re not limited to a single device’s user base. You can develop using a single code base. You don’t have to have an iOS website and an Android website, right? You can deliver real-time updates. You don’t have to get your update approved by the Apple store, the Google Play store before it goes live. And then linkability, the cornerstone of the web, really. Anyone in the world can share your product directly with other people. A PWA then is a set of best practices that aims to combine the best of those native and web application worlds so that you don’t have to choose between them. And this actually isn’t even a new idea. When I started JavaScript development in 2014, we were attempting to solve this with what was called a hybrid web application. We had a website and we wanted to get it literally in the hands of our users, like on their devices. So we created an iOS app and an Android app, and at the time even a Windows phone app. But the only thing those apps did really was load in our website. So we got a little bit of both worlds, I guess, but not really. Adobe itself was actually a player in the hybrid web application space with the popular PhoneGap and its open source version Apache Cordova. And there’s lots of other prior art here as well. I’ve kind of highlighted Adobe Air applications. And then more recently, Electron is kind of in the same vein. So if that was 2014, fast forward to 2015, and we see the first mention of PWAs or progressive web apps from Alex Russell and Francis Behrman of Google. Quote, these apps aren’t packaged and deployed through stores. They’re just websites that took all the right vitamins. They progressively become apps. Pretty cool, right? So let’s take a little bit of a deeper look. What are all the right vitamins? Well, we have some guiding principles in the form of the three pillars of PWAs. They have to be capable, reliable, and installable. So let’s take a look at those one by one. Capable. Here we’re talking about functionality. Can this web app do all the things that a native mobile app could do? In 2021, we now have modern web APIs like real time communication, geolocation, push notifications, even WebGL and WebVR. We have new and upcoming APIs like file system access, app badging, full clipboard support, and even WebAssembly, which allows us the ability to run high performance applications on the web is relevant here. The second pillar is reliability. Here we’re talking about things like dependability, speed, performance, and offline support. And these things are progressively enhanced by what is called a service worker. And I won’t get into service workers too deeply here. Just know that it’s a special script that the browser runs in the background. You can do things like intercept network requests, serve things from the cache, and provide that offline support easily. And then finally, the third pillar, installability. This one’s pretty straightforward, but it enables our app to do things like launch from a home screen, dock or taskbar, and run in a standalone window. Users can search for it using a device native search like spotlight search on Mac and switch to it using a device native app switcher like Alt tab on Windows. Long story short, your PWA behaves just as if it were any other app or program on a user system. Lastly, here’s another kind of popular list of vitamins you may encounter when doing PWA research. But all of these can be traced back to one of the three pillars we just discussed. So importantly, a PWA is not a framework or a technology. It’s a set of best practices to reach that goal of combining the best of both native and web. So websites that do all of these things well, that take all the right vitamins, progressively become apps. Okay. So now that we know what a PWA is, let’s talk about PWA Studio. PWA Studio is a set of developer tools that help you create, optimize, and then deploy PWA storefronts. And we have tools for every part of the stack actually. For your Magento 2 backend, we maintain the Magento 2 upward connector, which replaces the default Magento front end theme with a PWA storefront instead. We’ve just recently created a core meta package that allows us to add functionality outside of the quarterly core releases. And we also maintain a set of sample catalog data for an imaginary fashion brand called Venia, which we’ll get into more here in a bit. Next, we aim to make project creation and maintenance easy. We publish a project scaffolding tool that allows you to create a new PWA storefront by following a series of interactive prompts. We maintain a package called Build Pack that contains CLI tools that help with configuration management and extensibility. And we have a handful of utility packages like the one I’ve highlighted here, validate queries. And this is a utility that checks your client side GraphQL operations at build time. So you can fix any errors before going live. Your users will never encounter an error message or anything like that. We also publish tools to help you actually assemble your storefront applications. Of course, we have Venia UI and page builder that provide visual components and Peregrine, which you can basically think of as the e-commerce business layer. All the logic lives there. We’ve just recently introduced a package to enable theming. And then lastly, we provide that service worker that I mentioned earlier. So if PWA Studio is a set of tools to build PWAs, Venia then is our demo storefront built using those tools. So it provides a set of both UX and code best practices. And it also provides a ready to use storefront out of the box. So you can literally point Venia to your catalog and go live. You probably wouldn’t want to do that. You probably want to change up some branding beforehand, but you could do that. Okay. So I briefly mentioned the project scaffolding tool earlier. Now I’d like to hand it off to James for a closer look. Cool. Thanks Andy. Let me share my screen. All right. So the first thing you’ll want to do when you begin working with PWA Studio is create a new project. And the best way to do that is to use our scaffolding tool. So just like in construction, our scaffolding tool provides a base project for you to start building your storefront application. It’s also the tool we recommend you use when starting a new project. And all you have to do to run the tool is enter that command into your terminal. And so here’s a demo of our scaffolding tool in action. And it’ll show you just how easy it is to get started. If you’re familiar with React development, this command is similar to the create React app command line tool. It provides an interactive questionnaire to help you set up your project and then it generates your project files. Here we sped up the video while it downloads the dependencies, but in real time this whole process takes about two minutes from start to finish, which is pretty quick. And at the end here, you’ll see additional commands to help you set up the rest of your development environment. So what does the new storefront project look like? Well, these are the files you get after you run the scaffolding tool. It’s actually a working and fully deployable storefront. Some of the more important files I’d like to point out are the index.js file. This is the main entry point for your application. You see the service worker directory there. We talked about that. That’s where you’ll find the code for your service worker and how you can configure it. There’s a .env file. It’s where you set up the local environment variables such as the backend URL for your Magento or Adobe Commerce instance or your Braintree API token. There’s also the local intercept.js file and that’s where you can interact with our extensibility framework. We’ll talk about that in a later section. But if you want more information about the structure of your new project, we recommend visiting our doc site, pwa-studio.io and just search for project structure. So you’re probably wondering, why should I scaffold my project? Can I just clone the PWA repository and set up my project that way? And the answer is yes. And we have had early adopters that did just that. However, you may run into some issues with this setup that you wouldn’t normally have with a scaffolding project. So what happens when you clone our GitHub project is that you’re essentially taking ownership of this large monorepo code base. And so when it comes time to upgrade to a newer version, you’d be responsible for applying those upstream changes and handling any merge conflicts that you would get when you modify the core code. And so with the scaffolding project, the PWA Studio library code is included as package dependencies. So what this means is that when it’s time to upgrade, you just bump up the version of these dependencies and install new packages. And also the small amount of files in the base project means that you don’t have to search through nested directories to find the file that you need to modify. You just have your code that is part of your project. So now that you have your new storefront project set up for development, how do you actually develop the different pieces of your storefront? Separate your concerns because we have some advice based on our own development strategies that you can apply to your own project. Our first advice is of course to apply the principle of the separation of concerns. And this is a design principle quote for separating computer program into distinct sections. What this means is that you’ll want to think of your storefront application as a series of layers. For example, in this image, you have in the front the presentation or UI layer. And behind that you have your business logic layer, which will be the brains of your application. And finally you have the data layer, which of course provides the data for your application. So when you’re creating a new storefront feature, you should separate your code into modules with limited responsibilities and a clear set of interfaces. Not only will this make your module smaller and easier to understand, it will also help when you need to create test form, which you should also be doing in your project. A good example of this principle in action is in our Venya UI and Peregrine libraries. Our Venya UI package is a library of UI components that you can use in your storefront project. These components define the structure of the application, which is composed of React elements that eventually get rendered into HTML. The kind of components the Venya UI package provides range from simple components like buttons and images, and they progressively get complex as they are composed of these simple components, things like the wishlist page and even the app component itself. On the other side, you have the Peregrine library. It provides the business logic, like we said, the brains of your storefront project. The modules this library provides are responsible for things such as data access, state management, and providing functions that respond to user or browser events. They both work together to create the application. So here’s a simple example of what that kind of code separation looks like. On the left, we have the business logic module. As you can see, it has code for managing the state, fetching data, and setting the value for a message for a UI component there on the right. You can see it renders a presentation code, which is HTML elements, and it uses, it imports and uses the values from that logic component. This pattern of providing a logic component for a specific UI component is common enough in our codebase that we have actually given it a specific name that we refer to in our documentation, and that’s Peregrine Talons or just Talons. If you’re familiar with React development, you’ll recognize Talons as just custom React hooks. The difference between Talons and normal React hooks is that Talons are built specifically for a certain UI component, whereas regular hooks are created with code reused in mind. But Talons, on the other hand, are only really useful for UI components of the same type. For example, the Talon for the product detail page UI component returns values and callbacks that are only really useful for that UI component. These two may be strongly associated with each other, but they’re still decoupled enough that you can reuse that Talon if you wanted to build a completely different-looking product detail page with the same logic. And the same is true on the flip side. You can swap out the Talon a UI component uses with one that returns the same object or the same object structure but different logic behind it. And our last advice for splitting your code is to use CSS modules, which is automatically enabled and available for you to use in new projects. And what this feature lets you do is import CSS files into your JavaScript code and treat them as objects with style properties. As you can see in the example on the right, we import the… You can see where we import the CSS file for the example component and then access the style entries as you would a JavaScript object. So when this component is rendered, these values are replaced with a unique ID that prevents global naming collisions. And if you ever work with CSS, this is a very common issue that happens. Also, just a quick mention, if you’re interested in learning about the future of CSS and theming in PWA Studio, be sure to check out the Adobe XD session with Jimmy. I think that’s tomorrow. Someone can correct me if I’m wrong. Yep, that’s tomorrow at 1.15 Eastern and I’ll pop that in the chat pod too. So if anyone’s interested, they can find that on the session page and register. Awesome. Thanks. So as we pointed out earlier, performance is an important feature for progressive web applications. And one of the best ways to get that is by caching your data whenever and wherever you can. There’s a lot of caching tools and services that you can use for the commerce backend. But since you’re working with a web application, you’ll be mostly working with the client-side cache, which stores your data in the browser or local memory. And you can work with this cache directly or you can use third-party libraries to help you store the data, retrieve it, and expire it. One of the caching services available to you, we’ve talked about, is the Service Worker. And what the Service Worker is basically, it’s a service that sits between your application and the network. It’s also a key component for a lot of PWA features like offline mode. It can intercept and modify resource requests, but more importantly, it can also cache data and use them even when you’re offline. So out of the box, we’ve seen in the project structure, every new storefront project comes with a basic Service Worker configuration, which you can find in all new projects. And it’s in this folder. You can add modifications to fine-tune the performance of your site or add other PWA features such as system and push notifications and background sync. Another caching layer you should consider using is the Apollo Client Cache. Apollo Client is the name of the library used to handle our GraphQL requests. And one of the features it happens to have is caching. And by caching the data you get from your requests, you can actually avoid unnecessary network calls for that same data. And to use this feature, you just need to specify the fetch policy in your GraphQL requests, just like you see there in the code sample. If we take a closer look, we see that it’s telling the Apollo Client to execute this query against both the cache and the network on the first request, and then every request after that, look in the cache first to avoid unnecessary network calls. The Apollo Client supports a number of fetch policy that we’ve listed here, and you can use any of these to optimize your GraphQL requests. I highly recommend checking out the Apollo Client documentation for more tips on using this library. In this next section, we’re going to talk about I18n for L10n, or in actual words, internationalization or localization. And if you’re wondering why these terms have numbers, they refer to the number of letters between the first and last letters. Okay, so let’s say your storefront currently only serves a single locale. It’s always a good idea to build your application so that it’s world-ready in case you need to expand to other territories or you can support another locale. And to help with this localization, PWA Studio provides an internationalization framework you can use in your project. It uses the popular React INTL library to provide localized text using a translation dictionary. In your components, you can use the format message function or formatted message component to render the correct text for a specific locale. Here in the code sample, it shows the format message function being used to make the wishlist button text translatable by passing in an object with an ID and a default message in case there’s no translation dictionary entry. Okay, so we mentioned translation dictionaries, but what are they? Translation dictionaries are what provide the translated text to the framework. And these are just JSON files created in a specific directory either in your project or as part of a translation plugin that you install in your project. And as you can see on the right, the file is just, the file just contains key value pairs with the key being the ID we saw being referred to in the previous code sample and then the translated text. If your project needs to support multiple locales, you can create as many of these translation dictionaries in your project as you need. In this final section, we’re going to talk about PWA Studio’s extensibility framework. This is a pretty advanced feature which requires some technical experience to fully grasp. So, we’ll only be talking about it here at a high level since this is an introductory session. If you’re interested in learning more about this topic, we’re going to be holding a workshop for the hackathon. Is that right, Andy? Where we go more depth? Yeah, definitely on Wednesday, two days from now, there’ll be another presentation that gets a little more in depth. And then we’ll be hacking away for like four hours or so to make your own extensions. Cool. So, yeah, if you’re interested, check that out. Okay. So, you’ve got your project set up, you have some tips on how to create and optimize your code for new features. How do you actually apply these changes to the base Venya application? And the answer to that is using our extensibility framework. Before the extensibility framework was available, if a developer wanted to change something in Venya, they would have to copy over files from the core into their project and then apply those changes. As we mentioned earlier, the problem with this is that it made it difficult to keep these files up to date with every release. The extensibility framework addresses this issue by letting you apply your changes to the Venya source code without copying it locally. The diagram on the right here illustrates the interceptor pattern that the framework implements. However, this diagram actually provides a better idea of how extensibility works in PWA Studio. The sequence on the left shows how the base storefront can install a feature from package A and then build it into the static code bundles for the application to use. And the sequence on the right, you have a package B extending the functionality of package A by intercepting the targets that package A declares. And these are the files that are declaring and these are the instructions that tell PWA Studio what to do during the build phase. And it’s during this build phase that our extensibility framework modifies the code in package A before adding it to the static code bundles. And of course, the final result is a feature that’s provided by package A that’s been modified by package B, all while keeping their code base separate from each other. And targets, it’s one of the easiest ways to get started with extensibility framework is by using targets. They represent areas in the code that the developer has allowed you to change using a formal API. A good example would be the routes target and image into a UI package. This lets you define additional static routes for your application. And then accessing this is done through, as you mentioned, the local intercept file. And then you can see an example of this on the right. So what if there’s no target available that you need to make your customization? Well, that’s when you turn to targetables. And these work on a lower level than targets. Instead of representing specific areas in the code, targetables represent the actual source files in your project and in any of its dependencies. This means that you can make precise changes in the source code without taking ownership of the actual code. For example, the code sample on the right, before the extensibility framework, you had to copy a series of files, including main.js into your project to make this simple change. With targetables, you just create a targetable instance pointing to that file in the Magento Vigna UI package and call the function that lets you insert that code into a specific point in the file. And these are just a list of the types of targetables available from PWA Studio. And they just provide different APIs to make it easy to change the underlying code. And that is our presentation. Perfect. Thank you guys so much. I do have a couple of questions in the chat pod, so I’m going to try and cover those in our last couple of minutes with you guys. The first one comes from Nicholas. He says, how does PWA Studio interact with Magento’s PHP blocks? Do developers have to worry about module compatibility with PWA Studio? That is, in the same way, more integration work will have to be performed if your storefront uses a non-Luma theme, is it more work required to integrate modules with PWA Studio, or does it automatically handle the integration somehow? Yeah, so I’m not sure about PHP blocks specifically. I know there’s a GraphQL layer that PWA Studio sits on top of the talk to the Magento backend. So as long as the GraphQL surfaces that and we can query that information from GraphQL, yeah, you can pull it into PWA Studio easily. James, you might have a little more information about that, but I think it’s supported right now today. I just don’t want to give that assurance without actually 100% knowing the answer. Yeah, I think GraphQL would be your primary data source. And of course, extending the coverage would require PHP. I don’t know if that addresses that question as well. If you needed custom data that is not readily available, you would need to know a bit of PHP to surface that data through GraphQL. Yeah, and actually we’re doing that right now with some of our stuff. I mentioned the core meta package that we had to add because we wanted additional functionality outside of the quarterly core releases. So we had some PHP code, get it into GraphQL, and then also for us, build it right into Venya or we could package up another front end extension that queries that. Thanks guys. The next one comes to Makash. She says, hi, James and Andrew. Thanks for the informative presentation. Quick question. Do we have a use case of a PWA studio site, which is not a storefront? Is usage of Venya still possible if we don’t have a Magento use case? I don’t know that anyone’s ever asked that question before. That’s interesting. I guess it could be, I mean, a lot of this stuff is very tied to Magento and e-commerce. Like James mentioned, our create PWA is very similar to create React apps. So it’ll spit out a working app in the end. But yeah, a lot of the logic and kind of base stuff that’s in there is very tied to e-commerce. So I guess you could go in there and not use it. It would still work as an app. Yeah. I mean, technically it’s just a library that you can import into any project. And as long as you wire things certain or correctly a certain way, or you use some of the more primitive components, yeah, you could consume PWA studio libraries by themselves, a button that you perhaps liked in our library or a form. And like I said, the way we separate the code with Talents, you can swap out the underlying logic. Great. And there’s one more question. Well, there was two. One was the GitHub, which I posted in the chat. So check that one out. The cool. And then one from Ryan, do you think it makes learning curve more steady than vanilla React JS apps by introducing the unique features like Venio UI and Peregrine? The learning curve? Yeah. I mean, probably there’s a bit more to learn upfront just in terms of any UI and Peregrine. Like if you just had a simple create React app, you could get going on your own, but that will definitely simplify the learning curve for Magento. So you don’t have to know quite as much about Magento upfront. We kind of simplify a lot of those calls and data interactions and stuff like that. Try to give them friendly names and such so that you don’t have to know too much about it. Yeah. And we do our best to follow best practices and industry standards with our own source code that people can view and learn from. It’s one of the best resources is our open source project and our docs, which we try to maintain. Yeah. And I posted the link to that documentation site as well, which has always kept up to date with our latest documentation and information. Okay. Well, that’s all the time we have today. Thank you all for the engaging Q&A and thank you, James and Andy, for a great presentation. So that’ll be it for today. Thanks everyone. Thank you. Very cool. Thanks, y’all. Thanks, Emma. Bye.
Additional Resources
recommendation-more-help
3c5a5de1-aef4-4536-8764-ec20371a5186