 Hello and welcome to the Supercharged livestream. I'm Sorma and I'm Jake and today we're gonna do server side service workers See Paul couldn't make it into the office because the bridge train system So I thought we could have a whole episode entirely devoted to service What are you doing here? Well because because you were late I thought we could do this entire thing all about service workers. No. No, you keep doing this You keep trying to take over can we have one thing around here that is not about you and service workers? Okay, show our hands. Who wants this episode to be about service workers? fine Oh, well, that's that's rid of him then so sorry about my the tardiness on the show. I'm not front tail quick Yeah, so what we doing what we doing? We are actually going to do server side rendering and we're going to do it with you and not with Jake There was a lot of confusion on Twitter Was like a very enjoyable. Whoops. Yeah Anyway, but I didn't make it and that's fine. Um, I'm I'm not doing the coding today. You're doing the coding Yeah, it's a bit of a switch around. I'm gonna be on hand to answer questions and Talk to the folks and I can already see we've got lots of comments coming people already. Hello to everybody in the chat Thank you for joining us. We'd love to have you here So I do you know feel free to keep chatting away and well you can you can make Paul interrupt me So that I do more mistakes My goal for today is is try to do less typos than you do and I'm pretty sure I'm gonna fail I mean, although you do set the bar pretty high. Oh But this is my revenge. I mean, I mean, I'm gonna be very supportive throughout, right? So it's like rendering service at rendering. Okay. What are you doing? What are you doing? Service at running? Yeah, I should probably explain because of this word has been all of those three words two words If it was a hyphen just those words have been thrown around a lot And I feel like there's not a very consistent understanding of what it actually means and so I'm trying to gonna capture it in a few words So I was at rendering is what you want to do if you have a single page app If you think back to the first router that we did we actually used a little Python web server I think you wrote that whatever you requested you would get back the index HTML. So if you requested slash about or just home or slash Contact you would always get the same index HTML Which means in that site there wouldn't be the content that you actually wanted to read So you would have to wait for the JavaScript to spin up To analyze the path that has been requested and to swatch swap out the content in the DOM with the actual content And then we switched it up to the advanced router Which did actually have individual pages for like about contact Miss whatever it was and then and then we pulled those in But that would mean that whenever you change something in the layout that you would have to do the edits in all of these Individual pages, so presumably that's what we're trying to figure out today So what rendering basically still is always deliver the index HTML But already inject the content before serving it to the user So you render the DOM on the server side That is why it's called this way and send it to the user So the content is already there without the JavaScript meeting to run at all Yeah, and then hydration happens where the job spins up and takes care of all the dynamic parts Oh, let's get our hands ready and write some code I'm gonna start With something so we're gonna write note on the back end We're gonna write a note web server that does the server side rendering. So I'm gonna make this a script With copyright headers so that we can run JavaScript just with executing the script I thought for this so I have in the folder here I have an app folder where basically our advanced router code is in the thing that we wrote Two sessions ago, I think it's exactly the same. No, not much I think has been done and for this one I decided that I want to use express express is just a little bit of Convenience about notes native web server so that we have a simple web server and use it by creating an express app and This app object is what we're gonna do all the roots. Have you done an MPM install? Yeah, I have the modules in here with express and all the other things that I plan to be using I'll explain as I go along. Okay, actually using okay, so we want to start with something simple We're just gonna write a web server that is just a straight web server. That's nothing else So what we can do there is we want to say that our app uses middleware that is called static So what this line does is just says to to express just serve this folder the app folder as static content And then we're gonna use notes HTTP server Create server that serves our app and we make it listen on 8080 and you've got this all committed in your head Well node is that is what node excels at right? Very simple code that you can Bravo. I mean well done. It's very good. So let's do This who doesn't love a bit of chmodding chmodding like it's like the plus X that makes it executable, right? I did that line at the top. So it's it's actually a thing this hopefully you can't find module express. Well, that's good It's in there though, right? No, it's not. That's like the only model. I forgot to install So let's let's do some good old npm install because oh that means you have to do the install dance while we wait for it to go Because it's not that big I was only partway through that the install dance Yeah, it does have a very elaborate install dance fine. So we've got a question here Why not use import express from express? Why are you doing the old sort of require rather than anything newer? So the thing is that modules for me are still a little bit iffy. It's just something especially on the npm side It doesn't feel as right. I'm not even sure if node for which is what I'm you already Supports the import syntax. I'm not having so we would need a label in between. I don't know and also Imports are declarative and not imperative and sometimes you do want to have like I did here You do want to have the imperative way, okay? Like grab this thing and then do this thing with exactly so for now I'm just sticking to require until the entire javascript ecosystem starts out how to do modules It's just for me to keep keep me sane. Okay, so what's the start? It's actually working. There's no error at least That's good. So if you go to local host 18 there is okay. Oh, this is actually a little bit cramped Can you do the oh there we go I can feel the tension as you're trying to Don't do I get it right? Okay. Okay, so you've selected them all as well by accident. Yeah, it's good So I want to see the protocol as well. Are you that ruin it? Why don't you just make depth was a bit bigger do? Oh, I could it's be one point one. Yeah, okay. Oh There you go. Just oh, yeah, so We got this and Now what I wanted to do is you wanted to I wanted to port this to HP to because you know This is the future and we should do this but for that we need TLS certificates so because I forgot to download it I will go to Google Chrome Simple HP to server because not only is a simple HP to server, but it will also allow us to generate Certificates, so I'm just going to download the Darwin version Yeah, is that gonna go to you? Yeah, which should be here. There we go. And then we go download simple boom boom and now we have a Certificate which we can use and I'm gonna show you how exactly So we need a so what you just you basically So for anybody who's not seen this before you built a simple a bit like the Python simple server, but it's the it's in built and go and It adds it's an HTTP to server so it has to be running on HTTPS So you got a self-signed certificate that you've made that it makes on the fly for you Yeah, and then you're basically you're treating it wherever you run it from whichever folder you run it from It treat that is the folder that you're serving exactly Okay, so and I just used it for the ability to generate a certificate because using the okay Open SL command line tools is so painful It's the original motivation to write simple a to server to not have to do that Okay, so you're using for right you want the certificates and now you're gonna use them here exactly So what we do can do exactly is that we are going to use Require FS and do FS read file sync We're gonna do synchronous because I'm dirty like that and we're gonna use the key and the cert read file sync search dot PEM and Now what we should be able to do is just to turn over to HTTPS and Add the options parameter to our create server and now it should actually be HTTPS. So let's try that No error, that's good We can close this. Let's add this And we get this which is basically because it's a self-signed certificate Chrome is gonna say You know that it's not actually secured and it is it is secure in terms of encryption, but not authenticity Yes, we actually talking to the right server, but since you're a local host We have the option to say, you know, I know what I'm doing. Let's proceed Yeah, and as you can see we have HTTPS with the right flag because as I said, it's not authentic But it works. So now we're still serving on HTTP one. Yeah, right? Yes, because I just switched to it Yes, now ideally what I would like to do is using a to be to however Express currently doesn't work with the age of your model because the to MPM model is still very much in development What we can use however is the speedy module, huh, which interestingly enough does actually serve a to be to You just don't have the option to push. So it is a valid a to be to server and since you're not going to pushing today You said it's a restock. I can't just It's just gonna work like this Let's say Let's restart it just to make sure. Hmm. This is interesting Options it worked on TLS Let's let's just give a to be to a try just to make I'm not sure if I have it installed actually I Haven't installed apparently. Let's try it. Oh Something very strange is going on. It's already strange Mm-hmm. Why didn't try a different port entirely? Yeah, let's try a different port. Let's try 80 81. Let's restart that Go to here. Oh Interesting that is interesting All right, so the question is why do we not get HTTP to? So we are reading the certificate I Mean, there's not much code, but I could do something wrong No, no, there isn't I'm passing in the options. I'm passing in the app Hey, well, do you know what? I feel better that it's not just me. No, yeah, how's the boat? I expected I expected us to I am also in this right folder, right as far as I can see Yeah, they're speedy everything. I mean at the very least it should be speedy See what I did there. It should be speedy anyway Should be speedy. I'm just gonna skip over this for now. Okay. We'll come back. Yeah So let's stick with hd1 somebody suggesting it might be the caching, but I did I did do a heart refresh Yeah, I saw that. I saw you do that, too. Oh That's because I have Well, you do you go back to 8080? Oh That's because I still have the options in there Actually, that's let's say with hdbs just to make just to make life Let's start the server again Put the hdbs back in there It's just working. Let's stick with this. Yeah, so we start the browser. I like this people are basically saying switch it off I'm gonna give this a try and I like that people I mean We all like to do that. So I'm gonna restart the server. Yeah, I'm gonna kill this I'm gonna restart chrome open dev tools on The network tab and go to hdbs localhost 8081 No, it really doesn't like you. Okay Let's just keep it gone. So Right now what we're doing this should all be working We can go to our different website at our different subsections and it loads because we're just doing a static server Mm-hmm What we actually want to do though is we want to add special handling whenever an HTML file is requested Because this is where we do our server site rendering. Okay, so what we're gonna use is app.get saying whenever there's a get request for And now we're gonna use regular expressions I'm gonna try to make this understandable. Okay. So what we want to do is what do I do? I don't know because case and sensitive like case and sensitive. So I'm gonna be that person because I know it. Yeah Yeah, because that's you know, it's reading somebody else's regular expressions is it can be very painful Okay, and and this is probably not gonna be pretty also because I'm just talking about this. This is not production code It's not gonna end up being a production ready web server or production ready back end I'm not gonna pay a lot of attention to being to do any like IO optimizations or to do very efficient server site caching All these kind of things. This is mostly to show how to implement server site rendering It's about a technique not about a specific high performance implementation in this regard Yeah, although we're gonna have performance in mind because this is why we're doing this It's a super show. That's what we do. All right So let's think about this. When do we actually want to handle a request? That is either when the path that's being requested ends with a slash or With is the or for recognition If it has a slash Something that is not a slash with a slash at the end Is that right? Do you know so or index HTML, right? Wow, that's already tremendously readable. So So what we're going for here is so you could ask for like slash home Just slash slash home slash or slash home slash index. Okay, so that's what we're trying to capture So if you come up with any of those three, otherwise, we're gonna fall through to the static exactly So all the funds that are there are gonna be served just as as we know And This is why I love mode for because we have Function so what I'm gonna do for now is I'm just gonna check it is actually working and just send back a test string Hi Could have been on brown, but whatever. Okay, fine. Okay, so I'm gonna use super charged Hi Let's reach out the server. I hope no syntax error, which is good. So if we just go here Supercharged high. Okay. If you're gonna go to about Supercharged high if I go to about index HTML I and then presumably if we do like static What do we have for static? We have app. We have static app. J. S. Okay So this should now fall through to okay So that's the static hosting that we had before okay Also, I wanted to show the middleware of the static middle express is really nice because in the response They take care of doing sensible defaults like default cache control default adding an e-tag Doing the last modified. Okay. So let's talk about this very briefly because I know this is this is a bit of a Kind of a hidden gem. I suppose like when you understand about these headers Life can be a lot more straightforward. I have seen people for example Using a service worker and then trying to like cash bust and do all these things because the the headers are fundamentally They're fighting with their headers Right, which sometimes is okay because for example and get up pages You don't have any control over the headers that they use so you might have to resort to these things But usually if you have any control over your back end, which for example on is three hosting you do Fix your headers. Yes, because caching is part of HBG and the entire ecosystem. So good caching headers are worth so much So at least give yourself proper e-tags So that caching works for your clients and you reduce bandwidth that they use on the website So somebody's basically saying here the the e-tags. They've never really understood what the point is okay So why don't we take a moment explain? E-tags are pretty great. Basically what they mean is that When you receive a document from a server it gets an e-tag and that e-tag is a guarantee that it is Will only change if the contents of the files have changed Which is why most server implementations use some kind of checksum like sha one or sha two predicts MD5 whatever you generate these e-tags What the client can then do put it these files into its cache And when the user goes back and requests the same file somewhere in the future It can put an if if non-match header in the request and add the e-tag So the server knows which version the user has available locally and if the server sees hey I have the same version here that the user already has the server respond with a 304 Meaning not modified and you save the user redownloading the entire contents. Okay, and what this is actually kind of it There's also weak e-tags, which is you fire lighted. This is when it begins with a w slash. Does that sound that sounds for a weak e-tag? Okay, which is defined as The e-tag only changes if the semantics of the documents change But they're not necessarily bite equivalent What does that even mean exactly and this file I have never encountered them in the wild But you're saying that Express uses them by default, but it's still does bite different e-tags. I guess so what it means basically is They only have an effect if you're not doing range requests Okay, because they're not bite equivalent necessarily you can't do range requests or use a part of it for a cache But as long as it's the whole document you can use the one you have if the e-tags are equivalent I wouldn't worry about it too much. We're gonna cover our own e-tags later. Ooh, I think how exciting exciting indeed So we are now in control of delivering our own HML files So that's Before you go any further if you've just joined us. We are doing some server-side rendering today We are taking the advanced router that we did a few episodes ago And instead of kind of having a completely static Set up for the HTML files. We're actually building them on the fly in the server Serma has got some JavaScript code up and running, which is just at the moment turning out some HTTPS Basically, and we have somebody remarked that you have managed to create a regular expression that worked the first time around Which is impressive and I would agree I watch that I was like, I mean that's unintelligible I grant you that it really is look at that in a few weeks and that you'll be absolutely terrified But all the same well done. So we basically we've got this situation now where if we have a Requested slash slash section slash as in slash home slash or slash home slash index that HTML We will serve via this chunk of code in the middle and then everything else is going to fall through to our static hosting Exactly because that also they express the the order in which you declare your handlers or the steps is Important because express goes to the through them from top to bottom. Okay. All right So now we have a handler that we have to implement and the reason I did this is because let's look at our index HTML The original one which you might remember or you might not The thing is that between this index HTML the index HTML in slash about the one in slash contact They're all pretty much the same except in the as the SC view elements that we wrote The actual for example on this one home has contents while the other ones are declared as remote because we We are not on the page right now, but everything above and below is the same for all pages So let's split those apart and this is exactly what I'm going to do. So this one is What I'm going to call the header Let's expand this so people can see where I'm actually going Server site rendering app and this is going to be the header header dot partial dot HTML and Let's go to the rest and call this The Come on don't always throw me out of the folder. There we go the footer dot partial dot HTML So now we have split the file in header and footer and the actual index HTML will not contain much more then this and I will add something here, which I will explain later All right, so the actual index HTML which just has the content is relevant for this page It's just one line in this case because it's just one element. I already prepared this for the other sub pages So the about index HTML also has just one line Same for contact just the content for that actual subsection and the rest has been split apart in header in footer And what we're going to do now is we're basically going to assemble the header the actual content and the footer in our handler and I'm going to go to Introduce something new which is we have been using the node file system model to read files but the thing is that Node currently and they said they won't do this anytime soon in the future. They don't use promises and Reading multiple files with a callback based API Makes my head explode and that's why there's a module called modernize or mz, which has wrappers around all these Basic APIs from node and turns them into promised based APIs. So what we can do now basically is we can do promise Okay, so you're doing three requests and one for the header exactly so I'm going to do app Header partial HTML. I'm going to do really depressing. You're not making typos. Oh Fine carry on app and now we're going to need something here Which we're going to talk about in a second which is index HTML the actual content of the section we want to load and We're going to read the app See at a typo. Yeah, I think it's just a pity typo, wasn't it? So we have to sort out what we're actually loading and this is where the regex comes in because I have put parentheses about the thing that will be the section that we want to load and Express being a nice guy. We can actually go and say the item that we want to load is I Think it's this let's let's check this Ah Let's just send back our item So what I did here is I'm true. I think it is params on the request of you get contains the parenthesized parts of a regex. I'm just gonna send it back to see if it actually works So let's restart the server Let's split our screen into where is my chrome? There we go This is a little bit too small So if I go here We shouldn't see much, but if I go here Yeah, we have about Like a lot of contact. We have contact exactly what we want. So we have one question that's come in Is the routing that we have here? Yeah, effectively is It's different to the front-end code that we had only And today we are we gonna cover off? Using the same routing or we completely avoiding that no cool The code that you wrote in the route advance will was a disaster No, that's what you said It's mostly gonna remain untouched. We're gonna do a little bit of treating later. Maybe if we get to it I have an idea that I want to try out But for now, we're just gonna do the delivery part I mean if we get this done it might be interesting to talk about Writing JavaScript works in the front-end in the back-end and maybe even in the service worker Which is the trisomorphic JavaScript, which is a great buzzword that people came up with But that's for the future for now. Let's start rice and that's that must be service side client side and service worker based Routing yes, which you know eventually maybe terrific So we figured out what our item is so we can just put this in this great template expression so I'll just put item here and What we're gonna do next is we now have an array of Files so in case you don't know read file returns buffer objects. We don't want buffers We want strings so what we're gonna do is we're gonna map over all our files and Say to string and say this is you to have it encoded and now we have an array of strings And an array of buffers. Oh easy. It is so easy and what we're gonna do I Don't call me out on any honor. Yes. We have an area of strings. So now we can do response Send files join Like this and because we're good. We're also gonna catch our errors So if any any of these fails because for example, if any of these files don't exist The promise dot all will not resolve but reject and now we can handle that in the catch part of our promise chain and say our response should have a status of 500 for now and send the error to string Okay, so we're actually doing error handling which usually in one off code doesn't happen No, it's pretty cool. So it doesn't in mine as we may have noticed. So let's restart our web server and Let's do curl because we haven't done curl yet. Actually You know what let's do curl we're gonna use dash k dash i so we want to get to see the headers But we're also gonna use dash k that means ignore certificate errors because as remember We're still serving over TLS with a self-signed certificate and curl is gonna reject unless we give it dash k as an option Do some of you know that stuff off by heart as well. I've done so much curl that I actually know these two Way server error That's undefined. Oh, why is it undefined? That's not nice Item items the prom zero because if it's undefined, we're gonna use just an empty string. Okay, the easy fix, right? Let's restart the server do another curl. There we go So we have Reassembled the entire file because you can see the header and the footer However, if you take a closer look you will see that we have five sd views because our header has all the remote views And then we basically reiterate the home view with the actual content Which you know it pro I don't even know if your code handles this so you know don't do it don't do it I want to see it break that's gonna break. Let me open the console for for more fun in in the error department. Oh, thanks pal It's just broken. It's just nice. There's not even error. It's just broken. It just it just yeah Let's look at the code, but it should be yet. So as you can see here, I can I should zoom in zoom in a little bit We have five sd views, which is not what we want. So let's fix that And and one typical thing or one easy way to fix it is to turn our partials Into templates that we can use with a template engine Oh nice and my template engine of choice in this regard is because I know it pretty well is handlebars. Okay Yeah, it's pretty common. So what I'm gonna do is I'm gonna require in handlebars Handlebars require handlebars So go a question here. Yeah, is it normal to end up with rooting in three places or is that a no-no? Um Currently I would say it is pretty normal. I'm assuming that something like trisomorphic at least Isomorphic you can use in the front end and your service worker is gonna become a pretty common practice So this is I think there's a distinction here between just having the rooting all together Yeah, so when you do progressive enhancement, you're gonna build Rooting on the server side like this any way, right? Yeah, just gonna go because they have APIs and content delivery All these kind of things in your app right and then you are probably gonna progressively enhance into some rooting on the client Anyway, and then if you progressively enhance to have a service worker You're gonna have rooting in there something at least you and you might do a pass-through actually just kind of going well You know unless you're building streams on the fly in the service worker, for example, which is don't say that He will come back in the room if I say streams too loudly. That's Jake by the way safe I think so far some proof wall, okay Anyway, okay, so it's probably pretty normal And whether it's actually the same code the isomorphic trisomorphic thing So personally, I'm on a bigger believer in trisomorphic because even though I'm writing note right now That is not the only language you can use on the back end. There's like go Python PHP come on. Yeah, there's a way there's Java There's several pages that is and you can't share JavaScript code with a PHP back end unless you're doing really weird things and technically There's still CGI bin that that is yes, please don't okay, so I interrupted you I just imported required handlebars and now what I'm basically just gonna do is I'm gonna take all my files and For each file, I'm gonna say handlebars Compile this as a template and execute it with a request as the context So that means that inside our header content and footer We have access to everything in the request object, but since we have item. I'm just gonna add Item as a new object to our request so that we have this inside our context So I'm turning all the files into strings compiling them with handlebars executing them and then reassembling the website what we're gonna do now is We are gonna I would like to use handlebars if but the problem is that handlebars if only Checks for truthy or falsely values. It doesn't actually evaluate expressions What I would like to do is if if item is Equal to home Then I would like to skip this but this doesn't this is not actually in this case It would be empty because home is a default But handlebars can do this so that I'm gonna write my own helper, which means if not equal That doesn't exist yet. We're gonna write it. Okay, so let's if not equal So we have one of these for every single section exactly. So we're gonna see if this is for about If you're just joining us Serma and I are doing some server-side rendering today We are taking the advanced router from the previous episodes and we are basically making it rather having a bunch of static files We're now actually putting in some JavaScript to generate these files on the fly And we are in the middle of that process You're currently basically making our templates and making the HTML sort of dynamic so that it can be Built on the fly by the JavaScript that we have Thank you very much. I am actually here for the duration and of course you can join us You can ask your questions and there are some some brilliant remarks already coming in I Fortunately Jake is still shouting service worker every other You can't hear what it's them is. Well, I hear it. I mean I read it and I hear it and that's it's a big problem All the same do fire in your questions and your comments and we'll carry on on this end So you've got handlebars. You're making these dynamics. So now we we just you So we just used if not equal even though it doesn't exist. So let's better make it this so there's a register helper call if not exist and this is where handlebars turns into black magic because it just gives you as many parameters as The helper takes and a magic options element at the end What we're going to do here is we're going to check if a is not equal to be We are gonna Options function this now. This is just something I have to admit. I memorized this because What What this does is the options object contains the function that will generate the string that is in between our moustache braces in the markup code and This is just the context so that we passed an original. So in this case, it's going to be the request object Basically what we're doing is we're only going to render the things in between our if not equals blocks if A does not equal be which is what we wanted to say with if not equal So Fingers crossed if this actually works or not. I'm gonna restart my server. I'm gonna expect syntax errors There aren't any. Oh, yeah, big show Yeah, so let's restart this it's actually big isn't it looks it looks like it's actually correct You concentrate to the context section. We can click again. It is good. Let's look at the code and as you can see we only have Four SC views and the one that is actually live is missing from the remote ones Okay, wow so we achieved our goal of only rendering certain parts depending on what page we are currently on So that means we basically just is she achieved our server-side rendering We are injecting the content that is actually requested before any JavaScript on the client-side runs and yet We're more or less just delivering the same page over and over our header and our footer so what would you do in terms of Say caching this because if you build these pages all the time What would you actually do to say for example not have to rebuild these every for every individual visit? Let's do that. Let's let's build good caching headers. So we're gonna Before we sent the file We just assembled our content so this this content variable holds the actual bytes We are about to send down to the client what we could do is we could use these contents to actually Calculate a hash value of the contents and use that as an e-tag. Yeah, so let's do that luckily Node has crypto. Hey, you know in the last episode I asked you what the the German was for For CSS. Yeah, what would what would be an appropriate? Is there an is there an appropriate kind of German term for server-side rendering? Yeah, so that rendering I guess could be called The visa to go for lagnos fuel, which is exactly what we're doing right now And in case you're German, you know exactly what I just said that's and I've again like always I've got no chance of either Remembering or pronouncing it correctly, but it just sounds so cool Well, I'm still gonna call it server-side rendering. Yeah, I want to have more German Let us know and I'll make sure it happens So we have the contents and what we're going to know is we're going to calculate a hash and the hash is going to be crypto a Create hash maybe actually let's let's lose note and say crypto is require crypto and then crypto Create hash tag completion for the win. Okay, and we're going to use chart 256 because that is decently good do some indentation We're gonna append content It's called update because you can incrementally add data to a hash and have it hash it over time if you just have segments That's why the function was called Update which I find a little bit confusing and then in the end we want to have a digest as a hex value So that basically gives us a string that encodes the hash value with a hex format And what we can do now since we have the hash We can go here and say Respond set that is the call that sets the headers of our response We can just give it a dictionary and In this dictionary we can say for one we want to set the e-tag Which is our hash and because while we're at it. We can also set a proper cache control Public No cash and this is something I wanted to talk about because cash control is such a complex beast I've been trying to wrap my head around it and there's so many facets to this entire thing It has it can do so much that I just memorized basically two things that I'm ever going to use cash control It can do like private caches intermediate property control over everything But most of the time you just want public no cash and it sounds wrong, but it's not So something I used before when I did know what I was doing was Must Revalidate because that sounds right to me, right? So you're saying is that this should go out? It should try and get it from the server again Before you know before any exactly so I want the client to send a request of the server using the Cache checkers like if non-match or if modified since to see it should always revalidate the server if the cached version is still Fresh so up to date. Okay, however Must revalidate doesn't do that because what must be valid actually means is once the resource expires It should be revalidated. So what you would actually have to write it right is max H zero meaning it expires immediately after reception It should always be valid and as it turns out Max H zero and must revalidate There's a short version which is called no cash. So even though it says no So even though it says no cash caching is actually still happening, but with a validation round truth, okay So we've got a question from somebody basically asking Whether the code will be visible somewhere after the session and of course as always we're gonna put it onto our github repository We're gonna link it up in the video description. I guess yeah It's on our Google Chrome or can get up and everything's gonna be in there. Yes always has been with all of the other Yeah, it goes narrow kind of umbrella It's github.com Google Chrome slash UI element UI dash element dash samples. We will link it You can find it Based off previous episodes of it's always in the description for that and this code will go up there Bit of a funny name UI elements samples. This isn't really UI work today, but I hope you'll differently and they evolved So your no cash was basically there to do them the max age zero must revalidate exactly which is down to no cash It's a kind of a shorthand version. Exactly. It's just a shorthand really brilliant. So let's see if I did this, right? I'm gonna kill the server restart it Still no no error, which is Eerie, I don't trust it. Yeah Let's use curl and actually I'm gonna use capital I which means only show me the headers Okay, I don't care about the content right now and Actually, let's start with static fjs, which is a file as we tested before that is delivered by the middleware So we should have the somewhat weird weak e-tag Which we do sure enough we do and now let's request something that is delivered by our own function And we should have a really long e-tag a shout to five six hash Which we do so that we also get your public no cash there as well. Exactly. So that means that Assembling our the header the content and the footer we will Recalculate this hash every time and the user will only Redound it if they don't don't have it cached already. Perfect, which is really nice So now we have caching Ideally probably we would write a little bit more complex code to not Recalculate the hash value every time but these are the kind of things and I say this is a production code This is more about right and you probably you know consider a CDN and other kind of intermediate caches And so forth to make sure that you know things only hit your server when they absolutely have to but for the purposes of today We're showing and this does come up on the chat. Sometimes we aren't always going to jump to a final solution That maybe something a prefabricated one and the reason is not because we don't like them often They do a very very good job, but it's this is our opportunity to kind of show The underpinnings if you like the kind of engine the essentials the the engine inside so that we're it's about their principles More than the code So I think we're both kind of the opinion that if you have to know The basis that certain frameworks are built upon to be able to fix them They don't do what you want for once which usually if you use frameworks You will have run into the problem that something is not doing the same thing You would like it to do maybe you go somewhere and they say you know what we all we do is write Python And you think I don't know I'm used to writing in JavaScript in node What do I do? Well, if you know the kinds of things the kind of headers you should be setting the kind of ways you might be It's more a case of plugging things together rather than anything else. So that's kind of it's what you do versus how you do it There you go, right quote me on this All right, so technically We just got server-side rendering, which is really really cool. So if we go here, they should all be working As it is before and we're actually assembling these pages on the fly however something that Might be a little little weird Let me kind of disable cash Let's just I like cash because I see that we get to be a force which is not modified which is good, right? That's what we want exactly we want it But in this case, I wanted to point out that if we don't have caching enabled that if the site downloads contact It actually downloads the entire site even though again header and footer Are pretty much the same, right? And if you look at the only kind we actually need from contact is this single line So we're actually pretty being pretty wasteful Download when the user switches to another tab so the little bit more context here, I think is that What in the JavaScript code we actually we download the full document? Don't we let's look at the header So yeah, we basically would say the root is This one Oh, no actually when we go to about The sd view requests this website from the server the entire thing and puts it Into the dome pulls out the part it needs and switches out the but it takes the app But it downloads the whole document and then query selects it out only that little bit So you're saying what we should be doing is just just send down that little bit Yeah, okay, since we're going to throw away the rest anyway go go go go on the server side do it do it do it Look at our index HTML Text in our at our well index HTML root, I guess we could do something really sneaky what we could do is We could So add support for a query parameter. Okay, so right now if we do Something like this you will get the entire site Oh We'll get the entire site What would be nice is that if we add something like partial that we only get the bits that are actually relevant for our server side for our client side JavaScript So what I'm going to do is I'm going to check if partial is in the request query dictionary and Now at logic so as you can see here We have a lot of files that are being read but if we have partial We actually only want to read type of We only want to read This file well my copy pasting is off the charts today Still better than mine So we're gonna use let for once we're gonna use Because we're gonna change it if we have partial you're just gonna read one files if we don't We want to read all the files boom Okay, so you don't yes for partial We'll only give you the little bit in the middle if you don't we will give you the header the middle and the bottom Okay, so let's as a promise all files which sometimes might be an area with just one item in there and sometimes with three Somebody is asking. What is the actual benefit of server side rendering? You don't experience mostly and I think I touched on it earlier at the beginning. I guess if we didn't do this and we didn't do Like rendering out all the pages ahead of time and saving them as individual files The user would have to wait for the JavaScript to spin up Mm-hmm, so you had to download all the JavaScript build the page on the client and then inject that HTML And usually in between there's also a request to the server to get the actual data that the user wants to see Or you have to maintain multiple copies of the same index HTML, which is also Which is probably more developer experience But also there's very error prone because the second you you do something wrong Everything can break apart. So yeah, one of the superpowers of the web as well It is really worth pointing out is its ability to stream if you look at a large document If you look at a large document on the web and it's like several megabytes large It can still render after the first few kilobytes have arrived because it has hopefully potentially for some inline styles It's got enough to get something up on screen if you're gated on your JavaScript You have to wait till it's like an entire kind of bulk download is finished before you can get anything on screen And so having something that where the server can immediately respond by going look Here's some HTML and ideally some inline styles or whatever Get that up on screen and when the JavaScript and everything else is ready Then you can progressively enhance into other things. That's good if JavaScript breaks Which is something that can happen. I was just on a vacation in Indonesia where internet is Noticably slower than what we're used to here You really feel difference on website that do care about Delivering the right content on the very first response versus the site that need JavaScript and everything to just get started Basically performance and resilience are at least two performance. We're doing it on supercharged Carry on carry on I will All right, so we have files files and we're gonna do the rest days the same So if it's just one file, we're still gonna turn it into a string We're still gonna compile with handlebars bars, even though nothing is gonna happen there And then we're gonna create a hash Set the headers and set them back. So all the the pipeline stays exactly the same We just added one if to handle partials. So let's see with curl if it's actually doing what I want So I'm gonna reset syntax errors. You got one. Oh, it's not it's worth it outside strict mode Now didn't you say to me earlier? I'm pretty sure that yes I think that's the case apparently apparently you need to put in you Apparently I think in your versions of note. You don't need maybe I was on note five. Yeah, no, no five six four So yeah, I think that let's give this a try again That's a good start. I can live with that. Okay, so now you can do you so let's start Does the old version still work where we get the entire document? Yeah, I does and let's add partial And we just get a single line, which is awesome and also it has a different e-tag because it's a different document Which is good. So let's go Let's actually go into your code and get to patch up your code. This is so exciting We're talking about it's I write flawless code. I Let's look. Is the router the router? I'm not gonna help you now. I'm No, it's the view takes care of actually loading the data for itself because you know, that's actually sensible design All right, so somewhere in here we should have the XML HP request This is the on-load events that There we go. So what you do is you call You just use data which is I think the part of the URL that we've just navigated to and the only thing We have to do really is to append partial I don't trust this So I add a partial that means that now our client-side code should only load the data it needs to refresh the views Let's go back to the browser. Let's go back to home and refresh And because we have the preload headers. We already loaded the different. I mean, I can go here It should still work. So everything looks right and it's good So it's still working and let's take a look at what about actually load it Somebody's asking if you can when you get a moment, can you disable JavaScript and just show the benefit of server-side rendering when this is done? Switch off JavaScript, right? And then it will just show that the links actually work without Well, yeah, yeah, okay. So he I can now click. Let's reload. Let's go back to home. Let's reload I Had console I'm gonna click on about We load it about Partial and that means in response. We only loading a single line of markup instead of the entire document which is yay winning for us So we're gonna save a lot of data. So now let's do that since we this seems to be working fine We disable JavaScript Home refresh Okay, click around about Contact missy. This is there's no animation because we have no job. That does it still work She's still getting to the this is the this is progressive enhancements Enhancement done right because even without JavaScript the site is actually fully functional winning This is really really good. And then we just enable JavaScript again. We reload our website and we get our nice switchy animations So in the end We just wrote a back end in about 70 lines. I want to give this one more try Okay, I just want I'm gonna actually I'm here from speedy on speedy the entire time and we saw HP one, right? Yeah, I have no idea what's going on here I'm gonna blame note for Okay, that seems like a thing if you want to know why this didn't work follow me on Twitter And I will figure this out because this is bugging me Yeah, well, it's the only issue honey had the early doors and you recovered beautifully. I must say Are there any other questions on yeah, how is the chat doing? Yeah, it's doing brilliant. There's been so many great remarks so many So many brilliant chats in here. I've been really enjoying it. I see why you do this. This is this is really rewarding It's really nice people out there in the chat. Yeah So I guess what we really say we've got 70 lines of JavaScript. We're gonna push it up to the GitHub repo So that you can have a look around and we'll probably add maybe a few comments in here I Am gonna get you to move that regular expression out from there. That's yeah I'm gonna clean that one up because it's just that it's just it makes your eyes bleed and nobody knows It's not good. It's really not even the comment doesn't help. All right. Okay Are we done? I think we're done. Wow We got we got so that rendering in in under an hour Perfect. Okay. Well in that case, I guess all that remains is for me to say Thank you to everybody who's joined us on the live stream. Don't forget that you can subscribe. You can Follow us on Twitter. I'm at aro twist and at just Zorama and we will catch you probably in the TLDW till Too long didn't watch your TLDW. It was TLDW. Yeah, I've got it right this time Well done me normally when they record those videos. It takes me a lot of takes to get even the slightest thing, right? It's a bit like my my typing. It's it leaves a lot to be desired. It's it's like I'm not Exciting note. We'll catch you next time. Thanks for watching