Learn How SvelteKit Works

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey friends how are you doing welcome to learn how swellkit works as a framework so let's set expectations this isn't an introduction for beginners to swelkit if you want that I have resources for that if you want to watch it or learn how swelt or swelkit works but this is more of a deep dive in how swelkit works as a framework so if you're someone that's confused like where does your code execute on the server on the client because I've seen a lot of this from the questions in my comments or even on places like credit so this is going to be the resource for you and we're going to go over what silk it is what parts it makes we're going to look at some technical details but not that it's too boring but we're not going to ignore them so we're going to talk about that we're going to talk about server side rendering client-side rendering hydration and Etc so I hope you're excited as I am let's talk about futuristic web development I started web development at the height of the react era when single page applications were older age and that meant we had to recreate what browsers already knew how to do from navigation so using the browser history with JavaScript right you might be familiar this from single page applications to handling forms of course event prevent default everyone is familiar with that in fact it became so common we forgot how the web works and that it all already does that work for us so we had to implement that in JavaScript to support those types of applications this isn't me saying that's wrong or whatever because that was really required for the time and we learned a lot from doing that but as time moved on Progressive enhancement was pushed to the side and instead of using JavaScript to enhance the user experience it started being required so we can look at an example of that if I go to Twitter and if I open the developer tools and disable JavaScript so I can press Ctrl p and then I can use the pointy boy if I start typing JavaScript I can disable JavaScript and now when I refresh this is going to break because Twitter is using react yeah so we can see JavaScript is not available it's kaput so yeah you can do anything it doesn't even server render to give you at least a placeholder or anything else so yeah you're out of luck if you're not using JavaScript so we're under this assumption that everyone is using JavaScript and of course JavaScript isn't bad I love JavaScript but the fact is that your site should work before or JavaScript and not without it so that's the philosophy that Frameworks like remixed and swelkid embraced also want to mention another great talk you can watch is from Rich Harry's futuristic web development here he talks from the transition from sapper to swellkit and what the future of web development looks like so that's a really great watch if you want so things are starting to change and we're seeing a shift to the server because we realize despite having a computer in our pocket which shouldn't do everything on the client the client meaning browser but we say client because that can be any screen right or device you're using to interface with something the client can be anything and it's not just the browser and that's why we use that terminology so that's really our worst user experience because of the bundle size of the JavaScript so imagine your app that's just a single entry point like a single Javascript index.js file the bundle size is going to increase as your application grows larger of course it's not always the case you can use code splitting Etc but yeah having your entire logic in one place on the client JavaScript can fail for whatever reason if you dock under a tunnel where you're doing a request or something else then you're screwed so before you continue let's explain all these esoteric Concepts briefly like server side rendering and client-side rendering so server side rendering is the process of taking a request from the browser and returning a rendered version of the page as a HTML response which is great for SEO or search engine optimization because it's easy to index by crawlers then you have client-side rendering which we talked about just now single page applications right so is the opposite where you send the browser an empty HTML document and then JavaScript can hook into some element like I don't know like maybe it has an ID of app if you're familiar with react and then everything happens from that single element from navigation Etc but it's really great for applications but not for SEO so why did we move from server-side rendering to clients and rendering is because we really wanted that smooth user experience I'm not sure if you remember how Gmail for example was such a big deal because all of a sudden you had native app like feel when you were using an application on the web instead of imagine if you're using Gmail or something and everything you navigate to has to do a full page or refresh Etc that would really feel janky and awful right and then you have a fan favorite SSG or setting style generation if you're familiar with jamstack it's similar to server-side rendering so static side generation is almost the same as server side rendering but the only difference is where your build time happens right so instead of building a page on demand when you visit you pre-render the pages in advance and you can cache it forever on a CDN so for example you ship your block to netlify over sale and their CDN is going to Cache it forever and then when you make a change it's going to purge everything and then cache again everything forever and that's what's going to make your site super fast and responsive and it's of course great for SEO because it's pre-rendered in advance so a spa or a single page application is a general term used to describe an app that doesn't need to reload so again that great user experience when you change your route and is contained within one page where JavaScript handles everything using client side rendering so people get often this confused server-side rendering and Spas but actually it server size rendering and client-side rendering so again server side rendering you send a request to the server and it sends you a response there's a HTML document where everything is rendered right but with a single page application JavaScript hooks into a shell of a HTML element right and then it uses client-side rendering to change the content on the page and that's why you don't get great SEO so for example if I go to here and let me just see if I can not use the print options I do this always so you can enable black JavaScript and let's do this we're going to refresh Twitter and now look at this for so for example let's see this text let me just select it copy it if I go view Source this shouldn't be in the source it's going to be in light in some weird JavaScript right so if I do a control left search yeah and I can't even find that exact text so literally you don't have server side rendering this is bad for search engine optimization but something like Twitter really doesn't maybe care about the SEO but of course maybe it would be nicer to have some Progressive enhancements so you're not out of luck if you disable JavaScript right and then lastly you have MPS or multi-page applications you can think of something like eBay that's an e-commerce and is the opposite of a single page application because every page has to refresh live so you can think of PHP and Etc and for those kind of sites the first response is really important to show something on the page so the person doesn't leave your site because you want them to buy something so yeah so if you were to use a spa you would have to wait a longer time for all the JavaScript to load instead of using server side rendering where you can get that HTML document which is faster than having to wait for a spot to load JavaScript but yes so where does silky fit in all of this spectrum so swellkit is a full stack framework that gives you the best of both worlds where the page a server side rendered on your first visit but when you navigate to other Pages they're going to be client side rendered your first page is going to be serious hydrated and after that swell kit is basically a single page application right until you refresh the page or visit another one for the first time and circuit also gives you levers for your pages to use any of these rendering methods so you can pre-render a page if you want you can pre-render your entire project if you want and we're going to look into those options later and I really like this quotient documentation the core or cell kit provides a highly configurable rendering engine because silky blurs the line between front end and back end it might be confusing where your code runs and that's what I'm going to try to answer here so this post assumes you're this familiar with swellkit but if you're not I have an entire swirl kit for beginner series and a swell for beginner series you can watch swellkit is a back-end framework and you're going to hear that Celtic is a full stack framework and then some people argue semantics is really not full stack you don't get a database Etc it's really not important the important part is that you don't think of swellkit as swelt with things on top because in reality kit isn't built on top as well but it's a back and web framework where swelt is used as the view layer but interior you could rip out swelt and replace it with another component frame rate that supports server-side rendering and the same is true for other web Frameworks like remix for example so once you start realizing this soil kit is a replacement for something like Express and you write your front-end and back-end logic in one place you're going to have an easier time and it's going to answer your questions like okay if I'm using swelky do I really need a separate back end and then answer is enough so it helps if you're familiar with HTTP request methods and if you have prior experience with back-end framework like Express but it's not required and I'm really not a back-end person but as I said you can think of swelkit as a replacement because you don't need a separate back-end circuit is where you write your front-end and back-end logic and you can read on mdn about HTTP request method all the good stuff like get head post put delete and Etc which is going to be really informative so basically this is the fusion that happens when you combine kit with swelt so let's look at an example so here's an example of a rest API using Express so you can see we're importing Express here we're initializing Express and then here is our get HTTP method is going to return a Json response that's a message hello and then you're going to listen for this on Port 4000 and your front end app would be at something like localhost 3000 where you can consume the Json response so the annoying thing about this is now you're hosting your separate backend in front end but if you're using swell kit this is really one app so let's look at an example here here I have just a normal Express folder and here is the same code I copied and nothing special here I just installed Express as a dependencies and I said type module so we can use as modules yeah and then if I open the terminal I can go into Express and then I can just say no dot so it's going to run the index.js file and it's going to say listening on Port 4000 and then if I go here actually it's four thousand right my bad yeah so we can go here and we're going to see the Json response and that's really awesome so let's see how swelkit makes this so much easier so I can quit this then let's go one step above and then I can see the into the silky folder and let's look at that for a second so I can collapse the express one I can go to swellkit and in here I have routes here is nothing special just the default one you get when you initialize a circuit project and here is the magic sauce so you can create the same thing if we create a message dot Json JS file or you don't even have to include the Json but yeah it's really the same thing so we have an API and then we're going to get a Json response so yeah so we're in the swellkey folder and I'm just going to run pnpm run there because I'm using pnpm here but yeah now if we go to localhost 3000 we can see the default message but now we can go to our endpoint message Json and we're going to get the same thing so I hope now you understand what role swelkit plays and what problems it solves a bit more because swellkit is the front and add back-end you can deploy everything as a node server if you want or you can use something like netlify or versl that serves serverless functions which is really a nice method to host something or you just need a zip or JavaScript on the server right so for example for my site I have a newsletter I really don't need an entire backend for that right I can just use a sip of a serverless functions and it's really cheap to host it somewhere on yourself in fact it doesn't cost me anything to host it on yourself but of course you can keep your server separate if you want and it might not be a great idea for making something like Discord but if you need some real-time communication like websockets you can create a custom server if you want using toolkit and I even have a post on using websockets with circuit I'm not sure if I would use it in production but you can and in the future I hope swelkid will support websockets natively like it has the get post and all the other HTTP request message right so among other things swelkit also includes pages so it has file based routing right it has endpoints API routes it has nested layouts and this is way more powerful than just nesting files so for example if you're familiar with negjs you might be familiar so if you go to routes and then we can say some nested route index soiled right and this really isn't a nested route of course it's nested in the file system but nested layouts for routes are way more powerful where your components are literally mapped to the URL so a great example is from the remix marketing where we can look how this works swelkit really needs a site like this this is really an amazing site I really love what remix is doing with their marketing so remix has a cheat code nested routes and it's really the same as in cell kit or other Frameworks that have nested routes so you can see how all of these components map to the URL if you look at it here so here we're at the sales invoices and then we can see here is the sale so it maps to the sales URL and then its invoices and then it goes to the specific invoice and how amazing is this this means that for example if this goes boom boom first whatever reason instead of your entire app crashing and burning only this is going to fail in your going to get a nice user error message right and this is really awesome so thanks to Veet we also get hot module replacement so that means instant updates in the browser when you make a change and it preserves your application state so for example when you make a change your CSS signals hey only the CSS change I can update this immediately or if you update a Javascript file or whatever a cell component it's going to be like hey only this part change let me update this and this is really an awesome development experience you also get pre-processing for typescript scss at pug among others so this is in your swell config when you scaffold it by default so if you go to the soil config for example just call it this and close the sidebar here you go to adapter Auto for the specific Target environment we're going to talk more about adapters later and also cell kit lets you build component libraries so you can have a mono repo set up and then you can easily create and publish npm packages and of course I already mentioned it you have deployment options which are adapters for any platform swilkit uses the web platform what does that really mean you might have heard of this for swellkate remix and Etc and everyone throws the term around like it means something but what is it right let's first start by saying that swelkit is a machine that takes your code AS input and outputs code as you make a change and you can find a generated server and client code in the dotsville kit folder which you're going to look in the next section when we scaffold swelkit from scratch but basically spell kit Like Remix is a compiler and my favorite quote that describe swellkit comes from the silky documentation fundamentally a swell Kit app is a machine for turning a request into a response and if you're not familiar with this this might be like whatever but I'm going to show you what that exactly means so selfie leverages the web platform and uses their regular requests and response objects of the fetch API so it works in any JavaScript runtime that's not a browser and uses adapters to Output the code for the deployment Target so if we look here here is the request interface of the fetch API and you can read about this more if you want to learn it and here is also the response interface of the fetch API but yeah this is really an interesting read so let me just close this too so let's look at an example right so here I have an example of a simple request object and fetching the data so we're going to talk to the Pokemon API we're going to get a list of Pokemon so of course you may be used to it it's way easier just doing a Fetch and fetching the Pokemon API right but here I'm going to show you how you can use a request object so we're making a new request cons request then we say new request using the web platform right how awesome is this and this is basically what zelkit is doing under the hood and all these Frameworks and then you can specify other properties which you can refer documentation and we're going to console log the request out we're going to get a response like this and here we're using normally fetch but yeah let's look at an example here is a code pane I just copy pasted this code so here we have the new request and then I'm going to console log the request itself and here we fetch the request we turn it into a Json and then it's going to return an object that has results where the Pokemon are so if I uncomment console log request just so we can see the request and we're going to also see the fetch so this is the request itself that we created right so we can see it has a lot of properties and even more you can read of course when your documentation as before but yeah this is just the request and here is the response you get so we get a list of Pokemon and how wonderful this is so let's look at the swelkill version of this so if we go to the soil kit endpoint I made so here is Source routes again I created a pokemon.json route let me just collapse the sidebar and it's the same here so we're just doing a fetch for Pokemon and then we awaited and then return the Pokemon so if I open the terminal and like I said pmpm run Dev and we can go to the URL so if I go to here I can say Pokemon Json and then you're going to get the Pokemon and how awesome is this and I also console logged out the request and you can see here if you remember here is the request that you received and if you look at here is the same thing proving that swelkit uses the web platform and this is what it really means that it uses the web platform because it uses web apis and Etc and not some proprietary abstraction on top of it we should embrace the web platform and it makes it easier to work and collaborate on things right to understand how cell kit Works you're going to set a circuit from scratch and it only takes a couple of steps and it's surprisingly easy but it's going to help us understand how swell kit works so inside an empty folder I'm going to create a handcrafted Fack a Json file and specify we're using ecmascript modules which is the official format to package JavaScript code for reuse and we're also going to include some scripts to it interestingly enough when I was starting to record this there was a breaking change because felkid split the soil kit and wheat configuration file so that's was fun but yeah I just wanted to show you that it really doesn't matter how things change that it's all going to work the same and yeah it's going to be very interesting going over it so yeah let me just open the sidebar and we're going to create a package soon and then we're going to just copy and paste over the script so we have a types module and wheat is going to be in charge of the development building and previewing so now we only need a couple of packages we're going to npm installer in my case I'm going to use pnpm but yeah if I open my terminal I can say pin PMD and it's already like I've done this before yeah so you can just install this and yeah that should take a second and this is all namespaced under the spell.js organization on GitHub so kit and salt if we go to the repository here as well so here's a sale package and here is kit and we're going to see how kit also works because if you go here and maybe let me just bump this size up maybe if you're not familiar with mono repos basically instead of having different repositories for packages everything that makes swellkit work is going to be inside the packages folder so if you ever browse a repository GitHub see a packages folder it's a good indicator it's using a mono repo because I think this is using pnpm and if you go here to the workspaces you can see how it sets up the workspaces so this is like if you install the package from npm so you can use that path and Etc which is really handy yeah but if you go to packages we can see from kit here the adapters which we're going to talk about this is a Google thing I think amp creates wealth is the CLI for creating new set application and then you have Kit and other thing that pertains to it so if you go to the source we can see core node packaging the runtime utils wheat itself which is responsible for the developer server another thing worth noting it so what really happens when you run a command like npm run Dev so it runs V to Dev but what exactly is wheat or before it was swelled dash kit so let me just close this and if we go to our node modules we can see under bin are the binaries so this is going to be confusing to you when I open it this is just a bash script and it's really not important even understanding how this works because I for example don't understand bash but I can get the general idea what this is trying to do so this is trying to find the starting point of the application or the endpoint which is going to be in kids case well key JS so if we go for example to node modules where swell JS is you can see kit is here I think if we go let's see yeah it's going to be in this but actually the swelled kit JS file is here we just import the CLI so if we look at this repository here is the CLI and this was previously in charge of everything from the development server Etc it used wheat still but now it splits so now this is only in charge of creating packages and the synchronization of generated files which is interesting but for example if we go to wheat we can see is the same thing it just looks for the entry point so you can find it in pin let me just collapse it so sounds confusing yeah but again we can just go on repeat and now it's in pin so here is sweet Js and now we can see it's already here and here it Imports the start so again very similar it does it from this node CLI so if we go here note CLI and if I search for Dev yeah start the development server so this is really what gets output in your terminal but yeah let me just close everything before I spook you yeah so that's really what gets executed when you run a command like this you just find some binary and does whatever else we're going to need a couple of files to make swell kit work so let me just close package.json because I don't think we need it anymore and I'm going to collapse this so we're going to add a wheat config.js which is a place to add your read plugins and configuration so I can just copy over the config save it then we're going to add the soil config and then I'm going to copy that over and we don't even have to specify it anything finished if we go here to beat we can see it Imports the swell kit plugin and yeah so here we don't really have to specify here but here you can include your preprocessors for example if you include the preprocessor you get support for typescript scss pug and Etc but we're going to leave it blank until we get to learning about adapters that's really it so now we're going to have to create a source folder so let's create source and then we can create app.html which is our entry point which cells uses as a template or circuit I should say yeah but that's going to be it and I'm always amazed how even after we did this crime of this markup the browsers are able to build a proper document out of this and output it but yeah I was lazy so I just did it like this but yeah don't tell anyone of course so we're going to add a route and of course that's under routes you have to do a folder structure like this because swelkit is going to look for these files yeah so you can say index wealth and then we can save home and everything should work now now you have a general idea what happens when we run the development command so let's see if everything works if I clear the terminal if I run pin PM run Dev everything should work just fine so you can see that wheat Dev server is arguing at three thousand and we can just open it here localhost 3000 and we should get our home page and that's it that's how simple it is to set up toolkit so let's examine the generated output further so silky is basically a compiler detects your app as the input and creates the output so when you start a development server silk is going to generate a DOT swelkit folder that contains a couple of interesting things and it gets regenerated every time you make a change so let me prove this to you and if I run pnpm run Dev is going to generate the swellkit folder and here it is so inside we can see it has a generated folder that has the client manifest which holds all your routes if you see here is the layout error in cell route and this dictionary is interesting because I think it also Maps the component to A and B component where a is the layout or whatever and B is your page and then it also looks for a shadow endpoint but it's really not important so another interesting one is the matcher so if you're unfamiliar with matchers if you have a route like routes archive where you pass a number for a page you can make sure that this value is an integer by creating a custom matcher so someone can't pass in for example archive potato which would be valid and you really don't want that but yeah it's really interesting and then you also have a root.12 which is your entry point and we're going to look at that in a second so let me just close the matchers and I'm going to leave that open for the runtime you have your app where is the environment the navigation the paths and stores itself and then you have the client Singleton just make sure that only one instance of the silky client is running and I can close this and you have components here is your error and layout page really nothing special here okay so you can close this and here is the server itself and basically this is just copied from node modules if we go to soil actually so JS kit and then if you go to assets basically to just copy paste it over so really it's nothing special but yeah let me just collapse this but another interesting thing I want to talk about is the root.swelt but basically the root dot swell file is interesting because it takes the routes from client manifest.js that are treated as components and besides initializing some page values it's in charge of displaying the components so for example if you look at the client manifest it's an array so you would probably think that this is index 0. which is correct right and then you would probably think that this is index one and of course this will be index 2 but really that's not how it works if you have an error the error is the component is going to get rendered so this won't exist and this is going to be index one but if you don't have an error then everything is fine it won't even get loaded and only you're going to have your page rule is going to have index 0 and 1 Etc okay so let me just remove this I'm going to remove these values and this is going to make a lot more sense when we log out the values let me just close the documentation here and if we have our development server running we can go to the roots well and this is always a fun thing you can do just don't be afraid to go into these files and folders poke and prod around right we can just console log out these values and this is going to get removed when you get regenerated yes so we can say components so we're looking at these components and let me just reiterate how this works so it's going to return proxy objects but as you see here if it has a component so it says hey if there's a page then we're going to wrap everything inside the layout and it's going to get nested and more deeper this pyramid that gets generated because if you have more named layouts and Etc and here is even the announcer one if we go for example to our page I refresh and if I inspect the element we can see that this is basically what gets generated so this is the most important part the rook.12 which is the entry point so this is responsible for rendering your components to the page but basically how it works is I made a simplified version here so if page then it wraps everything inside the layout then it gets deeper if page inside is a named layout then interrupts it inside a name layout in the page and yeah Etc but yeah if we log it out here and if you go to the console I always like to refresh for good measure we can see what this page has so we can see this is a proxy layout component as I mentioned keep in mind how is zero index and this is one and as I told you this is going to be layout indexed if you have some error on the page so let me for example go to index svelt inside of here 9200 is going to work in a regular script through I guess we can say from New Era and then let's see if you're just going to a route or it's going to yeah so you can go see layout and then here is the error so you see your component for the page won't get even loaded which is really interesting but yeah if we go back to the root component and our post if we regenerate the thing so if we let me just close these files because we don't really need them so let me just also add a git ignore I'm going to show you what I'm up to let's just get ignore node modules usually the swell kit folder is also get ignored because it's Auto generated what I'm going to do is basically Commit This and save it to the git history then we're going to see the difference what happens when you make a change so this is what I do in this post here but yeah we can just close it and if we go to our terminal we can stop the server I can say git in it and because I'm lazy I'm going to go to the graphical user interface so vs code and we can just say sure swell kit and we can just add everything because we really don't care we're not going to commit this to GitHub or anything but now for example if I Collapse everything and if I go to Source routes if I say new file I can say sum nested route in Excel in this real isn't important so we can say nested here you can see here is some nested route and if we go to the git history we have to regenerator so you can see pin PM run Dev and you can see what happens here so let me just close the terminal we added the nested route here which isn't important here the types that get generated which is also interesting root swell gets regenerated so yeah that's whatever maybe it's going to change if you have more nested layouts or components Etc but what's the most important here is the client manifest as I have it here here is the git difference so you can see what really changed so it really added the nested route index well and then it updated the dictionary to include some nestorel so I hope this wasn't really that confusing don't be really concerned about having to understand how it works exactly but you're going to have a general idea how everything works at the heart of selkin is a client-side router that handles everything from intercepting link so for example when you click on a link instead of refreshing the page it's going to behave like a single page application and it also handles file based routing nested layouts providing page and navigation stores and watching file changes to regenerate the routes as you've seen previously but if you want to learn how all of this works and even if you want to make your own client-side router you can visit lihao on YouTube and he's currently doing an amazing series on writing your own client-side routing Library so if that's something you're interested in give it a watch and say hi from me but what makes silky truly work is wheat because it's built on top of it but wheat is a Next Generation build tool made by The View Creator Avenue and you can think of it as a replacement for bundles like webpack and it enables a development server server side rendering watching files for changes when we regenerate routes when adding a page so right have you ever thought about this how that happens you add a page and it updates it that's how it has hot module replacement so it updates your page when you make a change it supports abundant development basically before in the webpack days every time you save the head to bundle everything together because browsers didn't natively understand ecmascript modules but now they do so you have blazing fast development speeds when you make a change because of unbundled development but because of of all the dependencies of the package as it causes are huge waterfall because if you can imagine a request B and then it goes like forever we still do optimize builds for production and V2 uses roll up for that so it packages it all into one neat file so it's really efficient right but if we could zoom out and see a visual representation of what makes swellkit we would see something like this and I'm going to show you this in excalator if we go here we can see how it all works so basically these are the most important aspects I think what makes 12K so here we have Veet which is the development server SSR and HMR so it's a server file Watcher and bundler remember how I said that soil isn't something that this is just built on top of soil but swelt is actually just a part of it is the view layer or the framework right and then it also uses chokidar to watch the changes for the packaging and the lip folder right and then we have also adapters which are plugged in the generate output for Target platforms and this is node which is a server then you have netlify over cell and cloudfare pages that are serverless you can also pre-render everything you have spots single page application rise and then you have other community adapters so remember how we talked about what happens when you run npm run Dev and this is possible for Sade because shade is just a CLI Helper and yes it's named after the singer so it's a smooth CLI operator and basically when you run npm run Dev it loads the swell config and it also gets the read config and creates and starts the development server but yeah if this was a crime show this would be the part where you say enhance so let's also do that for kit and see what makes it work so if we go here we can see here is kit and also you have wheat which is built development and preview and you can find all of these folders and packages as I showed you previously in the swell kit repository you have packaging for publishing npm packages right because with cell kit you can easily create your own then you have core which is the build time and CLI code then you have the runtime that includes the client and server code and the most interesting one is probably not because it includes polyfills and basically if you're not familiar what the polyfill is it basically adds code to make something work that otherwise isn't supported so for example before node didn't support natively fetch so silkit still uses node fetch to expose it as a global so you can use fetch on the client and server so it's the same consistent experience but they're probably moving forward going to change that to use the one built into node because it supports it as of recently but yeah it makes the web apis available as globals the web crypto cryptography one the fetch response request headers and it uses node fetch right so what's interesting is that when you think about this this all makes swell kit right so all of this combined is basically the cell jsuit plug-in swelt combined with plugin soil kit plugin and this is really interesting because now they exposed it and since vid has a separate config here it is but before this was something internal where I was looking at it but it's really interesting to see how it's exposed now because vid has a separate config so here it is in reality but let me just close this and if I go back to the post so these parts together make sex audio and you can see David plugin is used to make swelt work with weave and it passes the plugin options from the compiler options preprocessor to the inspector which I might make a video on basically the inspector is awesome if you hover over a link in so Health it's going to tell you where the component is in your project and it's going to open it in your editor and again I talk about the V plug in swell kit because it's more interesting and at the time of writing this but need to update it because it's no longer internal but it's responsible for taking the swell kit config creating the routes server-side rendering and loading the template replacing cell kit so if we go to app basically replaces this with what you have on your page and it does also other things which is really interesting so I hope I didn't lose it so far if you're confused that's alright because I'm right beside you trying to also understand how it works but now you have a higher level understanding of how silkit works so let's explore how client-side rendering and server side rendering Works let's talk about client-side rendering you might have to process a lot of data or want to use a huge Library like graphql it's even larger than reacted around 160 kilobytes so imagine if you did it on the client constantly you're going to make the user pay not only for their compute but for the bandwidth when the server should do the hard work even though you have a computer in your pocket right this is really the shift you're seeing towards the server because we started to realize hey maybe it's not a great idea we're doing all of this on the client we should move the computation to the server and it's really not going back but we learned a lot from the past and what we learned we're going to apply to the present and the future right so for this example I created an endpoint inside routes API that's going to talk to the Pokemon API and return a list of Pokemon so you can go to Source routes and let's create an API folder in this release in convention I just using it to make it explicit this is something that we're going to expose to the outside so anyone can consume this API endpoint including our application yes we can create Pokemon Json JS and I'm just going to copy over the code yeah this is going to fetch a list of Pokemon if I go here if I copy paste it into the browser you return the Json response really only interested in the results that gives us back the Pokemon now that's it and we don't really have to touch it again so we can go to index.12 where the magic happens and previously we had this piece of code but let's just copy this over so again here it's nothing special this is going to be client-side render that we're going to see what that means in a second but yeah it just talks to our own API and returns a response as a Json this is really another benefit of having your backend because we can really massage the data however we want for example let's say we had a thousand Pokemon so now you're making the user on the client download that list of thousand Pokemon and then you may be going to map over and filter it and you're like really taxing the user right but yeah it's just going to fetch the Pokemon and it's going to Loop over them and display them and let's see if I have the development server so we can run pmpm run Dev and if you go to our home page we should see a list of Pokemon and it's loading and we can see we have all the Pokemon here and this is really great if we open our developer tools everything works great and we can see our elements here and for example let's say I want to make a Pokemon site and make all this sweet Pokemon dollars I want to display all the Pokemon in a list and I want it to be server side rendered really fast I want to Cache it and Etc and I'm like that's really great I'm going to have great SEO right but if I go to the page Source I'm like where is my markup what the heck is going on right and this is what it means to be client-side rendered because it isn't a document that the server sends that's complete with the Pokemon response this is just a HTML placeholder if we go for example to the network Tab and let me just refresh everything let's make it obvious and if you can see here is our HTML if you look at the preview there's nothing here because it's just a shell right JavaScript takes over this and it hooks itself to whatever element here it is to the body problem and then it creates all of these elements and takes charge but yeah that's really what client-side rendering means and now our business plan failed and we really said but really it's not lost because we can use server-side rendering and as I say here if you look at the network Tab and the page load is going to fetch the Pokemon API Json so if you go here it's a network tab let me just clear everything and I always like to disable the cache and if I refresh it we can see here it is somewhere Pokemon Json and here is our response so the server has to do a round trip as I showed in this diagram so here is the server and it gave us this index HTML file right here it is but now it has to go again back talk to the server so it has to do fetch API Pokemon Json and then you can do it on the client and that's what it really means to have a round trip right because it has to do all of this but using server side render we can get all of this data we need on the server and serve it to the user but another thing I want to mention is that some people are like oh it doesn't really matter Google can execute JavaScript in can but you can even read this resource understanding JavaScript SEO Basics if they can but it's not cheap to do because you have to open the page in a headless browser and execute JavaScript for millions of sites so imagine once Google bought resources allow the keyword is allow a headless chromium renders the page and executes the JavaScript so really don't put your stock on single page applications being or having great SEO right you have to rely on server-side rendering let's talk about server side rendering because at this point you might be confused and you're like hey didn't you say that swellkit server side renders every page by default before it turns into a single page application basically and that's true but we're doing this on the client so it makes sense why it's not terrified rendering because we're fetching the data once the client loads inside the script tag right but if you want server side rendering we have to somehow fetch the data before the page or the component is initialized right so how do we do that and you've probably done it before and you did it using the load function inside context module so I'm going to copy over this example so basically context module runs before your component gets initialized right so this is going to run on the server and the client because of hydration which you're going to talk about later but yeah it explodes this special fetch function and then we're going to fetch the Pokemon firmware API and now this is initialized and generated the HTML page right before our component right so we can just get the list of Pokemon and we can display the Pokemon if I save this and refresh we're going to see this is true and also we get the list of now and now we shouldn't see here a fetch request I think yeah because this happens on the server and now if you go here to the localhost you just make this larger you can see instead of the shell document we get the real deal so we get the preview here are headers whatever here is the response and now if you look here in the response here our Pokemon which is really awesome and even if you go to the view page Source we can see that we have now great SEO because of server-side rendering and we've done all the hardware on the server so we don't text the user and this is really a win but yeah let's talk about other things like for example you might be also wondering if you go to our endpoint if this only runs in node or on the server right how is this using Fetch and that's because remember before swelkit exposes globally the poly field fetch right so it's not a problem on the server but on the client we need to import that special feature because it also does some other magic things that makes it easier for us when working with these apis right so I really hope you understand the difference and how this works but if your page depends on data that's only used for that page let's say for example that only our home page is going to show the Pokemon data and we really don't want exposure API for entire world then you can just create a page endpoint which was previously called The Shadow endpoint so you can also reduce that boilerplate you can just remove or delete this code and yeah you're going to have less code which is awesome I also want to briefly explain how context module actually works if you're confused about it because it's really not that spooky so let me just select here JavaScript PDF in this example let me just copy this over so basically at the end of the day when your swelled component compiles and you can also think of your pages and components because that's what they are as we've seen in the Manifest but yeah basically imagine this is your swell component and this entire file is basically a module right so you're going to have code like this where you import that component and you're going to reuse it like component one component two Etc but since this file is a module and in the context of the context module right it's going to log context module only once but for these other components is going to always log out the component so the context module part is what happens in the script context module part right and the component here that we've seen this is what happens in the script tag so if you do here here is our script tag I hope this makes a lot more sense how context module works and you're not going to be confused just remember that this runs on both the server and the client and we're going to learn why because we need to basically render it once on the server and then we need to hydrate it again on the client so we can add back interactivity like JavaScript so instead of doing a round trip like we did using client sign rendering using server side rendering we can just get everything all at once to the user so we just hit the server it sends us back the HTML that has all the data we need and yeah that's really it another interesting aside is what silky does with the fetch response so during server side rendering the response will be captured and inlined into the render HTML and during hydration the response will be read from the HTML preventing an additional Network request and here I have an example and we can look at this if we go here so if I actually we can go to the response and we can probably find it here even though it's not that pretty if you go here here we can see here is our fetch response so it returns all the data and this is going to prevent refetching and Etc and just pretty format it if I can yeah awesome so now we can look better at this code and here is our Json response right that basically means inlining so what is hydration when a user requests a page the server sends a dry HTML page where the components are entered as HTML and that's basically what server-side rendering is because for example swelk has an internal method create SSR component that takes a component and Returns the generated string of that component and that's the HTML that gets returned but there's a problem you're just returning HTML so how do you get back the interactivity if you have an event handler Etc and that's basically where hydration comes in and it's just a way to load the JavaScript and make the page interactable again as we can see in this diagrams we have the server and here it runs on the server the create SSR component you get the HTML back but then you also have to download the JavaScript and then you hydrate it and then you have an interactive page hydration sounds like a fancy term but it just means adding JavaScript back to your server-side rendered HTML page so it's basically like this image if you want to learn more Lee Houghton again has a great video explaining how hydration works if you want to look into that and this is important to understand because your page runs both on the server and Client First the page has to be server side rendered on the server and send back as HTML so you have to re-render it again on the client to hydrate the page so for example if we look at our let's go to index so in this slot module the common question I see asking confusion is why can't I just use my database here right and you really can because of this right you have to run it on the server and client which makes it first unsecure if you're using some secrets you really can't use it here you have to use it inside the endpoint so if we go to our endpoint and let's pretend that our Pokemon is in a database here is where you would use your secret credentials and connect to the database right and you can't do it inside the load function and we can even try it out ourselves and I think the certain documentation is a bit confusing because they make it sound like only load is this magic thing that runs on the server and client when it should be more clear that your entire page which is the module right the component that is what runs on the server in the client and we can prove this if you just go to the script we can say hello and let me open the terminal and I'm going to open localhost or console so our terminal here is the server right this is a node process and here is our web terminal the console right and then let me just save this and if I refresh the page we should see Hello in both places and sure enough here it is once you understand this everything else is going to be more clear so again let me reiterate it isn't just slow that runs on the server and the client it's your entire page because it's just one big module right and once you understand it it's going to make a lot more sense and knowing this makes reading the warnings from the circuit documentation on using loading start to make a lot more sense so this wealthy documentation makes this point use the swelt provided fetch wrapper rather than using the native fish and here I have an explanation because it runs on the server and you need to fetch the data to server-side render it and it also says don't reference window document or any browser-specific objects because it runs on the server where those don't exist right and it says don't directly reference any API keys or secret Etc because the page gets server side rendered and then it needs to re-render on the client because of hydration and we can even look at an example of how this works let me just close the terminal and I already have this example in the swell triple but if you're like spooked by the selfie compiler output don't be because it's really not that bad and this is really how silica is a compiler and why does it need to ship a framework because it just generates the JavaScript required to run the page we can see all this happens inside this create fragment just creates the element and it mounts them and whatever and this works fine for the Dom right and here is also there is a component so remember how I told you that every swell component gets turned into a class there really isn't no difference here as you can see in the options for now it's generating the Dom but remember how I say that it needs to return a string so what happens if we want to use server side rendering and you can see this starts to look really familiar so you can see create SSR component all of this spooky scary nonsense like really doesn't matter we can just look at code like this and we can just gleam what it does right and it just basically returns a string that's the HTML and that's a really quote-unquote simple it is because sorry side rendering really isn't simple but the fact of that you just return a string yeah how does then swellkit know how to rehydrate it and here is where we can go back to the Dom and you can make the Dom output hydratable where silky is going to know what it needs to Output instead of rebuilding the entire Dome like using a single page replication it's just going to attach what it needs back to those elements so yeah if you look at this output and if we enable hydratable then it's going to look slightly different it's going to again create the elements but it's going to claim the notes because L stands for claim because probably C was taken right so that's another funny thing and then it's going to mount them and then using search hydration or paint hydration Etc and this is really not complicated and if you just understand like the surface level of it right we really don't need to understand the internal specifically a lot of this is going to make a lot more sense and give us confidence how it works in the post I've done the same thing where I went over it and yeah this is what I went in and I cleaned up the code here so it's much easier to read and yeah so let's make the same component in soil so if we go to Source routes we can create counter so let me just close this and I can just copy over this code yeah and then we can go here say counter yeah and everything should work but for example if we say context module I can even remove this this is just a snippet I have you can say export let hydrate we can say false and then let's for example if I go here you can see here is the hydrating part so here's also interesting just zoom in so you can see it here is where everything starts so it runs the start function this initializes the client it attaches itself to the body and Etc you can see here is hydrate status error knows these are your pages right parames and Etc but if I save hydrate false then if I refresh this you can see hydrate null and if I go here I need to refresh it and nothing is going to happen right yes I can just remove this and again I'm going to refresh it let me just close this and in the post I really show you how you can learn how this works and debug it yourself so for example we can go to the sources tab in our developer tools and we can put a breakboard on start and we can see how all of this works so we can do that let me just go to the sources and let's make this more readable and awkward like this but whatever yeah we can go here you can just plop a breakpoint on this right and now when you refresh the page it's going to start here and now we can step through it so we can go immediately to the star function and this is where the magic happens so here is the start inside star JS which is if we expose it let's go see reveal inside bar here it is and of course this is in your project files you can poke around it so here is the most important things that happen the client gets created it gets initialized and then it hydrates everything and if you're adventurous you can just step through it and you can just go through this we're going to skip this we're going to skip over and then when we hit hydrate we're going to step into the function get a surface area how that happens so the client has a underscore hydrate option and again let's just go over these options yeah and then you can just step over the things and see what happens so basically here it's going to go over the nodes and you can really ignore this and basically what it does it like loads the JavaScript required to make it work and basically that's it so if you go here so it's going to a loop and remember we have two things that it needs to all needs to load the layout and it needs to load the counter.swelt itself but yeah you can just step through it if you want it's going to skip this because it's not leaf and yeah this is where the magic happens right so we can even skip over this if you want there's a lot more but of course I'll leave that up to you and I also talk about this in the post if you step into the hybrid function you can see how swelkid loads the JavaScript modules so yeah basically it Loops through the nose the nodes are 0 and 2 index from the client manifest again everything comes back to your client manifest it has the proxy layout in the proxy counter and it just loads them for the page but yeah again server side rendering is a hard problem because you need to make sure what you have on the server and client matches and I'm grateful I don't have to think about it and I hope you also appreciate it more now so lastly let's demystify how adapters work so if you don't specify an adapter or use adapter Auto circuit is going to output for node if it can detect a supported production environment so first let's look at the adapter node which and we're going to import in size 12 config.js if I can open the sidebar let's open the swell config.js and with config.js because we're going to be using both so first we're going to install the adapter node development dependent cell.js adapter node give it a second and now we can just import it here we can say import adapter from swell JS adapter node like this and now we just need to specify in the kit options and adapter and yeah that's it and also inside the vidconfig we're going to give it some build options so if you want to debug your app in production you have to enable Source map so you have to say true because otherwise it's just some jumbled minified mess right so it's not going to be accurate where your code happens or debug it right so you're going to say true but I'm going to say false here and I'm going to disable minification because I want to be able to read the calls I'm going to say minification false I'm going to save this and now let me just close these two files because we don't need it anymore now we can run the build pnpm run build and you're going to see it works because it created the build folder for production but it also made a build and output folder in the soil kit because you can run pmpm preview or whatever but yeah inside the build folder let's just close this is really interesting because we can find the client is here right so if you go here here are assets Pages this is our CSS nothing special so we have chunks here again this is just some internal stuff you really need to think about it again the hydration we've seen before and you're also going to see a lot of interesting things in here here are Pages remember a counter and this looks really exactly the same like we've seen in the swilled Ripple and you can even see this in the response in your network tab which is really awesome so again this really isn't any different like it's almost the same right and again if we go to the error here is our error page and it's the same for the layout right and then what's also interesting in the server we also have some chunks here Hooks and here are some really not doesn't matter what's here let's see entries here or endpoints so here is our API Pokemon right and this is just a git function that gets exported and then we have some fallbacks our error page which is really similar again create the SSR component and Etc so this is really interesting you have our Pages again creating the SSR component for our counter really the same as before so this is really interesting how all of this works right then we have the node folders where the nodes are and remember the nodes are the pages right which are like modules we've also seen this in the Manifest file so it's all interesting how it all comes full circle together and of course here is the entry point for the application and I think it uses polka yeah class polka so polka is a micro web server it's fast it'll make you dance apparently you can see it yeah so it uses the polka server by default but yeah let me just close this in in the post I can close this I go over all of this and explain these things oh and yeah I also mentioned how you can see these weird hashes and if you ever wonder why these weird hashes are just because imagine if you deploy this somewhere and it gets cashed by a CDN and next time when you redeploy it's going to change the hash and it's going to pass the cache so it you don't get a CSS style forever so yeah that's the reason behind this weird file names but yeah I also show you here how you can use pre-rendering so for example if you want to pre-render our Pokemon if you go to index swelt I can go here and we can say export let pre-render true we can save it and then if we run the build again you're going to create an interesting pre-rendered folder inside build here is pre-rendered let me just close the terminal you're going to close this file so you can see it pre-renders the page in advance and again this is the hydration part and here is where it inlines the data so it calculated it in advance right because we're pre-rendering it so it's going to be fast and get cached by CDN and here is our Pokemon API that gets the already done response so this is really interesting right then you can understand how these things work you can also go a step further of course and you can even disable hydration and disable the router for the page if you don't want to ship any JavaScript but yeah if you want you can even use adapter static to generate a single page application if you specify a fallback page which you can see from the documentation so it's basically this is single page application mode if you're interested in something like that so you just specify a fallback and you use adapter static and that's really but lastly I want to look at another adapter that's adapter or cell because it's unusual because it's using serverless functions which a lot of people don't understand right so let me just for good measure nuke these two folders and we can install see PMI development dependencies adapter or cell we can install that inside the swell config just collect this we can say adapter for sale and this is already done so now if I close this we can say pmpm run build and now we can see the output and this is what I've done here and yeah here is the output so let me just close this we're going to close this configuration file and this is really interesting so as I mentioned it here in the post let me just go here actually where did I mention it oh yeah here so let's imagine I was welkid or I was a web framework offer and how would I figure out how to output for these platforms and that's really an easy answer because you always start with the documentation right so for example if I'm interested in versaille and how to figure it out I would go to the resale dogs that are right here and here is their build output API and you can study this however you want right but let's close this and here is the quote from the bill out of the API closely Maps the reversal product features in a logical and easy to understand format it is primarily targeted toward authors of web Frameworks who would like to utilize all of the reversal platform features such as serverless functions Edge functions routing caching and Etc and lots of people are confused about what serverless exactly is and really it's a server that someone else runs other people make the joke like ah it's really not serverless you're still using servers that's really not the point you as the user aren't setting up your own server right so you don't have to set up a node server on wherever because you can just use your cell and they're going to give you a serverless functions it spins up you have 10 seconds I think of execution time you really don't have any persistent memory Etc but it's really awesome for like small tasks and like that right basically this entire site runs on serverless functions when you request a post on Joy of code it hits for cell it hits a serverless function it I guess it just builds the pages HTML and returns it and then I cache it and that's pretty much it so yeah that's what I've done here and you get this output so Universal build output here's the config and here are the routes and I think this is just some configuration for overrides from what they understand so it's not really important and then you have the static part which is your app again immutable and then you have your asset same as before chunks pages and really this isn't any different than what we've seen before so it's not that bad right but here is the API so it already fetched it here is the index but what's interesting to us if we just close the static folder right here are the serverless functions so this is going to basically spin an old instance or whatever for 10 seconds and again you can see this is just a server like before like it's just a simple note HTTP server I think I haven't really Dove deep into this just wanted to demystify you can see it's specifying the package Json then it has to be common JS social is like okay I need to Output this code in common JS format so versel can understand it and basically this is the folder what gets generated when you initialize your project on resale right and you really don't have to think about this if you have the adapter Auto and you just point for sale to your repository on GitHub it's going to do all of this like magic yeah and you don't ever have to think about it but yeah as you can see it's very similar to what we've seen before only it's tailored for yourself specifically and is the same for netlify and all those other platforms and I hope this makes it more clear how these things work and going back to the swell kit code how swelk is just a machine that turns a request into a response so that's really interesting hope I didn't lose you but more importantly I hope reading the post didn't leave an impression like you have to understand everything or that I know everything because I don't even after spending hours looking at the source code because it's really complicated it's basically code that outputs other code and how it pieces together is a bit hard to understand so here's the takeaway swellkit is a backend framework and a compiler you write your front end and backing code in one place swelkit uses the web platform server-side rendering has improved performance and SEO pages are rendered on the server and client because of hydration and adapters are used to deploy to different Target platforms so thank you for reading and as always if you made it so far then if you found a mistake or anything you can edit the post on GitHub if you go here on Joy of code repository and you can edit it or suggest something if you found a breaking issue you can go to the appropriate issue for the post and you can submit it there and then I'm going to update it so thank you for watching and catch you in the next one
Info
Channel: Joy of Code
Views: 14,616
Rating: undefined out of 5
Keywords: svelte, sveltekit, ssr, csr, adapters
Id: VizuTy3uSNE
Channel Id: undefined
Length: 66min 54sec (4014 seconds)
Published: Fri Jul 08 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.