Writing code that resists realworld attacks sets professional back-end developers apart. In this hands-on NOJS course, instructors Jonathan Hill and Rachel Johnson teach you how to think like an attacker so you can build secure, trustworthy applications. You will learn to model threats with Stride and OASP, sanitize inputs with Zod, and defend against cross-sight scripting and SQL injection. Finally, you will master stateful, stateless, and OOTH authentication alongside rate limiting and throttling to protect your APIs from abuse. It's autumn of 2026 and in the middle of the night, freezers in hundreds of French supermarkets started to defrost. Staff opened up in the morning to a wave of hot air and ruined food. But this was hardly an isolated incident. Not long ago, an attack on airline check-in software left three of Europe's busiest airports checking in passengers using pen and paper like it was the 1970s. Hundreds of flights were delayed or cancelled. And tech companies themselves are not immune. Recently, a researcher successfully got access to source code, passwords, and customer data from AI app building platform lovable. Now, none of these needed a genius Hollywood style hacker. They were basic vulnerabilities just waiting to be exploited. And right here, I have got an app with a security floor which we are going to find, exploit, and fix. This is freezer ops. It's a dashboard for a supermarket chain and it shows freezer temperatures for two stores, one in London and one in Paris. I'm Tom, manager of the London store, and this is my freezer. I can set its temperature. So let's say I want to turn it up to just minus 10. I click the button and the dial moves. The freezer goes to minus 10. Now this dial shows us the temperature in the Paris stores freezer. This is not my store and the UI gives me no control over the temperature, but I reckon a hacker like you can turn up the dial and make their freezer defrost. And for this hack, you don't need to look at any code. All you need to do is mess with the URL that you can see right here. Look at what we've got here. We've got a store parameter and a temperature parameter. And I bet you could do something with that. So, play around with what we've got here. And to test it, just hit enter. Go ahead and cook this freezer's food. Okay, congratulations on your first hack. So, what have we got here? Well, we've got a store of one, and the London store is store one. Paris is store two. So, let's just change this to a two. And let's move the temperature from minus 10 to + 20. I'm going to hit enter. And look at that dial move. There we are. Up to 20° C. And their ice cream is cooked. And by the way, down in the terminal, the app is complaining. But who cares? Not the hackers for sure. But in the next Grim, we are going to put our cyber security hats on. We're going to have a quick look at some code over here and figure out how we can close down the vulnerability in this app. Okay, so to understand how we were able to hack the freezer in the Paris store, let's check out server.js. And please don't be intimidated by this express.js code if you're new to it. We are not going to do anything complex here. But I want to draw your attention to this block of code because here we are checking if the freezer store ID is the same as the user's store ID. And if it's not, we're sending a 403 status code which means forbidden. And we're also sending this message which gets displayed in the app right here. But unfortunately, this is not enough to stop this logic from executing. And this is the logic which controls the freezer temperature. So something is going wrong. When this check fails, this function should exit. But it doesn't. So your challenge is to fix it. And I've put here that you can do that with just one word. And I've given you a bit of a hint to look at the conditional logic above. And if we just scroll up, you can see that we've got two conditional logic blocks. One here and one here. So you can have a look at those for some inspiration. Now, when you're done, so when you've written just one word and you're going to be writing code inside this code block right here, all you need to do is save your code with command or control and S. That is going to rerun the app and then you can alter the URL to test your fix. I'm just going to reset the app now and you can go ahead and get to work. Okay. Okay. Congratulations if you just fixed your first security vulnerability. I did say one word was all that was needed and that one word is return because when we return here this function will exit and this code which controls the freezer temperature will not be able to execute. And if we scroll up we can see that we are using the return keyword inside each of these conditional blocks. Okay, I'll hit command S to save my app and rerun it. And it reruns automatically. Let's just check that my freezer is working. So, I'm going to set it to minus 10 again. That seems to be working fine. Now, let's go for store two, the Paris store. And this time, let's go all in. I'm going to put it up to 50°. I'll hit enter. And we get the forbidden message. And the dial does not move. So, we have successfully fixed the vulnerability in this app and protected all of the food in the freezer. And let's just open up the terminal. No errors displaying. Okay, so that was a really good job. and its flaws in apps just like this, which can for a supermarket, an airline, or an AI company, be the difference between a normal profitable day and a complete nightmare. In this course, you're going to learn to spot these flaws before the attackers do, and that's going to make you a better developer. In the first section, my colleague Rachel is going to kick things off by getting you into a security mindset. When you're ready, let's dive in. Hello there and welcome to this part of the backend security series. Thinking like a security-minded developer with Stride and OASP. I want you to imagine this. You've just built a shiny new student portal app. It works great. Students can log in, see their assignments, and track their goals. But one day, a student discovers that they can suddenly see another student's private profile. That's not just a bug. That's a security flaw. And in fact, and this is hard to admit, that exact same thing happened to me just a few years ago. After I developed my first ever student portal, I proudly showed it off to one of my students until this student decided to tweak the URL from her student ID to another student's ID. And instantly, we were staring at another student's details. Just like that, my app was broken into, hacked by a curious seven-year-old. Now, the scary part is that the code worked exactly like I wrote it. I just hadn't written it with attackers or even accidentally curious users in mind. You see, most of us developers start our journey focused on features. Does it run? Does it save? Does it render? But as developers, we also need to think like security-minded developers and ask questions like how can this be broken into so that we can predict how someone could break what we've built and then design it so that they can't. And that is what security-minded design and development is all about. So here's the plan for this section. We'll be looking at the following things. Stride for design time thinking. This is a checklist to help us spot what could go wrong. and the OWOSP top 10 for runtime reality, which is a shared language to recognize what does go wrong once our apps are live. And we'll also compare the two. And of course, there will be some thought-provoking exercises to help you with this mindset shift. By the end, you'll be able to look at any feature and see how someone might misuse it. And if it is misused, what we can do about it. Now, this part of the course is language neutral. There are no framework or language assumptions. We're going to be using diagrams to explain app scenarios and short bug report examples. This means that what you learn here will be applicable to any stack, no matter what your weapon of choice is. And when we hit a challenge, the scrim will pause and give you an exercise to consider and work out. Once you're done, we'll chat about the possible answers. Throughout it all, keep this phrase in your head. Think like an attacker, design like a defender. And that's the heartbeat of security-minded development. And by the end of this section, it will start to feel natural for you, too. Are you ready? Let's dive in. All right, let's get to it. In the last scrim, we talked about why security isn't just about code, it's about how we think. So, let's put that mindset to work. Imagine we're starting the design and development for a food delivery app called Quickbite. Customers can browse restaurants, place orders, and track deliveries. And delivery drivers can claim orders, deliver orders, and mark orders as delivered. Pretty standard food delivery app. Now, both customers and delivery drivers use the same QuickBite app. They just have different roles and permissions. And this app talks to the back end, and the back end talks to the database. So, this is the world that we're analyzing. We want to look at the system from a high level and model what kinds of threats could show up in our design. And one of the best ways to start thinking this way is with a framework called Stride. St R I D E. It was created at Microsoft to help teams spot potential threats early in the design phase. Stride is basically a checklist of six different ways an attacker might try to mess with your system. Now, the goal here isn't to get super technical. It's to start asking better questions. We're still in design mode here, so we're not fixing anything yet. We're just learning to spot the cracks before they spread. So let's have a look at our quick bite app through the lens of stride. So first is S for spoofing or pretending to be someone else. What if a delivery driver figures out how to login as another driver to steal their orders or a customer somehow places an order under a different account? That is spoofing. T is for tampering. Now tampering is all about changing or manipulating data on its way through the system. Imagine a customer edits their order price in the browser before it's sent. changing a $30 order to a $3 order. If our app doesn't check that data on the server, that change could slip through. R is for repudiation. Repudiation is about being able to deny your actions. Let's say a restaurant marks an order as handed over to driver, but the customer says it never arrived, and we have no delivery log or photo proof. There's no evidence either way, and that's a repudiation problem. There is no reliable trail. Next, I is for information disclosure. Now, this means leaking secrets. Maybe our error messages include customers addresses or payment info or we accidentally expose a full list of users in a public API. Even small leaks can be gold for attackers. D is for denial of service and at scale, distributed denial or service or DOS. And this is when someone floods your system so real users can't get through. A flood of fake orders can overwhelm the server and the app will crawl or crash and there's no food for anyone. And finally, E is for elevation of privilege. And this is when someone gets access that they shouldn't. Imagine a driver finds a hidden admin dashboard link and can suddenly issue refunds or give themselves a huge tip. And that's tried six letters that help you see where your app might be vulnerable before you even write a single line of code. So, in the next scrimm, we're going to try to put stride into practice with a few exercises. I'll see you there. In the last scrim, we looked at stride for the first time and how each of its letters stand for a threat that might happen to our food delivery app, Quickbite. Here in the Scriber editor, I've got stridechallenge.md open. You're going to see six potential threats for Quickbite listed out. And for each one, we're going to decide which stride category it belongs to and jot down a quick sentence of why. I've also popped the six stride threats down here in a markdown file for quick reference. So, we're going to work through the first one together. So, potential threat number one, thousands of fake orders slow the app to a crawl. Well, this one would be D, denial of service. And why? That's because it's a flood of requests that overwhelms the server. Basically, someone is spamming the system with junk traffic, so real customers can't get through. The server is too busy dealing with fake requests to handle real ones, and everyone goes hungry. And now it's your turn to give it a go with the remaining five potential threats. Take your time and fill it in just like I've done with example one. When you're done, we'll go through some possible answers. So, I'll catch you in a bit. Welcome back. How did you go? This is what I would have done. So, potential threat number two, a driver marks an order delivered but later insists that they didn't. Well, this one would be R for repudiation. And why? There is no audit trail to prove that any action was taken. Now, this one's all about being able to deny what you did. If we didn't log the delivery properly, there's no time stamp, there's no proof photo, there's no signature, there's no way to prove what actually happened. Both sides can point fingers and we're stuck. Okay. Number three, a driver discovers an admin dashboard link and can see all the current orders. Well, this one is definitely E for elevation of privilege. And why? Because a lower RO user has gained admin access. They've somehow stumbled into powers they were never meant to have, maybe through a hidden route or weak access control. And that is a classic privilege elevation issue. >> [snorts] >> Potential threat number four. A customer changes an order ID in the URL and views another person's receipt. Well, this one would be s spoofing. And why? They're pretending to be another user. By tweaking the URL, they're basically saying, "Hey, I'm user number 42 now." And if the app doesn't double check who's actually making that request, everyone can see everyone else's private information. Potential threat number five, an error message prints the customer's full address to the browser console. Well, this one will be D information disclosure. And why? Because of a simple leak of private data. This one is actually super common. Developers often forget that error messages can leak secrets. It may not seem like a big deal, but if your stack trace or debug info exposes personal data, you've just handed attackers some free intel. And finally, number six, a customer edits their total price to 30 cents before checkout. Now, this one is definitely T for tampering. And why? Because data is being modified before it is sent to the server. If we're not validating that number server side, we've basically said, sure, 30 cents for a full meal. Why not? Okay, if you've nailed them all, nice work. If you've mixed up a few, don't worry. The point isn't to memorize letters. It's learning to spot patterns and talk about risks in a clear way. In the next scrimm, we're going to flip the script a little bit. Instead of starting with threats like this, we're going to start with features and learn to spot what could go wrong before it ever does. I'll see you there. So far, we've looked at stride via the lens of what could go wrong, and then we've labeled those problems using the stride letters. Now, let's flip it because as developers, we don't usually start with a list of bad things. We start with a list of features. So, the next step to become more security-minded is to think of an extra question. What could go wrong with this feature? So, we're going to do exactly that with our student portal app from the first scrim. This one has been appropriated for a music school. Now, it allows students to upload practice recordings and for teachers to review them and provide feedback. Here in the editor, I've got feature threats.md open. You'll see feature one here for the student. I've also dropped a reference to stride down here at the bottom for easy access. So, for feature one, a student can log in and upload their weekly practice recording for their teacher to review. It sounds simple, but let's run through Stride and see what might go wrong. So, first is spoofing. Could one student pretend to be another student? Well, yeah, sure. Maybe they've got access to a friend's login and upload fake recordings in their name. So yes, spoofing is a potential threat. So let's pop it in. Someone logs in as another student and uploads fake files. Next, let's have a look at T for tampering. Could a student change data that they shouldn't? Maybe they can rename their file to overwrite another student's upload or they can intercept the request and change the file before it hits the server. So tampering is a potential threat as well. A student alters or overwrites another user's recording. Next is R for repudiation. Could a student do something and then deny it later. Imagine a student deletes their upload and says, "I definitely submitted it." If there's no log or timestamp, we can't prove who is right. So, repudiation joins our list of threats. A student deletes their upload and denies ever doing it. Moving on to information disclosure. Could a student's private data leak out? Maybe the video uploads to a public link or the file name includes the students full name and email. So absolutely information disclosure joins the ranks. Uploaded videos or names could be visible to others. Next, let's consider denial of service. Could someone stop the app from working? Sure, a few students could spam the upload feature with huge video files until the server runs out of space and no one can upload anything anymore. So, absolutely, students spam giant video files and slow the system. And finally, elevation of privilege. Could a student get powers they shouldn't have? And absolutely, a student could discover a hidden teacher page and view everyone's videos. And so, we have our sixth potential threat. A student accesses the teacher area. So, even with one simple feature, which is a student uploading a recording, we found examples for all six stride categories. And that's the mindset you want. Every time you design a feature, walk through those six questions and see what might come up. In the next grim, it's your turn to think like this, but from the teacher side. We'll look at how that side of things can bring their own security challenges. I'll see you there. Welcome back. We've already looked at the student feature together. So now we're going to switch perspectives. In the same feature threats file, you'll see that I added a second section for the teacher. So this time it's your turn. You can use what we just did with the student feature as a guide. And remember, the Stride reference is still sitting down here for you if you need it. Now, as for this feature, our teachers can log into the music school portal, review their students recordings, and leave feedback for each one. So, think about what could go wrong here. Run through each of the six stride letters and jot down a quick line for each if applicable. Once you're done, we'll compare notes. I'll catch you in a bit. All right, how did you go? Let's check out what might show up on the teacher side using our trusty Stride framework. So, first spoofing. Could someone pretend to be a teacher? That's definitely possible. If our login system isn't rock solid, a sneaky student could spoof a teacher account and leave feedback on their own video. Okay, next tampering. Could someone mess with data that they shouldn't? Well, maybe. Imagine a student intercepting a feedback request and tweaking the teacher's rating or comment before it is saved. Next up is repudiation. Could someone deny their actions later? Well, I think so. Picture this. A teacher edits or deletes a comment and then insists that they never did without any kind of audit trail or timestamp. We have zero proof. Next is information disclosure. Could private stuff leak out? Well, absolutely. Maybe the feedback page accidentally shows other students videos or the API could return way too much information. Up next is denial of service. Could someone jam the system? Sure. If multiple teachers all upload a lot of feedback files at once, the portal could slow down or even crash. And finally, elevation of privilege. Could someone get more access than they should? Oh, yes, always. Maybe a teacher finds a hidden admin page and then can suddenly see every single student's videos. And here we go. All six are applicable. Once again, even though it is a different role, we're still asking the same six questions. just pointing them to a new feature. And that's what makes Stride so powerful. It's flexible enough to apply anywhere in your system. And that stride is not just a checklist. It's a way of thinking before you even write a single line of code by walking through each feature and asking what could go wrong. You start designing with security in mind, not just bolting it on at the end. And that's the power of threat modeling. It helps you spot cracks early when they're still easy and relatively cheap to fix. But of course, once an app is live, new threats come into play. So, in the next scrim, we're going to shift gears. We're going to move from design time thinking to real world defense. And we'll do that with another industry classic. So, I will see you there. In the last few scrims, we looked at how to predict potential threats using Stride. That's all about design time thinking, spotting weak points before the app ever goes live. But what happens after launch? Once your app is out in the wild, it's no longer about what could go wrong. It's about what's going wrong right now and how we fix it. So, let's bring back our music school student portal. We've built it. We're using it. And everything is running smoothly. Students can even level up based on their weekly performance until one day that same curious seven-year-old pipes up in her lesson, "Miss, I'm level 10,000." And she's right. She'd realize that she could tweak the URL, resend the request, and boom, her level updated in the system. No hacking tools, no special access, just Curiosity and a browser. And that's the moment we go from design time prediction to runtime reality. When your app is live, you need a new kind of map. One that helps you recognize, prioritize, and respond to real security risks. And that is when OWASP comes in. OWASP stands for the Open Web Application Security Project and is a global nonprofit foundation that works to improve the security of software. Their website is an absolute treasure trove of resources, guides, cheat sheets, testing tools, community projects, all aimed at helping developers understand how attackers think and how to build apps that can stand up to them. Now, one of their most famous projects is the OWASP top 10. Basically, the greatest hits of web vulnerabilities that developers keep accidentally releasing. It's updated every few years and is built from huge amounts of real world data, industry reports, community feedback, and security testing across thousands of applications. And what comes out is a ranked list of the 10 most critical security risks seen in the wild. And each one isn't just a label. It comes with background information, examples, and practical advice on how to detect and mitigate those risks. So, let's think about our 7-year-old hacker who managed to change their level using just a URL. What OASP category will this fall under? Well, the clearest one is the first one, broken access control. The app didn't check whether the student was allowed to perform that action. They could change their own level simply by tweaking the URL. And that's exactly what broken access control looks like in real life. Someone doing something that the system should have stopped. Now, technically, this little student hacker could touch a few other OWASP categories, too. It's also an example of insecure design because the feature itself was never built with RO limits in mind. Why would we let a student's level be changed with just a URL? It might also fall under security misconfiguration if the route that updates a level was left open to everyone instead of just teachers or admins. And you can even argue authentication failures if the app never doublech checked who was making the request in the first place. As you can see, real vulnerabilities rarely fit neatly into one box. And that's why OASP gives us language to describe the different angles of what went wrong. But now you're probably thinking, hm, so what? I can name the issue, but how is that going to help? Well, that's where OASP really shines. Here is that main OWASP top 10 page. Again, you can click into any of these categories to learn more about it. Things like what it means, how it happens, and most importantly, how to now stop it. Let's have a look at the broken access control page to fix our problem. Right here under description, we can confirm that this is the problem that we're encountering. Access control enforces policy such that users cannot act outside of their intended permissions. This is exactly what went wrong for us. And if you scroll down a little bit, you'll hit my personal favorite section, how to prevent. And this is where OWOSP turns theory into action, such as denying access by default, along with a ton of other actionable points. In other words, it's not just don't do this. It's a readymade checklist that you can actually apply. And that's the goal right there because once you can name a vulnerability, OASP tells you how to fix it. In the next Grim, you'll get to play bug triage. You'll see short realworld inspired bug reports and your challenge will be to match each one to its OWASP top 10 category. I'll see you there. Welcome back. In the last groom, we met OASP and explored their top 10. These greatest hits of web vulnerabilities that keep sneaking into production apps. We also saw how our little 7-year-old hacker accidentally uncovered a case of broken access control and how OASP didn't just name the problem, it actually showed us how to fix it. So, let's put our new OASP top 10 knowledge into practice by jumping back into QuickBite. Now, QuickBite has grown quite a bit since we last saw it. There is now a restaurant role where restaurants can manage menus, pricings, and order windows. We've also integrated an external payment gateway to handle card details and payments. And to make sure that deliveries can be tracked in real time, we've added a maps API so everyone can keep an eye on everyone else. You can probably guess what that means for security. With new things in the mix, we've multiplied the places where things can go wrong. And that is the perfect playground for our OWASP top 10 bug triage. Here in the Scriber editor, I've got OWOSp example.m MD open. And here we have a short bug report example. It is our job to figure out which OWAP top 10 best fits this bug and how we should go about fixing it. I've also dropped a quick reference markdown file down here with our top 10. There is also a link directly to the OWOp top 10 website. So, think of this as a developer treasure hunt. You've got this bug in hand and you've got OOWSP as your guide and you're hunting for how to patch it. So, let's do this example together. Customer passwords are being stored in plain text in the database. Well, a quick skim through number one, broken access control and number two, cryptographic failures will tell us that this would be an example of cryptographic failures. Our app isn't properly protecting sensitive data. So, let's pop that in really quickly. cryptographic failures. Then we'd hop on over to the cryptographic failures page, scroll down to the how to prevent section, and check out what we can do about it. Now, this one is pretty straightforward. OASP tells us to encrypt all sensitive data at rest, which is just a fancy way of saying scramble or hash passwords before storing so they can't be read directly. And that's it. One bug recognized with a potential fix. We've identified the problem, matched it to an OWAP top 10 category, and looked up a simple, practical fix straight from the source. In the next scrimm, you're going to take on a few more quick bite bugs yourself, realistic ones that touch different parts of this new app. I'll meet you there for the full triage session. Welcome back. Here in the Scriber editor, I've got owasp challenge.md open. You'll see a handful of new quick bite bug reports, and each one describes a real problem that you will see in a real life system. Now, your challenge is as follows. For each bug, figure out which OWASP top 10 category it fits to, and then find one simple fix from the how to prevent section on the OWASP website. Now, remember, the goal isn't to memorize the top 10. it is to practice thinking like a securityaware developer. If you can identify what type of problem it is, OASP will show you how to fix it. So, as always, I've popped a quick reference down here as well as the link to the top 10 website. Remember to take your time. There is no rush. Once you filled out all the bugs, come back and we'll go through them together. Welcome back. I hope your bug triage was insightful and enlightening. This is what I would have done, but remember yours don't have to match mine word for word. For me, I went through the OWASP docs for each of these to make sure that the fixes line up with what's recommended, but I will keep it simple here so we're not just reading documentation together. So, the first one is that restaurant uploaded a file called menu.js instead of an image and it actually ran when someone opened it. Now, this is security misconfiguration. Our server is treating uploads like code instead of plain files. We can fix this by only letting users upload image types and keeping those files somewhere where systems can't accidentally run them. Next up, a driver changed the order ID in the URL. I could see another customer's order details. Now, this is broken access control. The app didn't double check who was asking. For this, we'll need to make sure that the backend always verifies that the person requesting an order actually owns that order. Next, any loggedin user can open/admin/ord orders and see restaurant dashboards. Well, this one is yet again broken access control. Hidden links are never enough. The server needs to confirm that only admins can open certain pages. If you're not an admin, you should see a nope message instead. Okay, moving on. Payment web hooks are coming in with fake paid statuses because we're not verifying where the request is coming from. Now, this one is software and data integrity failures. Our app believed whatever it was told. We can fix this by checking that messages really come from our payment provider, not from someone just pretending to be our payment provider. Moving along, login form is still using plain HTTP and credentials show up in clear text in the network tab. Now, this is another cryptographic failures case. If the page isn't using HTTPS, passwords can be seen by anyone watching the traffic. And so, the fix is to always use HTTPS everywhere, especially for login. And finally, logs are printing full card numbers and addresses whenever a payment fails. Now, that is security logging and monitoring failures. We should only log what's necessary and blur or hide anything that's private, like showing just the last few digits of a card. So, that's our OASP triage done. Now, remember, it's not about memorizing the list. It's about spotting patterns and knowing the kind of fix that would make sense. If you can name the problem, OWASP will point you straight to the right solution. So now you've seen both sides, predicting the problems with stride and spotting the real ones with OWASP. In the next scrimm, we're going to zoom out and look at how these two frameworks work together. I'll see you there. All right, we've come full circle. We started with stride, learning how to predict what could go wrong while we're still designing our app. And then we met OWASP, learning how to recognize and fix what's actually gone wrong once the app is live. Now, let's zoom out and see how these two fit together. Stride lives in the design phase, and OASP lives in the runtime phase. When you're sketching diagrams and planning features, Stride helps you ask what could go wrong. And when the app is real and users are using it, OASP helps you determine what actually went wrong. Stride helps you build with security in mind, while OOWASP helps you defend and respond when those ideas meet the real world. And Stride asks, "How do we prevent someone from breaking something?" And OWASP asks, "How do I prevent someone from breaking it again?" Picture the software life cycle like this timeline. Stride fits in early during the design and planning, and OASP kicks in after launch when bugs and exploits start to appear. and together they cover both ends of the security story. Let's take QuickBite as an example where a user was able to view another user's receipts. If we had used Stride early on, we might have spotted that URL parameter change issue before it happened. It's a clear case of spoofing or tampering. But once the app went live and that same bug started leaking customer receipts, OASP would step in with a label, broken access control, plus a checklist of how to fix it. Let's also have a look at our music school student portal example and our level 10,000 student. If we had applied stride during design, we might have caught that feature where students can level up and realize it needed tighter roll checks, a classic elevation of privilege risk. But once that app went live and our 7-year-old hacker discovered she could boost her own level, that became an OWASP broken access control issue in the wild. Stride would have warned us before launch and OWASP can now help us understand it afterwards. And that's how they connect. Stride predicts and OWASP diagnoses. And that's your picture of threat modeling from design time to runtime, from prediction to prevention. Congratulations, you finished this section on how to think like a security-minded developer. Throughout the section, we learned about these two things. Using Stride to predict design time threats and using the OWASP top 10 to recognize real world vulnerabilities. Together, these tools train you to think in both directions, to design defensively before problems appear and to spot warning signs when they do. Think like an attacker and design like a defender. Keep this mindset with you as you build. every line of code, every feature choice, every API call, ask yourself, what could go wrong and how can I prevent it? And that's how you think like a security-minded developer. Hey, and welcome to the section on cyber security, one of the most important skills you can develop as a modern web developer. No matter how polished your app looks or how smooth your UX feels, it only takes one vulnerability for things to go wrong. Data leaks, broken login, spam attacks, they all happen because someone didn't stop to think like a security-minded developer. And this is what this section is all about. Spotting the weak points and handling them. We'll start by learning to think defensively using frameworks like Stride and Oasp. You'll learn to predict potential threats early in design and then recognize the most common vulnerabilities in real world systems. Then we'll switch gears and look at rate limiting and throttling, the practical side of protection. You'll understand and build mechanisms that keep APIs stable, prevent abuse, and handle traffic spikes gracefully, all while keeping your genuine users happy. By the end of the section, you won't just know what to protect, you'll understand how and why. you'll be thinking like a true security-minded developer. All right, let's dive in. >> Welcome to this course on input and data safety. I'm Jonathan Hill. Everyday applications process billions of user inputs, usernames, passwords, email addresses, comments, search queries. These interactions are the lifeblood of modern web applications. but they also represent the primary attack surface for malicious actors. In this course, we're going to be considering a basic registration form. A few input fields, a submit button, seemingly pretty straightforward. Yet, this simple interface can be exploited in devastating ways. An attacker could inject malicious scripts that steal other users session data. They could manipulate database queries to access or delete sensitive information. They could flood your server with requests until it crashes. These aren't hypothetical scenarios. They happen constantly to applications that haven't implemented proper input safety measures. So, the fundamental problem is trusting user input. The single biggest mistake developers make is treating user input as safe data. When you accept input from a form and use it directly, whether displaying on a page, inserting it into a database, or processing it in your application logic, you're essentially allowing users to control parts of your application's behavior. Most users are perfectly harmless, but it only takes one malicious actor to compromise your entire system, steal user data, or take your application offline. In this course, we're going to use a registration form as a working example to explore the most critical input safety vulnerabilities and their solutions. These are going to be cross-sight scripting, how attackers insert malicious code through input fields, denial of service, how attackers can overwhelm your application, and SQL injection, how attackers manipulate database queries through input fields. And then for validation, we're going to learn all about this ZOD library, which is how to enforce data integrity and business rules on the back end. These all contribute to defense in depth. You'll learn that security isn't about implementing one perfect solution. It's about creating multiple layers of protection. If one defense fails, others are there to prevent the attack from succeeding. That's enough from me. Let's go. Welcome to this form project. We're starting with a basic front-end form using HTML and TypeScript. And we're going to be investigating its various vulnerabilities before learning how to use and implement a validation library, ZOD, to validate all of the fields against a schema that we're going to be writing. Let me talk through what we have so far. Since we want to focus our time on the vulnerabilities and the eventual solution, I'm just going to briefly touch on how we are currently set up. So, you can see in the mini browser this front end registration form. We've got a front end and a backend folder. We're going to start with the front end and index html is just our standard HTML form. We've got a few containers for validation, success messages, error messages, submit button, all the usual stuff. Now, if you think back to when you learned about HTML forms, you may remember that they have a default built-in HTML 5 validation. And this can block submission of the form before it reaches the back end. So things like required on an input and type text or type email, these are all part of the HTML 5 validation. type email for instance. This specifies the email type and it validates the input against a well-formed email address pattern. But a malicious user can bypass HTML 5 validation pretty easily. They can disable JavaScript or even use the developer tools. So if we rely on HTML 5 validation for all of our validation, our server could have no protection. So in this course we're going to be learning about this validation library ZOD which can validate on both the front end and the back end with the same code. Side note we will actually be focusing mainly on the back end. Other benefits of using a library like this and not the HTML 5 validation is we have better control over the error messages. We don't have to rely on the HTML 5 generic ones. HTML 5 is also quite limited. Libraries like Zod can handle complex business logic and it means we have a single source of truth. Instead of validation logic being scattered between HTML attributes and JavaScript, we're going to have everything in one place in our Zod schema. So you may guess I'm leading up to the fact we're going to disable the HTML 5 validation. So we sort of start from scratch. And I'm going to do that on the form. And I'm just going to write no validate there. Okay, that's enough about this file. So app.ts, ts. This is our browser logic. It reads the form inputs, posts to the back end, manages loading state, and shows success or error messages. Here's display success. We've got set loading handle submit. Here's getting the form data. Here's our fetch post. And we're currently configured with this / API/register vulnerable endpoint. This is the one that's set up right now. And on purpose, I've made it very vulnerable. not something we'd ever use in production. As we go through the course, we're going to create a new endpoint which is going to be much more secure. Now, types.ts. This mirrors the backend types for the client. We've got register request, we've got register response, and validation error. These are used in app.ts. So, we can see at the top we're importing them. And then we have validation error here in display errors. We've got register response in display success. And down here we've got register request. So types.ts here provides type safety for the API responses. We also get IDE autocomplete and it's good for API contract documentation. There's a store folder here. This is where our TS files are being compiled into JS files. It's same for the back end. We have a store folder there. Okay. Onto the back end. Server.ts. This boots the Express app, enables JSON passing and permissive calls, mounts roots from /root/orth, and exposes health endpoints. It includes a global error and 404 handlers and starts the server on port 3000. In roots, we've got orth. This is where that endpoint is /register vulnerable. It's deliberately skipping any validation, echoing raw user input to demonstrate some of the vulnerabilities we're going to be talking about soon. And then the state folder. This includes mock DB. This is a mock database of a user count. There isn't actually any database here. This is just so at the top of our front end, we have this user count that is going to increment as we use the form. Let me just quickly show you that. I wish I was 18 again. There we go. And now it's gone up one from 393 to 394. Now, a quick note on how we're running back end and front end at the same time. The back end is a node app using express and the runner here is running the backend server. I have the runner set up. So when I save a file, it's going to recompile the backend folder and start the server. So if I save this index.html, we'll see in the mini browser goes to 3000. And that means that in the terminal here is where I'm running a lightweight front-end server, http-server. So I go Ctrl C. That just closes it. And I have a nice script in package.json dev. This is going to run TSC on the front end folder and start the front end server. Let me show you that. MPM rundev. And we're back up and running. You're going to be having to restart servers later when you do challenges, but I'm going to remind you then about how to do it. So no need to remember or make a note. I hope that made sense. Do pause the video and have a look through the code yourself and let's get cracking with the rest of the course. Our first vulnerability is cross-sight scripting or XSS. This is when malicious script is injected into a trusted website to run on the victim's browser. XSS has been around since around 1999, and you know it's a big deal when it's number one impactful attack from the X-Force Cloud Threat Landscape Report of 2024. Gosh. So, a bad guy on the left here injects some code into a trusted website at the top. The victim visits the website, could be a comment section, and by interacting with it, executes the code in their browser. The important thing here is that it runs under the context of the website. And since the end user's browser has no way of knowing that the script should not be trusted, it will execute that script. So potential outcomes could be the site served for the victim is defaced. It's rewritten the content of the HTML page and this could easily make them do something they shouldn't do. Sensitive info in the form of cookies could be transferred so there's a hijacking. Malware could be transferred to the victim or the victim could be redirected to another site for a fishing campaign and then data sent to the bad guy. If we think back to where this all started, the user input in the website, we need to learn to not trust user input. We must validate inputs, inspect, and potentially reject. OASP have a great cross-sight scripting prevention cheat sheet that I've linked here. I recommend you bookmark it for the future. So, our form project here. Let's get the front end running with mpm rundev. This is what you're going to be doing in a minute. Here we go. And let me just show you whatever name we put into the name field. We submit. And that name is going to be rendered in the success message. So, if we look in app.ts in the frontend folder, we see display success. Here's that message taking the response do user.name name and using text content to render that. But here is why returning user input directly is dangerous. Text content treats everything as plain text. So it's nice and secure. But in another scenario, we may be using inner HTML instead. This passes the HTML and executes any code that is in here. Let's add some comments. So text content is safe. any script is escaped, but inner HTML is vulnerable. Script executes. Let me demo that. So, I've got a little script here that I wrote earlier. Let me put it as a comment so you can see the whole thing. It's an im tag with an on error. So, let me save first. I'm going to stop the server and restart it and then see what happens when I submit this in the name field. All blimey data breach excss successful. So this is only a demo. Don't worry, nothing bad has really happened. So that just shows us the issue with executing user inputed scripts. So it's going to be your challenge now in the next scrim. Have a quick look at these comments. I'm going to delete them in a second. They are going to help you. Great. See you in the next scrim. Okay, it's challenge time. So this is what I'd like you to do. As the challenge starts, you're probably going to have to start the front end in terminal with mpm rundev. And then I want you to copy in these name inputs and see what they do. So we've got a div, we've got an SVG, and we've got an I frame. So you be copying them into the name input and then submitting the form and looking below the submit button for that success message. Then in app.ts, here we are. Change the way the success message is being rendered. So the injected script is escaped rather than ran. We need to change this part here. Save this file. That will recompile the back end. Then you need to go into terminal, restart the front end. So you may need to control C to stop it. And then npm rundev again. And then test with these same scripts the form to check that the behavior has changed and nothing bad is happening that all of these are just being rendered as text. All right, good luck. See you in a minute. Hope that was all right. So I'm going to go into terminal and run npm rundev. Nice. So let me see what happens maybe with the i frame. So we go into name, paste it in, and ooh we get this big excss attack. So we need to change this inner HTML to text content. There we go. But that means that the text is going to be rendered as plain text and the script is not going to be executed. So we now save. Then we need to stop this server. MPM rundev to restart it. And let's try the iframe again. We should get different behavior. There we go. You see the plain text rendered rather than the actual I frame with that message. Brilliant. So this was an example when we're rendering part of the code that has been inputed. But remember, inputed data is going to be potentially sent to a database and may be rendered later, maybe in an admin panel or in an email template. So it's not just the front end that shouldn't trust any inputs. The back end also shouldn't trust inputs. Other consumers of the API may render it unsafeely. All right. Well done. Onwards. The next vulnerability to talk about is the denial of service. This is generally an attack on the availability of a system. So there are a few types of DOS. The first one is a magic bullet, sometimes called a ninja attack, a very targeted attack when a bad guy on the left here writes a specially crafted message taking advantage of a rule he'll violate in the protocol. Could be a buffer overflow when you send more info than expected which makes the system go down. The next type would be a volume based attack. This saturates the bandwidth without length limits. Maybe an attacker could send an extremely large input that exhausts server resources causing a denial of service. So a quick example here is in the name field they could use a repeat 10 million. So the database would fill up quickly, queries would slow down, storage costs would spike and backups would become huge. The next type is protocol attacks. These exploit weaknesses in network protocols to use up server resources like connection tables. An example could be a sin flood. This exploits the handshake process of a TCP connection. Under normal conditions, TCP connections exhibit three distinct processes in order to make a connection. Everything starts out well with the bad guy sending a sin packet. The problem is the address they've included that should be their address is a fake address. That means when the system continues the handshake and sends a sin a it goes to the wrong place. This is an unexpected system at the bottom here. At this point the system starts a timer and starts using resources. Normally the system that receives the synac should then send one back completing the three processes. But because they're totally unaware, they do not send anything back, meaning that the server resources continue to be taken up. The bad guy then sends another SIM packet with another fake address. This goes somewhere else and another timer is started using even more resources. This continues until the service goes down. So the handshake is never completed, leaving the server stuck with these halfopen connections. We can call this a type of death by a thousand cuts attack strategy. And one of these death by a thousand cut attack types taken to another level is the DDoS, distributed denial of service. This is using botn nets or sometimes called zombies. It starts with a user here on the right accessing a system absolutely fine. A bad guy on the left starts taking over systems. They could be doing this using malware or hacking into them, building an army of unsuspecting users. This is the botnet or zombies. Then when the bad guy wants to start the attack, they send a message to these systems that he's taken over and they start to bombard the victim system with traffic. So these botn nets coordinate many infected computers to send attack traffic from multiple sources, making it hard to defend against. Hence why it's called a distributed attack coming from lots of places. And this can potentially cause the server or network to become overwhelmed resulting in a denial of service to normal traffic. And because each body is a legitimate internet device, separating the attack traffic from normal traffic can be very difficult. So what can we do about this? Ideally, we'd have infinite capacity, but that's not really feasible, is it? So redundancy and the rule of three multiple instances or backups of critical system components to maintain availability if one fails or becomes overwhelmed. That's three servers, three data centers, three network paths, three DNS servers, etc. One can fail due to an attack or a hardware failure. One can be under attack and hopefully one remains available to serve legitimate traffic. Rate limiting and throttling. This is controlling how much and how fast. It limits the volume or frequency of requests. For example, maybe a maximum of a 100 API calls per minute or no more than five login attempts in 10 minutes. Maybe limiting bandwidth throttling to 1 megabyte a second. Filtering is controlling what, who, and from where. It examines and blocks or allows based on content, source, or other criteria. For example, blocking traffic from specific IP addresses or countries, rejecting requests with malicious payloads like SQL injection or XSS, allowing only authenticated users, or finally blocking requests based on user agent or headers. Hardening is removing unnecessary services, reducing the attack surface of a system. The idea is that every service running is a potential vulnerability. We may have to remove default accounts like default admin users, disable accounts for people who no longer work at the company, and ensuring no unnecessarily privileged accounts exist because attackers can exploit leftover or default credentials. Patching is always using the latest software. Software always has bugs, doesn't it? And some of those bugs are security vulnerabilities, flaws that attackers can exploit to gain access, escalate privileges, crash systems, steal data, etc. When a vulnerability is discovered, the software vendor releases a patch. Essentially, a fix that closes that hole. Patching is the process of applying those fixes. Monitoring means continuously watching your system so you know what normal looks like. That means you can then spot when something abnormal is happening. You always need a baseline of normal activity so you can recognize anomalies. For example, if your server normally gets a thousand requests per hour and suddenly gets a 100,000, that's a big red flag. But you'd only know that if you'd been monitoring normal behavior first. And finally, incident response, security, orchestration, automation, and response saw. We really need dynamic playbooks so that we can respond quickly to threats. Fantastic. See you in the next scrim. Our last vulnerability is SQL injection. Inserting malicious code into database queries. So yes, this attack consists of inserting or injection of a SQL query via the input data from the client to the application. There we are. It's due to poorly sanitized data, and the result could be reading sensitive data, modifying data from the database, executing admin operations on the database, such as potentially shutting down the DBMS, and in some cases, issuing commands to the operating system. So, here's an example of a SQL query. This could be from a login form. We're all very used to login forms these days. So this says select all which is the star from a fictitious users table where username equals whatever has been inputed in the username field and the password is whatever the password has been inputed. So a legitimate login checks if a row exists where both the username and the password match. If a row is returned, the credentials are valid and it grants access. But if no row is returned, the credentials are invalid and it denies access. But a bad guy could potentially add something like this into the username field. Inverted comma or one equals 1- dash. So this would be added where the dollar username is here. So it would create this complete query. Here's the first inverted comma. And then we would sort of close that inverted comma with the first from the username. Then we'd have or which is a SQL special word. and then 1= 1 then the dash dash. So the single quote closes the username string early. We know that 1= 1 always evaluates to true. So this makes the whole wear clause evaluate to true and the dash dash in SQL starts a comment. So anything after the dash essentially becomes irrelevant. So this would then potentially return all of the users from the user table logging the bad guy and bypassing the authentication check. Okay. Okay, in the next scrimm you're going to play the part of the bad guy. I'm going to get you to come up with something to insert into a SQL command to delete all the records from a fictitious table. See you then. Welcome back. So, still on the topic of SQL injection, if we could imagine a registration form that's taking a name and an email and inserting it into a users table, we can imagine a SQL template could be set up a bit like this at the top. Insert into users into the name column and email column with the values of whatever they've inputed as name and whatever they've inputed as email. So, I want you to think, what could a bad guy submit in the email field to do some real damage? say to delete or in SQL terminology drop this whole user's table. I want you to have a go at crafting an input which would drop the user's table. You might want to have a look up what the SQL command for dropping a table is. This is just a bit of fun to get you into the right mindset. It's going to be going in here where dollar curly email curly is. So you might want to think about the syntax that we used here. We had a single quote, didn't we, to close this single quote here. So, you may need one to close this single quote. And then you'll be in a bracket, won't you? So, you may want to close that bracket and then think about what indicates we're stopping one SQL query and starting a new one because we may want to make the system think that we're stopping this one and then starting our new malicious dropping the table command. and then think what we had at the end of this one to make sure that anything after that would be taken as a comment. So I've got the challenge text here for you. I'm just going to put it at the top. So you'll need to start the front end in terminal by running npm rundev. You should then see the form on the right in the mini browser. Then I want you to write an input for the email address field which would drop the users table. Assume that the SQL template is this. You can write it in the email field. submit the form and then check the runner terminal. Now I've set this up so you will actually see the full query in the runner terminal. Let me show you that. So if I run mpm rundeendev and I add daved.com and I submit this form and we look in the runner terminal. There you go. It says vulnerable executing query and that daved.com has been added or inserted or injected in here, hasn't it? So you can keep modifying your malicious email address by looking here and saying, "Oh, I need to change something so that we potentially close the single quote, close off this bracket, finish this SQL command, and then start a new malicious one." And I also have this set up that if you do manage to fictitiously drop the table, you will get told you've managed to do it in the runner terminal. Don't worry if you don't manage it. I'll go through it all in a minute. Okay, good luck. See you in a minute. Okay, hope that was all right. So, back to this slide. As I said, I think we're going to need to use a single quote. We're going to have to close off this bracket. We're then going to use something that stops a SQL query, which is a semicolon. So, here we have it. single quote smooth bracket semicolon and then the command drop table users. Then I've got another semicolon to finish that command and I've used dash dash in case there was anything after it which would be then taken as a comment. So the total command would be this. Here's my inserted code. Let's give that a go, shall we? So in email address, I add that and I submit. And let's have a look in the runner. Disaster dropping users table. And if we look at the top of our form, it says we currently have zero signed in users. So that's just a bit of fun that I've set up. Manually hardcoded it so that we go back to zero. Don't fret. Nothing has actually been deleted. All right. Well done. So how can we stop this happening? Well, we've seen that when we build queries by concatenating strings, the database can't tell what's supposed to be SQL code versus what's supposed to be data. Anything we enter becomes part of the SQL command. But there are ways to safely handle user input in SQL queries by keeping the query structure separate from the data. So using prepared statements with variable binding, aka parameterized queries, is the way to go. They're simple to write and easier to understand than dynamic queries. and parameterized queries force the developer to define all SQL code first and pass in each parameter to the query later. So here are my parameters. This is just an example. I've got rec.body username. Assign that to username and the password to password. And here's the query structure I'm defining. I've used placeholders here, question mark and question mark. This will depend on the language and library you're using. So the syntax could be different depending on the type of database or the SQL type or potentially if you're using an OM. We pass the data separately. So here's username and password from up here. And then the database driver handles escaping. So it knows the structure is fixed and treats parameters as pure data, not executable code. Prepared statements ensure that an attacker cannot change the intent of a query even if SQL commands are inserted by an attacker. So if username here was that one equals 1 example, it would be treated as a literal username to search for in the database which as you can imagine would come away with nothing because there's not going to be a username as inverted comma or one equals 1- dash. So parameterized queries are defense at the database layer. In real life, you can have front-end HTML 5 validation. And then what we're about to talk about is ZOD middleware input validation and sanitization. And then finally, database layer prepared statements. And just before we finish this scrim, OMS can handle parameterization automatically. So that's another plus point for OMS. All right, see you in the next scrim. Welcome. Let me introduce you to Zod. The docs describe it as a TypeScript first schema validation library with static type inference. They have zero external dependencies. It works in Node.js and all modern browsers. It's tiny, installs really fast. It's an immutable API. We're going to see what this means later. It means that methods return a new instance. It's a really concise interface. The method names are really short. They're chainable. It's declarative, meaning you describe what you want, not how to check it. And there's no boilerplate code. No need for lots of if statements and error throwing. It works with TypeScript, as I said, and plainJS. And there is an extensive ecosystem. So, if you click on this link, you'll go to their ecosystems page. There really is a thriving ecosystem of libraries, tools, and integrations. So, you'll see a complete list that support Zod or built on top of it. Speaking of their docs, you're going to be needing these for challenges later. So, I really recommend clicking this link and having a new tab open and checking out the basics and all about schemas and errors, etc. Right, that's a good start. Let's get our hands on the keyboard and actually use Zod. See you in a minute. Now that we know what ZOD is, let's learn how to use it in practice. Here I have just a simple TypeScript VIT project and I'm going to install ZOD with npm ZOD. It's such a small package that it's going to install incredibly quickly. And then I'm going to import it in this main.ts ts at the top using import star as z or zed from zod. There we go. Now, it's probably going to be set anyway, but in tsconfig.json, we just need to check that strict is true, and it is. So, to validate data, we must first define a schema. Schemas represent types, and they can be simple primitive values. You probably saw some of these in the Zod docs to complex nested objects and arrays. I'm going to show you first and then we're going to dive a bit deeper into what a schema is later on. So define schema. And to do that, we just need to decide on a name. I'm going to go for teacher schema. And we then use the zed that we've imported here. We then decide on the method to call against zed. Now the simplest would be zed dot string. and then we have some smooth brackets. This is like the rule that all the data we're going to try and validate through the schema needs to follow if the validation is going to be successful, the data valid. I like to think of validating data a little bit like an airport scanner where you have your bag or the data to pass through the machine. The machine has been set up with certain rules like no knives or no liquid of a certain size and if everything's okay, the data just goes through and comes out the other side of the machine. But if it's failed some of the rules or your bag is not in the format that was expected, the machine errors and your bag or the data doesn't make its way all the way through the machine. You'll see in a second why I'm talking about going through the machine and coming out the other side. So let me write here machine set with rule. And this is saying the rule is everything has to be a string. But you probably saw in the docs you could use Z dot number, you could use Z dot boolean. Let's stick to string for now. Now we need to say what is the data that we're going to be passing through the machine. So let me just make a const. Let's go for teacher and let's go for me Jonathan. So the syntax when we're going to validate against the schema and that's the wording we're going to be using. So to pass the data through the machine, we go schema name and this is just pseudo code by the way. and we use dotpass and then in smooth brackets we go for data to validate and then the return of this it's the validated data. So you can imagine the bag has gone through the machine and comes down the ramp the other side all good but if not this is going to throw an error. [clears throat] So let's do it. What's our schema name? teacher schema and we use pass and in smooth brackets we put the data which is just the const teacher. There we go. So this is going to return what we have on this line. So because teacher is a string should be all good. Let's find out. Let's console log this line. There we go. And I control or command s bring up the console and we have a string Jonathan. So there we go. [clears throat] It's returned the validated data. Let's see if I can break this. So, what if I turn this into some numbers. Save it again. And the data is not there anymore. The machine is gone. Error. Error. We have an uncaught zod error. We've got a few properties in an object here. Expected string code invalid type path nothing path message invalid input expected string received number. That's quite helpful. Okay. But I guess if we change the rules of the machine and we change this to Z number and the actual data we're passing through the machine is a number, we should get the number back. The bag or the data has gone through the machine, been scanned. Yes, this is what I was expecting and it comes down the ramp. Fantastic. All right, see you in the next screen where we're going to build this out into an object. See you then. Welcome back. So, a teacher might not just be their name. They could have other properties. So, let's turn this into an object with a name property. And let's go for an age property. Now, regardless of how usethful I sound, sadly, I'm not 21, but for now, let's imagine I am. There we go. So, our data now is an object with two properties. So we're changing what we're putting through our validation machine, but the settings of the machine is still expecting just a direct string. So to tell the ZOD machine that we're expecting an object, we're not going to use Z.string. We're going to use Z.object. And we have the smooth brackets again. And in the smooth brackets, we place the object that we are expecting that we're happy with. So we're going to have a name key. Now these in Zod are called keys and an age key. And then we put the Z dot string here. And for the age, because it's going to be a number, we're going to go for Z dot number. I really recommend looking at all the primitive types that you can have in ZOD in the ZOD docs. So now the settings of the machine has changed. The machine is going to allow an object with a name property, which is any string you want, and an age property, which is any number you want. And this is the data we're putting through the machine which should satisfy that validation. So we save, bring up the console, and yes, here's that data that is returned if it's successful. But if I changed the age to the string 21 and saved, what are we going to be expecting? Yes, an error. That zod error. I save. Boom. Uncaught zod error. Expected number received string. Okay, that's back to where it was. So, a little more about schemas. Now, I mentioned they represent types. Well, in Zod, a schema is essentially a runtime representation of a TypeScript type. If you think about it, this does look a little bit like a type in Typescript. And we're going to be showing you how we can infer a TypeScript type from a schema a little later. So, this schema describes the structure and constraints of the data that we're going to allow. So this is saying this should be a string and this should be a number. We're going to be adding on to these saying for instance the number needs to be positive or needs to be smaller than x. But the neat thing about zod schemas are that they're different from Typescript static types because Typescript's types are erased at runtime. Zod schemas exist at runtime and can actually validate data coming from external sources like APIs or user input. So in Typescript at development here we have the TypeScript type a user type and the type checking works in development. But when Typescript compiles the TS file and when we run TSC compile into A.js file all the type annotations are completely removed. There's no validation. For instance that string annotation vanishes at runtime. There's no way to check if the data matches the TypeScript type. If an API returns unexpected data, your app can't catch it. Typescript only helps you during development. TypeScript assumes your data is correct. Zod, however, actually checks the data. So in development, here is our TS file and our user schema. We define the schema and then when in runtime we run TSC compile, the schema still exists. The data is validated. Zod will throw an error or lets you handle validation failures gracefully. And many developers in the wild use both ZOD for runtime validation and extracting TypeScript types from the schema, giving you both compile time and runtime safety. And as I mentioned, we're going to be talking about extracting the TypeScript types from the schema very shortly. Okay, it's been a while since you've had a go. I've got a challenge for you. It's essentially just recreating what I did earlier in the scrim, but that's no bad thing, is it? So, I want you to create a student schema with the following keys. Name, which is a string, and is pro, which is a boolean. Then, I want you to define a student object with madeup values for the following properties, name and is pro. So, you could just do yourself or anybody you want. And then validate the student against the student schema. Now, I've kept the comment here to help you with the syntax since it's the first time you're doing it and log the result to the console. So, I think what you're going to need because there's two keys here for the schema, you're going to need to use Z something that's going to enable you to have two keys. All right, good luck. Just have a look earlier in the scrim if you need to and use those Zod docs. See you in a minute. Okay, I hope that went well. So we've got const student schema and this is going to be Z dot and we need object and then we go curies and we have name and is pro keys. The name we've said is a string. So we need Z.string and is pro is going to be a boolean. So this is Z dot boolean. There we go. That's number one done. Number two, we need a student object. And this is going to have name property and is pro property. Name. Let me go for well, we're all still students, aren't we? All still learning. So, let's go for me. And is pro. I'm going to be bold and go for true. Now, to validate the student against the student schema, we need this syntax. So, we need schema name, which is student schema.path pass and then smooth brackets the data to validate is student and then let's check by console logging. We save and there's the data. So yes, that's all good. The machine has been set up wanting an object with a string any string for the name property and any boolean for his pro and we gave that here. But if I change true to the string true and I save, we get the zod error. Fantastic. See you in the next scrimm. Let's see how much you remember. I'd like you to import Zod at the top of this file. Then create a character schema with two keys. Name, which is a string, and episode, which is a number. So that would be like calibrating our machine. And then the data that's going to go through the machine. I'd like a character object with the following properties. name which is going to be the string Luke Skywalker and an episode property which is the number four. Now before you come at me this is the first time Luke Skywalker appears in the films episode 4 and then validate the character against the character schema which means put the data through the machine and log the results to the console. You can then command or control S and check in the console to see if you're seeing the data i.e. validation is all good or you're seeing the ZOD error and the machine has a problem. If you're not quite sure of the syntax, use the ZOD docs, please do. Good luck. See you in a minute. Okay, at the top, let's import Zod. So, we've got import star as Zed from Zod. That's number one done. Create a character schema. So we're going to go const and the name of the schema is character schema and then because there are two keys to this we need an object and to make an object we use z.object smooth brackets after that method and then we pass to it the object that we are going to be satisfied with which has got a name key and an episode key and the name is a string. So we go for our z dot string and episode is a number. So we go Z dot number. That's number two. Number three, define a character object. So we go const character. Open the object up with the curies. Name property and episode property. Our name is the string of Luke Skywalker and the episode is going to be four. The number four. There's the data to go through the machine. Now to validate the character against the character schema, let me write out in a comment the syntax we've got schema name dotpass and we put in the smooths the data data to validate. So our schema name is character schema. we go for path and the data is called character and that's going to return the data if the validation is successful and it sticks to the rules that we set up here for the schema and if not it's going to return that zod error. So let's console log all of this and save and have a look in the console. There's the data. So we're all good. So that works. But let's just check that the zod error comes up if I make this a string of four. Save. And yes, there's the zod error. Okay, turning this back to a number. Lovely stuff. Okay, fantastic work. Let's talk about inferring a type from a schema in the next scrim. See you then. Here we are back at our teacher schema. So let's talk about TypeScript types. We're used to saying type teacher and then we say it's an object and name is always going to be of type string and age is going to be of type number. And then we would make this teacher object of type teacher, wouldn't we? But when we look at the TypeScript type here and the ZOD schema, they're kind of doing the same thing, pretty much defining it twice. So Zod lets us get rid of all of this and use the Z dot again. And we're going to go forinfer and then we have angle brackets. And in the angle brackets, we say it's a type of and we just put the schema that we're using there. So now as the schema changes and we maybe build it out, Zod is going to automatically infer this TypeScript type from that teacher schema. So you're going to be having a go at this on your own. So do just check out that syntax. We use Z dot again and it's infer. We've got angle brackets type of and we put the schema name after type of. All right, the next thing to talk about, we've got very used topass and we remember that pass returns the data if the validation is successful and the uncort zod error if it's unsuccessful. But we need to learn about something slightly different. So I'm going to do another console log and this is safe pass. So when I now save, we can see that pass just gives us the data. But safe pass gives us an object with a success property of true and a data property of the data. Now this is when the validation is successful. Let me show you what changes when it's unsuccessful. So I change this into a string. Save. And I need to comment out the pass to start with. So save pass gives us a false reading for the success property and a new error property with that zod error. So if it passes validation we get success true and the data and then if it fails validation we get success false and we get the error. So why would we use this? Well having a success boolean in this returned object is really helpful. You can imagine using this in an app. If you're validating the form inputs you might want to know whether the validation has been successful or not. whether you need to show some errors or whether you need to ask the data to the back end. So we could for instance access the success property by going dot syntax success and then we get the false or if I change this back we'll get a true. Okay so a few extra things I need to tell you about here. We've used just dot string and number but why don't we have a new key. Let's go for is American so I can demonstrate the Z do boolean method. Hopefully you've already checked out all of the primitive types in the docs. And then here we're going to need an is American property to our object. And as you can probably hear, I am not American. So we go false. And Zod also lets us chain methods onto the end of these. So say dot number if I wanted to go for a domin and in the smooths I'll say you have to be 18 to be a teacher. So this is still going to pass isn't it because I've got 21 here but let's change this to 13. Save. And that's now failed the validation. You can also have things like gte greater than. You can have lte less than. That's now true because less than 18 we've got 13. Brilliant. Now let's imagine teachers have ids. So this could be a number and we get a chain on a dodefault. So in case there is not an ID given in the data, we can give a default value. Why don't we use math.random? So now I'm just going to get rid of the dot success so we can see the whole returned object. And there we go. Because I used default it was okay that I didn't have a ID property in the data. I could have specified one but a way to give a default value if one is not specified is to use dot default. And then another cool chaining thing to do is do optional. If you don't mind if that part of the data is there or not, you can use do optional. So I can now comment out the is American property and it'll still pass the validation because I've made that key optional. Okay, time for a quick challenge to get your hands on the keyboard. Here we have it. We're back to that student schema we had earlier. I'd like you to complete the student type. So notice we've got Z do something and in the angle bracket something before student schema. So that type is inferred by ZOD from the student schema. And then add the type annotation to the student object and then modify the console log to show whether the validation passes or fails as a simple boolean. So we're going to be changing this part, aren't we? and then something on the end to make sure we access the part that's going to give us in the console that boolean. All right, good luck. See you in a minute. Okay, I hope that was all right. So after Z dot we need infer and then in the angle brackets we're going type of. There we go. That's number one done. We need to add type annotation. So we go colon type of student. And then we need to make this safe pass. There we go. And if we save it now, we see we get that object, but we just want the true. So it's going to be the success property. There we go. Awesome. Hope that was all right. So now you understand safe pass and inferring TypeScript types. See you in the next screen where you're going to have a bit of a bigger challenge. Welcome back. Before I get you stuck into another challenge, I just want to tell you about coercion. There may be a time when you want to convert one data type into another while validating. For instance, if we think about HTML forms, they always return strings. But you may want to store the data in your database in a different data type. So let's imagine that this data has a string of 13 but we want it as a number. So here up in age I can add dotcoers. That means that it's going to convert the string to a number and then validate it with the LTE. So I save that. Bring up the console and we now see that age is actually a number. It's not failed the validation even though the data is a string. It's coerced it and converted it into a number and run any other validation on it. Okay, challenge time. Let me take this back to our character schema. There we go. And here's the challenge text. So, I'd like you to create a character type which is inferred by Zod from the character schema. Then I'd like you to add typed annotation to the character object. Then I'd like you to add an optional is Jedi boolean key to the character schema and then convert the episode key to a number. So right now if you look at the data the value of the episode property of the character object is a string. So we want to convert that into a number and then modify the log to the console down here to show whether the validation passes or fails as a simple boolean. So, it's this part here you're going to have to change and maybe add something on to the end, but you can always save and check the console and modify your answer accordingly. All right, good luck. Use those odd dogs if you need them. See you in a minute. Okay, hope that was all right. So, create a character type. So we go type character and we want to infer with zod from the character schema. So we use the z dot and it was infer and we need our angle brackets and inside here we have type of and then we just give it the name of the schema. Bingo. And then we can type this object the type of character. add an optional is Jedi boolean to this character schema. There we go. And this is going to be Z.Boolean. And it's optional. So we're going to chain on dot optional. Now because it's optional, we don't need to add an is Jedi property to this object. Convert the episode key data to a number. So episode we're going to go Z.co.number. number. There we go. And modify the log to the console to show whether the validation passes or fails as a simple boolean. So instead of pass, we now need safe pass. Let's check in the console what that gives us. Oh yes, that gives us the object with the success and the data properties, but we want just the value of the success property. So we can go into this with dot success. Save and check that. Yes, we get the boolean. Brilliant. I hope that was all right. Now, before we finish this scrim, let me show you one more thing. Let's change this from Luke Skywalker to maybe Jaba the Hut. And he's in episode six, I believe. Now, let's add another key to this schema. Let's go for email. And this is going to be Ze that I mentioned earlier. This runs a special email reax that Zod has created that make sure the data is in an email format with an at and things like that. Very similar to the rules that Gmail has for what an email address is. So we can add down here an email property and let's imagine this is jaba at hutc.com. Now is that going to pass? It is. Let's imagine we get rid of the at. So now that's not really an email and it fails. Okay, good work. See you in the next scrim. Welcome back. Let's get into errors. When we failed the validation, we saw the zod error. Let me show you that again. So if I change this to a number and save, we see our success property and error property. And the error property is this zod error. So here we're seeing the standard error properties on all JavaScript errors. This Zod error has a name property and a message property. But instances of Zod errors actually contain aues array which we can't see here. We can go into the ZOD error and target it and see that and I'll show you that in a minute. But I just wanted to mention that when we log the error here. So we can actually go to dot error couldn't we? Here when we log this we only see certain properties the name and the message the issues array is hidden in the output but it does exist. And funnily enough zod is stringified the issues array and put it in this message. So the issues array actually contains these things but in a way that we can target that array which has objects in it. This all seems very complicated but I will show you. So, what I want to do first is actually I'm going to create a results variable, a result variable. There we go. And we're just going to There we go. So, that's our validation and we've assigned it to result. Now, I'm going to log result error. This is what we had earlier. So, it's basically the same as what we just did. But now, I'm going to target this issues array that I promised you exists. Haha, here we go. So this is actually an array that we can then target meaning that we can go to the first thing in the array which is this object which has expected code path and message properties. Earlier when we saw it say zod error as I said zod had stringified this issues array and made it into a message. If we think back to our airport scanner analogy, the machine has taken the detailed scanner report and turned it into a nice easily read display. But we have to use this issues array if we want to actually get some of these values. For instance, if I wanted this message, the default message here, I have to go dot message. So basically issues, if we go back to it, is something like this. It's an array and each issue has an object. So we could create more than one issue, couldn't we? We could make the age under 18. And now we have the array of two objects. The first one's to do with invalid type, expected string received number, and the next one is to do with the number being too small. So why don't we do a little bit more code here? We're going to make an if statement and say if result do.uess, success then we're going to console log all good bro. But if it's not and the validation has failed then we are going to console log the message of the problem. So we've got result error do issues and we're just going to imagine we have one issue. So that means we can go into square bracket zero and go into the message property of that object. So now let me make this back into the string Jonathan so that we only have one problem with our validation. And there we go. That's the message telling us that the age is too small. We're going to be doing this in our project a little bit later. But actually we're going to be going one step further because we may have more than one issue. Why don't we do some mapping? So actually instead of getting the first thing in the array, let's go do map and we're going to call each in the array uh then we go big arrow and we are going to create an object with a field property and a message property. So the field property is going to be do now was something in the object that told us where the problem was. It was the path. Now to allow for nested fields because in some forms you know you can have nested fields the value of this path property is actually an array itself. So we're going to go into the first item in the array and message is just going to be a message. So let me just show you again what the issues array looks like. Here it is. You see that the path property is an array itself. So that's why we need square brackets there. Why don't I put a comment here saying array for nested fields? Eg. We could have like a user field and in that user field is a profile field and in that one is maybe an email. Okay. So now we see we've got a nice array with our custom properties. We've got a field and a message. So we can imagine if we did have an HTML form, if things fail the validation, we might want some errors to show up at the bottom of the form. And we can use the value of this field property to tell them where the problem is and the value of this message property to tell them what the problem is. This is just foreshadowing something we're going to be doing later in the project. So the main thing to remember here is the issues array which is inside the error object. See you in the next scrimm. Right, we have one more part of errors to learn and then it'll be a quick challenge. So virtually every Zod API accepts an optional error message. Now what does that mean? Well, we've been seeing the message in the console, haven't we? Here's the default one, too small. But I can actually add to dot string or dot min any of these a custom error message. So to dot string all I need to do in here is say should always be a string. I can do it after the 18 needs to be at least 18. Now when I save this this message changes because it's no longer using the default message. is using my custom one. If I then change Jonathan to numbers again, so we now have two validation problems. Our array gets bigger by another object. And the first object is to do with the name and that should always be a string. That's my custom error. And the age is my other custom error. Needs to be at least 18. So that's how we create our custom error messages. We don't have to always go with Zod's default. All right, time for a challenge. This is a bit different to usual. So, we're back to our character schema, but I've taken a few parts out and added these stars. So, we're getting a lot of red lines. Don't worry about those. Your challenge is to replace each of the six stars with the following issues, result, path, or success. There is one instance of each of these words, and the above list has been jumbled. So, they're not in that order, I'm afraid. Then you can test the code by modifying the character object saving and checking the console. You would modify it so that you either get errors or you don't get errors. So you need to put something here. You then need to go into result do something. This is very similar to the last scrim actually isn't it? Result. Ah was that special thing I asked you to remember in the past scrim. And your mapping around that field is going to be do something. What was that thing that was to do with nested fields? And then it's going to be something dot message there for the message property. Hopefully, since there's not many of these, each one will become pretty clear if you work through it slowly. Right, good luck. See you in a minute. Okay, I hope that was all right. So, what have we got to play with here? Issues result. So, this is the validation. So it kind of makes sense that we assign this to a variable and result would make sense, wouldn't it? So result there. Let's get rid of result from our list. Now if result dot well that makes sense because we've just created result here. If result do something that looks like everything's good with the validation. So we remember that we need the success property and we've got success here. That makes sense. Else. So if it's not a successful validation, console.log result. error dot something and we're mapping around that. So, what was it? Can we map around from the error object? Oh, yes, it was that hidden issues array. And then we're calling each thing in the map. So, it's do something. Uh ah, so this needs to be dot something. And last but not least, path. Yes, that was the property in each object of the issues array which had the field where the problem was and it was the one that was array itself due to nested fields. Okay, brilliant. We're done. Get rid of the challenge text. Let's save and let's see what's happened. All good, bro. Yeah, so everything's fine here. Let's turn this into a string. Save. And now we have our custom array and the one object because there's one problem with the validation field. It's in the episode. Yeah. And the message is invalid input. So just for fun, why don't I make this a custom error message by adding in the brackets should always be a number. And I save. And the error updates. Awesome. Okay. Nice work. See you in the next scrimm. Welcome back to our form project. Now it's time to put our newfound ZOD skills into practice. If you recall, we only currently have that insecure endpoint. This is what we're going to do to implement ZOD and create a new fully secure endpoint. We're going to have to install ZOD, then create some validation middleware. We're going to start with a basic inline schema. We're going to add middleware to a new endpoint and then test it of course and then render the errors to the form and test those and then expand the schema into its separate file. Let's have a quick look at this diagram how everything's going to work. So we start on the left with the form that's submitted and we make a post. That's where our validation zod middleware is going to come in. It's going to check that data and if there are any errors, it's not going to let the data through the machine. It's going to send a 400 back with the errors to render on the form. But if the validation is successful, the data along with any transformations that ZOD has made, make their way through the machine and hit the back end. In the real world, we would then save the user to a database, returning that user that's created, and then we can send that back to the front end with a 2011. So there's the full diagram. Okay, nice. So I've also created this readme.md. I did promise earlier that I would remind you about the commands for compiling the back end and the front end, etc. So, a backend setup, the way I've set it up is that by saving a file with command or control S, that is going to compile the backend folder and restart the backend server. So, let me show you that. So, if I just put a full stop here, you see the little yellow dot meaning that this file has been edited. If I now save and look in the mini browser, we see the mini browser changing. The runner has run a script which recompiled the backend folder and restarted the backend server. So that's really easy. Now for the front end, it's in the terminal. We can see here the server running. So to recompile and restart, I go for control C. It says http-server stopped. And then I just run mpm rundev, which runs a script to recompile the front-end folder and restart that http-frontend server. And the mini browser shows us the front end rendered again. Great. And then this is the only endpoint we have right now. /register vulnerable, but we're going to be creating a new one with the ZOD implementation, which will be much more secure. So, for future challenges, you can always check this readme.md if you need reminding how to restart servers. Okay, let's get cracking. See you in the next scrim. Welcome back. Let's install ZOD and then create our validation middleware. So we start by using npm install zod. Done. Now our middleware is going to be in back end. Let's make a new folder called middleware. And in there let's make a new file called validate.ts. Okay. So the main goal of this file, let's write a comment is to validate the request body against a zod schema. Yeah. So this file is basically going to be a validation middleware factory function. And we're going to be writing a higher order function that takes a zod schema and returns an express middleware function which runs when a post to the path arrives. Okay. So our function let's call it validate and it's going to take a zod schema. Now the zod docs say that all scheas extend the z.z type base class. So that's the type we're going to use here. So let's import that at the top. And this is going to be of type zod type. So this is returning our function. So let me set that up. And the parameters are going to be wreck the express request object, res the express response object, and next function. This calls the next middleware. So we need to import those. So they're going to go in here. And the types we're going to import at the top, these are from Express. Okay. And then the return of this function is going to be void. There we go. So this validate function is going to be called once during the root setup and it's going to return this middleware function that express calls on each request. So we need to bring this down here. Now this is our main thing that we want to do. Validate the request body against a zod schema. And this is where you're going to come in. So here's your challenge. We went through this when we did our mini Zod course. We need to validate rec.body against the schema. So think back to what the syntax was. Schema is going to be just called schema. And we're going to use the zod passing method which returns a result object. So if you think back, there were two types of passing method. A sort of smaller simpler one which if successful returned the data and if unsuccessful returned the zod error. But there was a slightly longer version which returned an object with a success property and then either a data or an error property. That's the one we're going to use here. I'd like to store the result in a variable. You can do that above the challenge text or below. It doesn't matter. Okay. Good luck. See you in a minute. Okay. I hope that was all right. So, I'm just going to write out the syntax. It was schema name dots safe pass. That was what we needed, wasn't it? And then it's the data to validate. So for us, the schema name is just schema safe pass and the data to validate is wreck.body. Fantastic. And then store the result in a variable. Bingo. Nice work. See you in the next scrimm where I'm going to complete this function. Okay, time to finish off this validate function. And actually before I do anything, let's export this because we're going to be using it in orth.ts in a minute. So now that we've validated the rec.body, let's put some more comments to know what we need to do. So if validation fails, we want to render the errors and tell the user who's using the form where they went wrong and where they need to change. So we're going to kind of map the ZOD errors to a userfriendly format. And that could be something like field name and error message. That might be how we render it on the front end. And then we're going to want to set the status and the JSON response and then return. And that means anything underneath will be if validation is successful. So we're going to want to attach the validated data to the request object and call next. Okay, let's get cracking. So if validation fails, so we can do an if statement and then we need to think what in result is going to tell us it's failed. Well, because we've used that safe pass, we get the object with the success property. So basically we have the result object and we use dot notation to get success. So this is false. So why don't we use the exclamation mark? So in here we're going to do all of this map errors, right? Where are we going to get the errors from? Well, in our result object, if validation is unsuccessful, as well as getting that success as false, we also get the error property. So those are the errors result error. And then we need to think when we learned about zod errors, how we access the information like the message of the error and potentially where the errors happened, the field. See if you can remember. Oh yes, it was in the issues array. Now, let me just paste in here what the issues array looks like. I'm going to do it right at the bottom. It's an array. And every issue has an object. And that object has got a message and the path, which was an array because potential nested fields, wasn't it? So, we want to map around all of these different errors. So, we're going to go do map and then we say every error, let's call those. we go arrow and we want each one be an object and we can kind of now customize what object we want it to be in the format. So because we might want to render field and then error message our object is going to have a field property and a message property. Now message is pretty easy because it's just message. So we go dot because that's each object in the issues array and we just access message but field we have to be a little bit more careful because that's an array itself. So we'll go path but because there's no nested fields we just access the first item in that path array. Okay nice. So all of this we need to assign to a variable. Let's go for errors variable. Okay. So our errors is now our array of objects in the format we want. So now we set the status. So we go res do status. And if it's failed, we're going to go for 400. And we chain on.json. And our response is going to be an object. Let's go for a success property, which is obviously going to be false. and an errors property which will be the errors array here. So remember with no colon this is essentially errors colon errors. Nice. And then we just return at the bottom. Okay. Yep. So that's if validation fails. We don't really need that anymore. And then below that below the return this is going to be if success is true as in validation has been successful attach the validated data. So the request object is wreck and we can attach it to the object and attach it whatever property we want. Let me call it validated data. And where do we get the data from? Well, we've got this result, haven't we? That's the object with the success property. And if it's a successful validation, a data property. So that' be result data. Now because up here we validated the request body against the schema that means it must match the schema. So TypeScript will know the exact shape of this data based on the schema. This means we get typed data downstream. Now we need to type this wreck and because express's request type doesn't include this validated data that we've made up sort of like a custom property we can use as any. This bypasses TypeScript to add a custom property. It's a common way to extend the request object. And then we just call next. This passes control to the root handler. So in the front end, we're going to use this errors array to help us render it below the form. Great. I hope that makes sense. Next, on to writing the schema. See you then. Welcome back. Now we finished our middleware factory function. It's time to talk about the new endpoint we need before getting into the schema. Eventually, we're going to be passing the schema to the validate function which returns our middleware function. And it's this function that Express will use for each request. So back to or.ts. Here's our vulnerable endpoint. So below we're going to write a new fresh secure endpoint. So we need to create a validated secure endpoint. So we're going to do a lot of similar things to up here. So for speed, let's just copy this line. Little bit lazy of me, but here we are. Now I'm going to call it register instead of register vulnerable because it's going to not be vulnerable. And we need to remember that we've got the path and then we've got the root handler, but in between there, that's where our middleware goes. So, let's use some different lines, shall we? Here is the middleware. Let me just finish this off. There we go. So, our middleware is that validate function. So, let's import that at the top. And it's from We've got to go back a level. It's in the middleware folder. and it's the validate.js file that we're getting it from. There we go. So then we take this and we put it in between the path and the root handler. And remember it's a function and it's going to take the schema. So we'll leave that blank because you're going to write the schema in a minute. So remember this root handler function only executes after all the middleware in the chain has completed successfully. So it's almost like the data has to get through the zod validation before any of the root handler fires. So if there's an error, it's never going to reach the root handler. So we look back in validate.ts and we remember that the data is going to be attached to the wreck. So let's copy this again. So this is our data and let's assign that to a variable. Let's call it user data. Now we need to test. We then have our business logic here. And then the response we're going to send back is going to be an object and it's going to a bit like before have a success property. And let's send the data back. For now, we're just going to send the whole user data. Later I'm going to change this, but for now it's almost challenge time for you. Let's just write a test here. So a simple console log and it's going to be the user data and which part of it we don't want anything potentially sensitive like a password but let's just go with the email. Now before it's challenge time we need to change the endpoint so that we're using our new /register. So we go to the front end app.ts and we find where this is happening which is here this fetch and we're just going to get rid of -ashvulnerable. So it's now heading to /register. Save that which is going to recompile the and let's just have a quick look at the diagram again. So we've put our middleware in between the path and the root handler. So that means that if it fails validation, we don't even get to the back end. But if it passes validation, the validator gets to the back end and we would then send it back with the user with a 2011. Okay. Hey, in the next scrimm it's going to be challenge time. See you then. Welcome back. And now it's challenge time. So you're going to write the inline schema just here above the new endpoint. And we're going to see if it works. So here's the challenge text. I want you to create a register schema with the following keys. Use the ZOD email method on the email key along with a custom error message of invalid email address. You can just copy and paste that. Limit the password key to a string. So that's going to be one method of at least eight characters and that's going to be a chained second method along with a suitable custom error message. And I'd like that error message to be about the at least eight characters part. Pass this register schema to the validate function in the smooth brackets and then save which will recompile the back end. restart the front end that's going into terminal and running mpm rundev and test the validation using the log to the runner console. So you'll be able to look here. Don't worry about this error message. It's just because there's nothing in here and you should see the email logged to the console. Now remember for this to work you need the validation to pass for it to be successful which means you're going to have to give a valid email address in the email field and a password of at least eight characters in the password field. I'm gonna help you quickly by just importing zod at the top here. Import star as zed from zod. There we go. All right, you can do this challenge just in here. Good luck. See you in a minute. Okay, I hope that was all right. So, we go const register schema and because there's two keys, we need to go z.object object and we have the smooth brackets after every method and then we have the object with email and password keys. The email is going to be the zod email method. So we go zeal along with a custom error message. So we can copy this into the smooth brackets. And the password is a string. So zed dotstring and we're going to chain on at least eight characters. So that's going to be minimum min. And the zod docs show us that min takes the number of characters to start with and then the custom error message. So let's go for password must be at least eight characters. Then we pass this register schema to the validate middleware function. There we go. And we save. Let's check the runner is working. Okay. Yep. And let's stop the front-end server, recompile, and restart it with npm rundev. Here we go. So, let's for starters, let's just not do an email address to see if we do get the errors. There we go. Email invalid email address and password. So, the errors are definitely getting fed to the front end. But if I use a valid email address in the right format, which needs an at and a.com, something like that. And then make sure this is at least eight characters. There we go. The errors go away. And we check in the runner for our console log of the email. Yes. Fantastic. So, our inline schema is working with our new secure endpoint. Fantastic. Next, Grim, I'm just going to be finishing off this endpoint. See you then. Welcome. Let's finish off this endpoint. We don't need the test anymore. That was all fine. Now, I said business logic. Let's talk about what that may be at this point in an application. So, we may hash the password. We never want to store passwords in a database in plain text. If the database is compromised, then attackers would get everyone's passwords. So, we could use something like brypt or argan 2. These are intentionally slow to prevent brute force attacks. We could store the user in the database with parameterized queries. This could be an extra layer against SQL injection. We could generate a JWT token for authentication. This is a way for the user to prove they're authenticated without having to send their password with every request. We would then most likely send a verification email for the user to confirm their email is real and does belong to them. Okay. Now here I mentioned earlier we need to make sure we return safe public fields. So we need to make sure we exclude password obviously maybe age and bio. Now let's put this on a new line and make this into an object. Now let's only return the fields that we're talking about now and that we have validation for. So that would just be email and that's going to be user data email. And just like up here, we need to make sure we return the mock user count. And look at that. I realized I've totally forgotten the status. So, let's put a status 2011. There we go. Well done if you noticed that earlier. So, this is guaranteed to be a valid email. Okay, lovely. Saving that. Let's check the runner. Yep, all good. Let's mpm rundev to get the front end running. Now, if I don't add anything to these fields, we get the email and password errors. Quick mention again, I think I may need to just clarify when we talked about mapping over the issues array here and targeting the path. I think I mentioned that this data was coming from fields. Now, I need to be clear that when we validate nested objects or arrays, let's have a look at our schema. So, we've only got one object here, but potentially we could be nesting objects within other objects like something like this where we've got an object and a nested object. So, the reason why Zod uses the array here is that the path we're getting from this property name. So, this would be user and then nested in there would be name or age. So that's where path is coming from the schema object property name. And because we haven't got any nested schemas, we're always going to access the first item in that path array. And when validation fails, we're returning the errors which we've made this array of objects for each error. And here we can see them ended on the UI. So if we look back in front end, we've got our display errors function. And we're going through errors and creating a list item rendering error. Colon error dossage. All right, I hope that makes sense. And then if we get a proper email address and a long enough password, those errors should go away. Nice. You might wonder why we've got undefined here. That's because we're rendering the name. Remember, we're not returning the name yet because we haven't created key for name. That's coming up shortly. Okay, let's extract this schema into its own file and do some type inference. See you in the next scrimm. Welcome back. So, we have our small inline schema here, but we're going to now extract it into its own file. So, why extract the schema? Now, we could want to reuse the schema in multiple places. It's good for organization. We're going to be exporting the inferred types. So there'll still be type safety. And it means we have a single source of truth for validation rules. So in back end, let's make a new folder called schemas. And then in there, a file called user schema. And then we can take away this schema we've already done and put it into user schema. We then don't need this line, but we could put it up here. We need to make sure we export this register schema and then import it at the top here. It's in schemas and user schema. There we go. So that should still work. Let's check install that we now have schemas. Yep. Okay. Time to test. So the runner is working. Okay. Let's just run npm rundev. Yep. Okay. Everything's compiled properly. This is all working. Let's just There we go. See our errors. Fantastic. Okay, you're up. It's challenge time. In the mini Zod course, we learned about inferring types. So, in user schema.ts, create a register input type which is inferred by ZOD from this register schema. Export this type and then in orth.ts, import the type and use it to add type annotation to the user data object, which remember is down in our new endpoint. Here's user data. So, this needs typing. I'll just put that there to help. Okay. Use those Zod docs to help and go back to the mini Zod course if you need. See you in a minute. Hope that was all right. Okay. So, we create a type and it's going to be called register input. And this is going to be inferred by Zod. So we remember we need to use zed again and we use the zed infer funnily enough and then we have angle brackets and in there we put the schema name but before that we need to say it's a type of this schema. There we go. So now when we build out this schema the type will be inferred. It'll be constantly updated. So this means that this type this register input type becomes this automatically. Okay, export the type and then let's copy it and we go in here and then at the top we just add it because it's coming from this file. We can add it to this curly brackets register input and then we use it to type the user data. Fantastic. Save everything. Brilliant. I hope that was all right. Let's run a quick test again. That's all good. Let's close this mpm rundev again. And are we getting our errors? We are. Let's test with a nice long password and a valid email. Fantastic. There we go. All right. We've got a few more fields to complete for the register schema, haven't we? See you in the next scrim. Welcome. We're getting close to the end of this form project, but we only have these two keys for the register schema. We need to build it out. And it's your challenge again. Blime me. I really work you hard, don't I? Here we have it. So, I'd like you to add an age key to the register schema, which converts the string to a number. Now, remember that HTML forms all return strings as standard. So, even if the user inputs a number eight, we're going to be receiving that data as the string of that number. So, we are going to convert it back to a number because that's how I'd like it in our database. And then we want to validate it between 13 and 120. I'd love to see 120y old using this API, wouldn't you? Then add a username key to the schema which only validates strings of between 3 and 20 characters. Now, Zod lets us make some data transformations. So, I'd like to chain the necessary transformations to ensure the email is stored in lowerase. So this is a really great opportunity for you to look in those Zod docs and without any surrounding white space. That's going to mean that all the data is nice and uniform and standardized. Then save, which remember will recompile the back end and then restart the front end in terminal using mpm rundev and test the form to check that we get errors when we fail the validation and a nice success message if the validation passes. Right, take it slow. See you in a minute. Good luck. Okay, let's add age below here which converts the string to a number. So we think back to that mini zod course and we need to go Z dot and then coers because we are transforming it and then we say into what? Into a number. Let's make sure we spell that right and validates it between. So we're going to add more dot somethings onto here between 13. So that means we're going to have a dot min and a dot max 120. There we go. So we have transformed the data and then validated it with min and max. Now a username key only validates strings. So we're going to go z.string between three. So again we need our min and 20. There we go. Now chain the necessary transformations to ensure the email is stored in lowerase. So the zod docs tell us that we have a dot to lowerase method to lowerase. There we go. That's a transformation after the email validation has processed and without any surrounding whites space. So then we also need trim. Great. Let's save that. Check the runner is all happy. Yep. And then we run our mpm rundev. Starts up the front end and we can test this. So, why don't I just not add anything? I should get lots of errors now. Great. I'm being told the age is too small. I'm being told the username is too small. So, email address. Let's go for pair again. Actually, you know what? Let's go for Tom. Age needs to be between 30 and 100. Let's go for I don't know 21. Username needs to be at least three. So we'll go four characters. Password above eight characters. Should this pass? Yes, it does. And if I say went for five here, age should still be erroring. Yes. Too small. And that's the default error message there since we haven't put any custom error messages on the age key. Awesome. Let's get rid of the challenge text. And I'm just going to tidy this up and put these on different lines. Okay, so give me a second. That looks better. I'm going to just modify this. I don't like invalid email address. Let's go for required. And must be a valid email address. So in case they don't add one, they're going to be told it's required. Let's go for required here. In case they miss out age, I'm just going to add a quick custom error message for min and max. Let's add a quick comment here. Now I want to actually add one more method here and it's going to be int. We want integers only. So my custom error message is going to be age must be an integer. Even though we know HTML forms do always give us strings, it's always good to be really clear in case, for instance, a bad guy could hit our API directly and sort of bypass the front end. So that's why we still have dot strings here, but we're not going to put custom error messages on dot strings because they're never going to be showing up in the UI because the HTML forms do return strings. Let me add a few here. And the last thing to make the password a bit more safe, I'm going to add a reax. This is going to make sure that they can only use letters, numbers, and underscores. I'm not going to go into how we write reax. You can always ask your favorite AI, but we're going to go for that. There we go. That's looking much better. Now, let's test it. We saved that. Let's stop that and rerun. So, let me add loads of exclamation marks for the password. Let's check that our custom error messages are working. There we go. We've got that custom error message for password. We username is good. Age is good. Required and must be. Yeah, fantastic. Now, a little bit more housekeeping. Back in author, we need to update our response. Send an ID. Let's go for date.now. And then we've got username as well. Okay, lovely. We're almost there. We just need the name and the bio. See you in the next Grim. [clears throat] We're so close now. One more challenge for you. Here it is. You can probably guess. Add a name key to the register schema which only validates strings of between 2 and 50 characters. You're going to be getting pretty good at that by now. Add a bio key which only validates strings of up to 500 characters and make that bio key optional. Then save. Restart the front end in terminal and test all of the fields now using the form. Check that only the data that we have specified in the schema is being allowed. Good luck. Okay. I hope that was all right. Let's go for name right at the top. And this is a string of between two and 50 characters. There we go. Add a bio key. And this is a string of up to 500. So we go max 500. Make the bio key optional. So we just chain on one more dot optional. Okay, nice. Let me save that. Check the runner's happy. Yep. MPM rundev. So name. If I just go for one character here, we should have a problem with name. Yep, too small expected string. But notice we don't get a bio error messages because we made it optional. So missing it out isn't a problem. Is not going to cause an error. Okay, lovely stuff. So let me add a custom error message here. and here. And let's practice that reax again on name. So we go dotreax. And this time I only want the name to be able to contain letters, spaces, hyphens, apostrophes, and periods. So it's going to look like this. And the custom error message will be. And then I think it would be good to trim this as well in case there's any trailing white space. And then let's go for a quick error message here. Okay, very good. So I hope you can start to see many of the benefits of using a validation library like Zod. Tiny bit more housekeeping. We now need to add down here name. And finally now if we pass validation we should see the name in the success message. Let's have a go. Let's say I'm 30. Boom. There we go. So, so it's not undefined anymore because we're returning the name in this user object. Let's have a quick look in app. We should see display success. There we go. We're getting response user.name there. Lovely. So, now we have all of the data in the correct data type. We have a strong password. We have transformed certain user inputs into a standardized format. We have users of a suitable age etc. Good work in this project. Why don't you try from scratch creating a new schema and implementing it in your own form. Great job. You've made it to the end of this course. Thanks for following on and being a great student. The core principle we've learned is never trust user input. We've learned about defense in depth. We've covered multiple layers of protection, each serving a specific purpose. XSS prevention protects your users from malicious scripts by properly handling how data is displayed. For instance, using text content overin HTML. Denial of service mitigation ensures your application remains available even under attack through rate limiting and resource management. SQL injection protection prevents attackers from manipulating your database queries through prepared statements and parameterized queries. And input validation through libraries like ZOD enforces data integrity and business rules, ensuring your application only processes well-formed data. The techniques covered in this course are fundamental, but security is an evolving field. Stay informed about new vulnerabilities. Keep your dependencies updated and continue learning. The registration form we used is just one example. Apply these principles to every user interaction in your applications. Thank you for joining me on this course. Good luck with the rest of your learning. Hello and welcome back to the backend security course. In this section, we're diving into authentication and identity, how apps figure out who you are and how they keep that information trustworthy. Last time, we put on our attacker goggles and learned to spot weaknesses with stride and OASP. We looked at all the ways that people tried to sneak in, pretend to be someone else, or poke at the edges of an app to see what breaks. And now we're going to switch perspectives. Instead of finding the cracks, we're going to study the structures that hold everything up. The systems that apps use to verify identity and keep it consistent across requests. If you have a look at most of the threats in Stride or the issues in OASP, almost all of them tie back to identity. Spoofing is when someone pretends to be another user. Broken access control is when someone is doing stuff they really shouldn't be. And sensitive data exposure often happens because the app didn't properly check who was getting access. If an attacker can trick your app about who they are, then everything within is up for grabs. And that's why authentication is one of the foundations of back-end security. Before we get hands-on, let's set the stage. First, we're going to untangle the two big OR words that you hear everywhere: authentication, and authorization. Then, we'll explore the three major identity models used in real apps. Stateful identity, stateless identity, and delegated identity. Now, these are the three big arcs of this section. Each arc focuses on one identity model, how it works, where it's used, and the common pitfalls to watch out for. And as usual, there will be opportunities to challenge yourself with the new concepts. By the end, you'll understand not just what these systems do, but why real apps choose one approach over another. Each of our three arcs finishes with a challenge so that the learning stays tight and focused. You'll complete one identity model before stacking the next one on top. For each one, I'll walk through the first scenario so you can see the kind of reasoning we're aiming for. Then the scrim will pause and hand things over to you. You'll get a handful of short situations to read and reflect on using the same mental model we would have just explored. And once you've had time to consider your answers, you can resume the lesson and we'll walk through some possible answers together. The examples and challenges in the section will be in JavaScript because it's familiar. But just know that the ideas apply no matter what backend stack you use. We're not here to memorize framework methods or learn a new language. We're here to understand how identity flows through a system and how we can protect it. All right, let's jump in and explore how modern apps prove who you are and keep that identity secure. Before we dig into authentication, we have to talk a little bit about the other or in the room, authorization. The two both start with or and can sometimes be mixed up or understood as the same thing, but they're not. Whenever a user interacts with your app, two big questions decide everything. Who is the user and what is that user allowed to do? One is authentication and the other is authorization. Often said together and often mixed up, but they solve two totally different problems. Let's start with authentication. Authentication proves who you are. It answers the question of is this really who the user claims to be? Now, as an internet user, you'll be familiar with some of these authentication methods. Logging in with a username and password, signing in with Google, or sending an API key or a token. If an app gets authentication wrong, someone can pretend to be someone else. And that's spoofing, the S in stride. Now, authorization comes after that. Once the app knows who the user is, authorization decides what the user is allowed to do. So, some common examples include a user reading their own data, a user updating their own profile, reading student data if you're a teacher, or getting no access to other student data if you are a student yourself. If authorization fails, user can do things that they shouldn't, leading to elevation of privilege or broken access control. So, how do the two fit together? Well, most back-end systems follow a simple flow. Request, then authentication, then authorization, and finally the resource. For example, if a user is trying to read their own profile, the request for data comes in. Authentication will then check if the user is logged in. After that, authorization will check that the user is accessing their own data. And finally, if all that is fine, then the resource or the access is granted. Now another example is an admin trying to reach an admin only endpoint. You'll notice that only one of these four things has changed the authorization part. So the request arrives, authentication identifies the user and then authorization checks for admin rights and if that all checks out then access is granted. So realistically we need both authentication and authorization. Good authentication with weak authorization is unsafe. And good authorization without solid authentication is meaningless. If someone can pretend to be the wrong user or act beyond their permissions, they can break almost anything in your app. And that's why so many real world vulnerabilities boil down to these two things. Now, to set expectations, the focus of this section is authentication and identity. how apps prove who a user is and how they keep that identity consistent across requests. We will mention authorization where it helps the bigger picture, but we won't dive deeply into authorization logic. So, now that we separated who you are from what you can do, the next step is understanding how apps actually remember you from one request to the next. So, in the next scrimm, we're going to look at the three big families of identity systems used across the web. I'll see you there. Before we get into the details, here's the core problem. HTTP is stateless. Every request is brand new. No memory, no context, and no built-in way to remember who the user is. So, if your app needs to recognize a user across multiple requests, it has to store identity somewhere. Modern apps usually solve this in one of three ways. Stateful identity, stateless identity, and delegated identity. And these three families power almost every login flow you'll ever see. A stateful identity means the server remembers the user. Once someone authenticates, the server creates a session, which is a bundle of information that represents that loggedin user. The browser sends a tiny session ID and each request uses that ID to look up the user. Once again, this is the pattern that you see in traditional web apps and in many frameworks by default. If you've used Express Session before, this should ring a bell. Express stores your session. Your browser sends back the session ID and Express uses it to remember who the user is. Stateless identity means that the client carries the proof. The server doesn't store a user session. Instead, the client sends something, usually a token, on every request. The server can validate that token without storing an entire user session on the server. And this works beautifully for APIs, mobile apps, and distributed systems where shared server memory isn't always an option. If you've ever hit an API and gotten this 401 unauthorized missing authorization header, that's what's happening. The server expects the user to bring the proof every time. A delegated identity is when a trusted third party confirms who the user is on your behalf. Your app says, "Hey Google, can you check who this person is?" Google handles the login and gives your app a token that proves the user's identity. This is when you see those buttons that say sign in with Google, sign in with GitHub, or sign in with Facebook. Together, these three families cover almost every identity system you'll encounter. They all work towards the same goal, authenticating users and enabling authorization decisions, but they take very different approaches with different strengths and different security pitfalls. Across the rest of the section, we'll explore each family in turn. For each of the models, we'll have a look at how it actually works, some common mistakes that developers make, and how to work around those mistakes through a security mindset challenge. Now, let's dive into the first identity model, stateful identity. In this scrim, we're going to have a look at how stateful identity actually works. This is the classic pattern where the server remembers who you are and your browser just carries a tiny ID that points back to that memory. As we mentioned earlier, HTTP requests are stateless. So every request is brand new. Nothing remembers anything between requests by default. So when a user logs in, our app needs a way to identify who is sending these requests. Stateful systems solve this by creating a session on the server. A session is just a small bundle of data that represents the loggedin user. It may include a user ID, a name, or maybe the user role. Now, this session lives only on our server. And to reconnect the user with that session, the server sends the browser a cookie. Now, the cookie lives in the browser and is sent automatically with every request to that domain. The only job of this cookie is to let the server know what user session this particular request belongs to. So let's see what actually happens in a typical stateful system. The user logs in by submitting their username and password. The server checks if the username and password match a user and if the login is valid, the server makes a session for this user. This session is stored on the server only. And as mentioned before, it might include a user ID, a name, and potentially a role for authorization. The server then sends back a cookie that contains just a tiny reference to the user session, a user session ID. Now the browser receives this and stores the cookie automatically. You don't have to write any code for that part. And on every future request to that domain, the browser sends this cookie along with the request. Again, this is automatic, so don't worry too much. And finally, the server looks up the session by the session ID in the cookie. If it finds a valid user session, then that user is authenticated for that request. So once the user has the session, it can also use information inside of it like the role to help with authorization decisions. But like I said before, we're not going to go too deep into authorization logic now, but it is good to know that some apps reuse the same session data for both identity and permissions. Now, the cookie is the key to this entire system. A typical session cookie does not store the user's identity directly. It does not store roles or permissions. It only stores a tiny session ID. All the sensitive data lives on the server in the session. And the cookie is just our lookup key. It's a little bit like leaving your stuff in a gym locker and grabbing a numbered key for that locker. The key itself doesn't list what's in your locker and it doesn't have any real value by itself. It's just the thing that you use with the locker to get your stuff back. And that's what a cookie is. It's just a numbered key. The real information lives safely on the server side or in your gym locker. And this is one of the reasons why stateful identity is so widely used. The server is in control of the session, which makes it much harder for attackers to tamper with directly. So, now that we've seen how cookies and sessions work in a healthy, stateful system, our next scrim looks at what happens when things go wrong. the common mistakes that developers make with sessions and how those mistakes can turn into real issues. Now that we understand how cookies and sessions work, let's look at the mistakes that developers commonly make with them. Here in the editor, I've created cookie pitfalls.js. This is where we're going to have a look at a few Express style cookie examples. These look a bit like real server code and they'll give us a nice concrete frame to explore each pitfall. Don't worry, we're not actually running the code. It's just a realistic frame to help you spot what's going on. In this scrim, we'll have a look at two common cookie mistakes. And then in the next grim, we'll switch on over to session side mistakes. The first pitfall is the classic beginner mistake, putting sensitive information directly inside of a cookie. Remember, the cookie is just your gym locker key. Its only job is to hold a session ID that points back to the real session on the server. But sometimes developers end up doing something like this. Session ID, user ID, RO, email, password, IP address as well. Now it may look convenient to have all of this data in one place for our browser. But it's a huge security risk. Cookies can be intercepted, logged, leaked, or read by JavaScript by the attacker. So the moment you start putting private information inside a cookie, that data starts traveling everywhere the user goes. And this introduces two major stride problems. Information disclosure because private details are being exposed. Spoofing because leaked IDs or roles can help an attacker impersonate a user. And in OASP terms, this becomes broken access control since exposing roles or IDs can accidentally hand attackers extra privileges. The fix is super simple. keep all sensitive data on the server inside the session store and make sure that cookies only contain a session ID. So here in the editor, we're going to fix this up. Let's grab a copy of this cookie and we're going to cut absolutely everything except for the session ID and nothing else. And this here is the perfect cookie. Or is it? The second pitfall is easy to miss. Cookies that last way too long or worse, never expire. When the server sends a cookie back to the browser, we can specify a max age or expiry date. If we don't, many browsers will just keep the cookie indefinitely. For example, down here in cookie pitfall 2, a server can send back this particular cookie. It's a great cookie. It just has the session ID, and in fact, it's exactly the same as the one we just fixed. But this cookie doesn't expire. And with no expiry set, that cookie may live for months or years if the user never clears their browser data. And this is dangerous for two main reasons. If an attacker ever steals that cookie, they have access for as long as it lives, which might be forever. And a user whose permission has changed or whose account should no longer be active might still have access through that long-ived cookie. So in stride terms, this leads to elevation of privilege because outdated permissions can remain valid. And in OASP terms, this is authentication failure because identity isn't being revalidated often enough. And the fix is simple. Just give cookies a reasonable lifespan. Back here in the editor, let's take a copy of this cookie so we can fix it. To add an expiry, we can add a max age property and we'll set it to 1800, which is 30 minutes. Shortlived cookies limit how long a stolen cookie is useful for, and they force the system to reconfirm identity regularly. It's one of the easiest security wins you can implement. So, the two big cookie mistakes are putting sensitive data in cookies and cookies that never expire. They're simple concepts, but they show up in real code all the time. Fixing them requires almost no code, and the security payoff is huge. Okay, that's the cookie side of stateful identity. In the next Grim, we're going to have a look at some session pitfalls. I'll see you there. Now that we've covered common cookie mistakes, let's flip to the server side and have a look at session pitfalls. These issues are just as common, but because sessions live on the server, they're much easier to overlook. Before we have a look at the pitfalls, a quick reminder of what a real session store looks like. In an Express app, you'll actually never manually write a session object. The framework creates it for you and you store it behind the scenes, usually in memory. Each session is designed to be quite small, something like this. Basically, an object of data related to the user session. So, we have the session ID, user ID, potentially a role, and of course, expires. For our examples, I'm going to write these out as simple JavaScript objects just to make things clearer. Think of them as the kind of records a real session store would generate automatically. The first pitfall is when we absolutely stuff the session store. A session is meant to be tiny, just enough to identify the user. Usually, that's just a user ID, maybe a role, and not much else. But beginners sometimes treat the session like a little storage box here in session pitfalls.js. I've got some examples set up. So let's come over here to the first example and have a look. Here we have a session that contains a session ID, user ID, RO, cart, last view page, theme, and some C posts. While this technically works, it causes some problems pretty quickly. Remember, sessions live on the server. So if we cram too much into them, we waste server memory and we risk the session going out of sync with the real database. From a stride point of view, this becomes a tampering issue. Not because someone is editing the session directly, but because the app is making decisions based on data that's stale or inconsistent. And in OASP terms, this falls under broken access control because the app is relying on outdated session information when deciding what requests to allow. And of course, the fix is simple. Keep sessions small. identity and maybe RO only. So to fix this session, we simply have to strip everything back until we only have the session ID, user ID, and RO. So let's grab them all and we'll pop them in this new one. Nice and small. Moving along, the second pitfall is a sneaky one. Long live sessions. If you're thinking, hey, that sounds a lot like the second cookie pitfall, you'd be right. Sessions need specific expiry as well. Let's have a look at the example down here. Now here we have a session which is actually identical to the one that we just fixed. It looks fine, but now we know the issue with long life anythings. In the last cookie scrim, we talked about longived cookies and sessions have the same problem just on the server side. If someone ever steals the cookie that points to this session, they get access for as long as the session survives. And if the user's permission changes, the old session may still say that they're allowed. and logging a user out of everywhere becomes almost impossible if none of their sessions ever expire. It's the same long life issue, but even riskier because the server is trusting stale data. Our Stride and OASP vulnerabilities are the same as the cookies. In Stride, this shows up as elevation of privilege because outdated session data can still grant access. And in OASP terms, this is an authentication failure. The app isn't revalidating identity often enough. So, two fixes help us avoid these issues. First, sessions should naturally expire after a reasonable time, maybe 20 minutes, maybe a couple of hours. And sometimes the app should issue a brand new session, for example, after login, after a RO change, or when the user reauthenticates. And this is what it might look like in JavaScript objects. So, we'll just grab the original and pop it down here. And we're going to add a property that helps it expire. Some frameworks use expires and some frameworks use expires at. And I'm just going to add today's date and a time that is around 30 minutes from now. There we go. It's that simple. Shortlived sessions means we have a much safer identity model. So those are two pretty big session pitfalls. Stuffing too much data into a session and sessions that never expire. They're pretty easy mistakes to make, but now that you know how stateful identity works behind the scenes, you'll know exactly why these issues matter and how to avoid them. Now, a quick note on the frameworks that offer stateful identity systems. Most of these, like Express, Django, Rails, Laravel handle the basics for you. They keep the cookie small, manage the session store, and give you sensible defaults. But these pitfalls still happen all the time because developers control what goes into the session and how long it lives. Frameworks can store the session safely and offer sensible defaults, but only you decide what the session contains and when it expires. All right, that's the session side of stateful identity done. In the next scrim, you'll put your new knowledge to the test and try spotting these issues in real examples. I'll see you there. Welcome to your stateful challenge scrim. So far, we've learned about how stateful identity works, how cookies carry a tiny ID, and how the server stores a user session, and how simple mistakes can accidentally weaken authentication. Now, we're going to put all of that into practice. Here in the editor, you'll see a series of cookie and session examples. Some look harmless, and some are obviously suspicious. Our job is to scrutinize each one, spot what's wrong with it, and then fix it up. Here at the top of the file, you'll see the four common pitfalls that we were just talking about, as well as some instructions. Let's walk through the first scenario together. This function sets a cookie after login. There are a couple of security risks here, which we'll list down here in the pitfalls section. First, this cookie has way too much in it. Not only that, but it's full of super sensitive data, such as this password or this IP address, and that's no good. This is pitfall one, sensitive data in cookies. We know by now that the only thing that belongs in a cookie is the session ID. Well, the session ID and the expiry. And speaking of the expiry, the max age here is way too long. Google tells me that this is almost 32 years. And this is pitfall 2, longived or never expiring cookies. Okay, we've listed our risks. Now, it's time to fix it up. I'm just going to copy and paste the original. And then I'm going to cut everything from user ID all the way down to the IP address. And then I'll fix up this max age so it's only 1,800 which is about 30 minutes. And we fixed it. That's scenario one. Okay. Now it's up to you to handle scenarios 2 and onwards. Think about all the pitfalls that we talked about in the last few scrims and use scenario one as a template for handling the rest. Take your time and I'll catch you on the other side. Welcome back. How did you go? I bet you did super well and crushed all those pesky pitfalls. Let's go through these together. Scenario 2 is another cookie that is set after a user logs in successfully. This one is the complete opposite to scenario one. It is too small and has no expiry. So, this falls under pitfall 2, longived or never expiring cookies. And this one is super easy to fix. We'll just have to add an expiry. So, let me grab the original and we'll just have to add the max age property. And I've set it to 3600, which is about 1 hour. And there's scenario 2. Now down here, we're going to jump over to sessions for scenario 3, where we have an object that represents a user session in the server. And one look at the sheer size of this, we know we've got ourselves a pitfall 3, overstaffed session stores. Now, while this is technically possible, we don't really need everything here. We only need the session ID, some minimal identity data, and the expiry. And speaking of expiry, we have something here that won't expire till the year 3000. Now, this was probably just a typo, but it is still dangerous. So, this is pitfall 4, longived or never expiring sessions. So, let's fix them both up. I'll copy the original, and then I'll cut everything from the cart to the IP address. And then I'll change the expiry to today around 30 minutes from now. And all done. And finally, let's have a look at scenario 4, which has both a cookie and a session for us to scrutinize. First, there are some non-pitfall issues with the cookie. Did you find them? Well, first, the cookie is missing a session ID, which is literally the most important thing about a cookie, so we'll be sure to fix that in a second. And that max age, well, I guess it's short, but it's probably too short for any situation. So, a cookie should have a reasonable expiry. Now, on to the pitfalls. It looks like the cookie has some information that doesn't need to be there. The user ID and the role. So that is pitfall one, sensitive data in cookies. Now moving down to the session. All the properties we need are here, but one of them is sticking out like a sore thumb. And of course that is the expiry. So this is pitfall for longived or never expiring sessions. So there are a few things to fix here. So let me grab a copy of both. Now, from the cookie, I'm going to get rid of the user ID and RO. And in their place, I'm going to add the session ID. And then I'll bump this max age up to something a bit more reasonable. 1,800 or 30 minutes. And down here in the session, let's swap that expiry to something that's 30 minutes from now. And there we go. Much better across the board. Now, even if your fixes looked different, the important thing is that you thought about the reasoning. And that's exactly what security-minded developers do. In the next arc, we'll explore a completely different world where the server doesn't remember you at all and the token itself becomes a proof of identity. I'll see you there. Welcome back. Last time we explored stateful identity, where the server remembers everything and the browser just holds a tiny ID in a cookie. But sometimes your app can't and shouldn't remember that kind of state. Maybe you're building a public API. Maybe you're working on a mobile app. Maybe your system needs to scale across multiple servers where storing sessions would be slow, messy, or impossible. So, for the next handful of scrims, we're shifting gears and looking at stateless identity. But before any of that, we must clear up the biggest beginner misconception. When we say stateless, we don't mean that the server stores nothing. We mean that the server stores no session object, nothing that tracks the user between requests. The server doesn't hold a user's identity. The request brings everything the server needs to figure out who the user is. And that's the stateless idea. With that in mind, let's start with the simplest form, opaque bearer tokens. An opaque bearer token is sent with every request in the authorization header. It's just a random unguessable string. We call it opaque because the server can't read anything inside it. It's not encoded. It's not structured. It's just a random string credential. Now, a quick side note. Even though the header is literally called authorization, in this context, it's still being used for authentication, proving who the user is, this bearer token doesn't grant any permissions. It just identifies. This name is just an odd historical leftover from the early HTTP days. Here's the basic flow with an opaque bearer token. The user logs in with their username and password. The server checks the username and password. If valid, the server generates a random opaque token. The server also keeps a token to user lookup, a tiny mapping just so the user can recognize a token. Then that token is sent back to the client and the client stores it maybe in local storage. Then every future request includes the bearer token in the authorization header. Now this is something that our app must be programmed to do. Then the server validates the token, finds the user in the token user lookup, and the user is authenticated. At this point, you're probably thinking, "Hey, why does this sound exactly like cookies and sessions? And why have you just used the exact same slides?" And you'd be on to something. Both systems do involve something the client sends, something the server checks, and something that connects the two in order to identify a user. But the philosophy of identifying a user is completely different. Yes. In both systems, identity ultimately lives on the server, but the way they go about it is completely different. And therefore, the server stores different things. A stateful server stores a full user session object, while a stateless server only stores a tiny tokentoer lookup. It's not a session. It's just enough for the server to recognize the token and work out who the user is. On the client side, the difference is very simple. A stateful client stores a cookie with the session ID, but a stateless client stores the token itself. And those different storage models change how identity travels back to the server. Stateful identity is sent automatically through cookies, but stateless identity has to be sent explicitly in the authorization header as a bearer token. And finally, each model fits different use cases. Stateful identity works beautifully in traditional web apps, but stateless tokens are the standard choice for APIs and mobile apps. A good analogy is like a key card to access a building. The card doesn't contain your name or identity. It's just a piece of programmable plastic. You tap it at a door's card reader and it checks the card against a list of allowed cards to decide whether to let you through. So that's opaque bearer tokens. They're small, they're simple, they're statelessish, and honestly, they're very elegant. But of course, there are plenty of ways to mess them up, and I have a feeling you're already thinking of a few. So, in the next groom, we'll have a look at the common pitfalls that developers run into with the bearer tokens and how to avoid them. Welcome back. We now know how opaque bearer tokens work. The server checks your login, generates a random token, and the client sends that token on every request. The server keeps a tiny lookup that maps a token to a user. It's simple, lightweight, and clean. But bearer tokens have one huge weakness. If someone steals your token, they instantly become you. And that's what bearer means. Whoever bears it uses it. So with opaque tokens, most of the danger isn't in how they work, but in how they can be stolen, misused, or replayed, which is just a fancy way of saying used over and over again. So let's have a look at some common pitfalls. Pitfall one is unsafe token storage. The number one way that tokens get stolen is simply storing them somewhere unsafe. If a plain text token sits in local storage, a plain variable, or an unprotected cookie, then any malicious script running on the page can grab it instantly. And the moment that it's stolen, it becomes a spoofing problem. The attacker is now indistinguishable from the user. There's no perfect storage for tokens, but the rule of thumb is simple. Store tokens somewhere harder for attackers to reach and reduce how often the token is exposed. Pitfall two is long life tokens. Anyone else getting deja vu? Yes, this one mirrors what we saw with cookies and sessions. If your token lasts days or weeks or months and it somehow gets leaked, an attacker now has that long to impersonate the user and do some lasting damage. That's information disclosure and spoofing rolled together. Now, the fix is pretty straightforward, and you'll know this by now. Use short expiry windows. The shorter the window, the smaller the blast radius. Pitfall three is that there's no automatic revocation. Opaque tokens don't manage themselves. They don't expire on their own. They don't invalidate when someone logs out. They don't just magically stop working unless that's how we've programmed them. So even if we do set expiry dates on our tokens, if our app doesn't even action upon them, that token may still stay valid forever. And that leads to elevation of privilege and broken authentication. So to make sure that this doesn't happen to us, our app has to check the expiry on every request and delete the token when the user logs out. Both of these make a huge difference. The next pitfall is token lookup bloat. Opaque tokens rely on a lookup and every login adds a new record and if tokens expire quickly, which they should, we'll generate a lot of them. If we never clean up these expired tokens, then lookups will slow down, memory usage will spike, and the whole system gets sluggish. And an attacker can deliberately abuse this, spamming your login endpoints to generate thousands of tokens and bog down the lookup, and that is a denial of service attack. So, how do we fix this? A simple cleanup job. Just regularly remove expired tokens. And finally, pitfall 5 is a tampered lookup. This lookup is your source of truth for identity. If an attacker ever gains right access through something like SQL injection or leaked admin credentials, they can simply change the mapping. A token that once belonged to a normal user can suddenly map to an admin user. And that is elevation of privilege. Nothing about the token changed, only what it pointed to. So protecting the database and any admin interfaces is just as important as protecting the application itself. So those are some pretty big pitfalls of opaque bearer tokens. They are lightweight, flexible, and widely used, but they don't protect themselves. Most of the risk comes from how tokens are stored, how long they last, and how the lookup is managed. And all of this leads naturally to our next question. If OPEC bearer tokens need a lookup and they're this vulnerable to theft and replay, what is a better option? And that's exactly what we're going to explore next. Welcome back. In the last two scrims, we explored opaque bearer tokens and the problems that can show up when they leak, last too long, or get mismanaged. Now, we're going one level deeper into stateless identity. What if we wanted a token that didn't need a lookup at all? A token that literally carries all the identity a server needs? Well, that's exactly what JSON web tokens or JWTs or Jots were designed to do. A JSON web token is a self-contained token. That means it carries all the important information. Who the user is, what they're allowed to do, which again is authorization, when the token expires, who issued it, plus a cryptographic signature to prevent tampering. I know it's very fancy. Everything the server needs to authenticate the user lives inside the token itself. Therefore, no lookup needed. And this is the most stateless version of stateless identity. This text sausage is a JSON web token. It's a three-part token separated by dots. We have the header in blue, which describes the algorithm and token type. Then we have the payload in yellow. This is where we have the user identity information as well as roles, also known as the claims. And finally, we have the signature in pink. This is that little cryptographic stamp that proves that the token hasn't been tampered with. So, now that we've seen the text sausage, it's important to understand how that sausage is made, what goes into it, and why it ends up looking like that. So, here's the simple version. The server starts with two ingredients. the header which says use this algorithm and this is a JWT and the payload which is full of the users's information or claims. Then the server combines those two ingredients with something only available within the server, the secret ingredient or a secret string. It mixes the header and payload with the secret to create the signature, that pink tamperproof stamp, and then encodes all three parts and joins them with dots to form the final JWT. Now, anyone can decode the header and payload with a decoder, but only the server can create or verify it because only the server knows the secret. That's what makes this whole thing trustworthy without needing a lookup. Here's a standard login flow with JWTs. The user logs in, the server checks the credentials. If valid, the server creates and signs a JWT. This signed token goes back to the client and the client stores it locally. Every subsequent request must include the JWT via the authorization header just like the opaque error token and then the server verifies the signature. No lookup and no server storage used. And this is why JWTs are considered fully stateless. The identity is the token itself. So let's compare JWTs with the opaque bearer token. Opaque tokens contain nothing. They're just random unguessable strings. A JWT on the other hand actually contains data encoded claims like the user's ID, their role, and the token expiry. In terms of how we identify the user, with an opaque token, the server has to look it up in that tiny token to user lookup. But with a JWT, the server verifies the signature and simply reads the claims inside of the token itself. In terms of server storage needed, of course, opaque bearer tokens need that small lookup, but JWTs don't need any storage at all. And as for where identity lives, opaque bearer tokens have identity living on the server, but with JWTs, identity lives inside the token itself. So an opaque bearer token points to identity stored on the server and a JWT contains the identity right inside of itself. So, that's JWTs, fully stateless, self-contained tokens that the server can verify instantly. They sound pretty magical and used correctly, they're incredibly powerful. But because JWTs carry so much inside themselves, they also come with their own set of pitfalls, and some can lead to some pretty bad security problems if you're not careful. So, in the next Grim, we'll walk through some common JWT mistakes and how to avoid them. [clears throat] I'll see you there. We've now seen how JSON web tokens work. They're fully stateless. They're self-contained and they're verifiable without a lookup. But here's the catch. Some opaque bearer pitfalls still apply here. A JWT is still a bearer token. If someone steals it from you, they instantly become you. Same spoofing risk, same stakes. Not only that, but JWTs also come with a few extra pitfalls, little traps that exist because the token is self-contained and often contain more information about the user. So, in this grim, we're going to have a look at some big pitfalls. Number one, JWTs look encrypted, but they're actually not. One of the most common mistakes with JWTs is assuming that they're encrypted because it looks like gibberish, but they're not. They're just encoded, which is basically rotated text. In fact, we can actually pop that JWT from the last scrim into a decoder like this and we can see both the header and payload decoded. Now, the good thing is that only the server can verify the token because only the server has the secret that created the signature. So, we are safe there. But the pitfall still stands. If the token leaks, then the contents leak as well. This would be information disclosure with stride or sensitive data exposure with OASP. The simple rule here is this. Keep the JWT payload boring. No phone numbers, no emails, no private data, nothing you wouldn't put on a post-it note. Pitfall number two is weak or leaked secret keys. Now, while we can decode the actual contents of a JWT, a server won't trust it unless the secret ingredient or key matches. But that only works if the secret key is kept secret. If the secret key is easily guessable or leaked or pushed to GitHub, which is very common, an attacker can generate their own valid JWTs, they can literally create an I'm an admin token and the server will believe it. That's classic elevation of privilege. An attacker giving themselves higher permissions that they should never have. So, here's the rule. Use an unguessable secret and keep it safe. Pitfall three is that JWTs can get oversted. They can hold a lot of fields. So people often treat them like a mini user profile. Now this causes huge tokens and huge tokens causes big headers, slow requests, unhappy proxies and bloated logs. This also plays into the first pitfall. JWTs can be decoded. Do we really want these addresses, phone numbers, preferences, notifications leaked? Probably not. So the issues are this slow requests and potentially lots of leaked information. And that second one is an information disclosure problem or a sensitive data exposure because anything you pack into a JWT is immediately readable if that token leaks. So what do we do? We keep JWTs tiny. Only include what the server truly needs on every request. And pitfall number four, long life JWTs. You probably saw this coming from a mile away. Just like every other credential we've talked about, JWTs need an expiry. If somebody steals it or if the account changes, they can still use that forever. You can't revoke it. You can't force log out either. You just have to sit there and wait until the heat death of the universe. And here we definitely have elevation of privilege or broken authentication because we keep granting access long after it should have stopped. So the fix here and you know it JWTs must always have an expiry and the short ones are the safest. So those are some pretty big JWT pitfalls. They do fix the lookup problem, but they come with their own risks, and they still inherit all the usual bearer token issues. So, we've covered opaque bearer tokens and JWTs. Now, let's put them both into practice. In the next Grim, you audit a few scenarios, find some problems, and suggest some fixes. I'll see you there. Welcome back. We've now explored both forms of stateless identity, opaque bearer tokens, and JSON web tokens. and we've looked at where each one can go wrong. So, in this groom, we're going to put that knowledge into practice and run a quick stateless security audit. Here in stateless challenge.js, I've come up with a handful of code snippets and scenarios. Up the top here, I've also listed our five bearer token pitfalls and our four JWT pitfalls, as well as the instructions of what to do. Each one of these code snippets or scenarios contains something that's risky, fragile, or poorly designed from a stateless identity point of view. Our job is to spot what's gone wrong and provide a fix. Now, some of these will have code fixes and some will just require a conceptual answer in the form of a sentence or two. For example, the first scenario here asks for a code fix, but scenario two asks for a conceptual answer. So, you would simply pop in a sentence of how you would fix this particular issue. So, let's work on scenario one together, which is under opaque bearer tokens. This is one of the records in the token user lookup. So, what's wrong with it? Well, it looks like it expires in the year 3000. And as always, this is probably just a typo, but still a pitfall. And this is bearer token pitfall number two, long life tokens. For the code fix, I'm just going to copy and paste the original and change the expiry to 30 minutes from now. And there's our super easy fix. Okay, it's your turn to handle scenario 2 and onwards. Take your time and I'll see you on the other side. Welcome back. How did you go? There were a few things to chew through. So, let's have a look at what we could have done. Scenario two. This is the token lookup after 3 months in production. We can only see four entries here, but there is a comment saying that there are thousands more. Now, obviously, I wasn't going to pop a thousand lines here, so we'll just have to imagine. Now, thousands of records in just 3 months. That sounds like bearer token pitfall number four, token lookup bloat, because expired tokens were never removed. In fact, we can see that every single one of these would have expired back in October of 2025. So, here's a quick oneline conceptual fix. Add a regular cleanup job that removes expired tokens. And that's it. Let's move right along. Scenario 3 starts with another lookup followed by a variable that holds today's date and then a function which is called on every request. It tries to authenticate a user from the bearer token that the request brings. On the surface, this looks pretty harmless. The function does take the token and then check if it exists in the lookup and then it returns either the record itself or null if it doesn't exist. But here's the problem that's lurking in the shadows and it's bearer token pitfall number three. no automatic revocation. Now, this function is accepting any token that exists in the table, regardless of expiry. So, let's fix it up with a bit of JavaScript logic. I'm going to grab the code of the function and pop it down here. And we're going to add a bit of logic to it. Up here, we already have the variable now containing the current date and time. So, we'll just have to use another quick check here before returning the actual record. Now, if the records expires property is less than or equal to now, we're going to return null. And at this point, we can also remove it from the lookup. Luckily, we have the index and we have the splice method. So, from token table three, we're going to splice at the index and just one of them. And now we've hit two birds with one stone. Moving on to scenario four. Now, here we find out that there was a recent security breach in our system. and we're given a before and after snapshot of one part of our token lookup. Now, this might have taken a little while to find, but it looks like user number one, who used to be a user, is now an admin. It would appear that during the security breach, our token lookup was changed. And that is bearer token pitfall 5, tampered lookup. The fix here is conceptual. There's no piece of code that we can quickly whip up here to fix this. So here I wrote to protect the token lookup as carefully as the rest of our user database, prevent injection, lock down admin tools, and [clears throat] monitor changes. And with that, we're on to JWTs. Here in scenario 5, we can see the payload going into a JWT. Well, this one's pretty obvious, isn't it? There is way too much. from sensitive data like a street address all the way to unnecessary stuff like user switched tabs 14 times and resized the window. A JWT payload doesn't need any of that. So here we have JWT pitfall number three over stuffed JWT payload. Now fixing this is easy. We just have to include only the stuff that a server needs to determine identity. And I'd say that's just the ID name and the admin boolean. And now we've definitely lessened the strain on this JWT. And finally, scenario six. This server config is used when issuing JWTs. There's actually two issues here. First, that secret is way too easy to guess, and it's kept in the server code in plain text, [clears throat] so it's probably committed to GitHub as well. So, we've got JWT pitfall number two, weak or leaked secret keys. Another issue is the missing expiry. This JWT is never going to expire and with no lookup or use a session as a fallback, this is literally going to stay valid forever. So JWT pitfall number four, long life JWTs. And the fix here is conceptual because it will take too many steps than we can talk about in this one script. So here's what I suggested. Use a long random secret loaded from a safe place like environment variables and always include an expiry claim so tokens are short-lived. Wow, that was a lot. Well done on getting through all of that. By now, you should be feeling more confident spotting stateless identity problems in the wild and just as importantly, knowing why they matter and how to respond to them. In the next Grim, we're going to switch gears completely and look at a different approach to identity altogether. One where your app doesn't have to verify users directly at all. So, when you're ready, let's move on. Welcome back. We've spent the whole module so far looking at systems where our app handles identity. First with stateful sessions and then with stateless tokens and now we're going to switch to something completely different. Delegated identity. You know, you've actually seen this everywhere. When you sign up for an app and you see buttons like sign in with Google, Facebook or GitHub, that is delegated identity. Under the hood, most of these flows use a standard called OO, which is the protocol that apps use to delegate identity checks to providers like Google. In these cases, your app isn't checking a password. Your app isn't verifying the user directly. Instead, it asks a trusted third party provider to do it. For this scrim, we're going to use Google as the example simply because almost everyone has seen that flow. But just keep in mind that Google is just one oorthth provider amongst many. Now, before we go any further, we need to clear up one thing right away because it trips almost everyone. OOS is mainly about authentication, the kind that we already know about and the part we actually care about in the section. Google checks the user's identity, who they are, and that's the authentication we've been talking about this whole time. But then there's also OOTH authorization, and this is completely different from the authorization we talked about at the beginning. This has nothing to do with our app's internal permissions. Instead, it's about what parts of the user's Google identity our app is allowed to access. If you've ever used Google to sign up or sign into something, you've probably come across a screen that looks like this. Here, the app is asking for our permission to use our name, profile photo, and email address from our Google identity. And depending on the app, you might get asked for some more permissions. Here you can see that this app wants access to my contacts, more of my contacts, my calendar, my Google Workspace directory, and all of my emails. It's super nosy. Now this is different to the authorization that we know about. All of our apps authorizations like admin roles, user roles still happen inside our backend after authentication takes place. So just to be clear from an authentication point of view, OOTH just answers the question who is the user for us. Okay, let's look through the classic sign in with Google flow. First the user gets prompted by the app to login via Google. Once this button is pressed, the user gets redirected to Google. Here, our app is basically saying, "Hey, Google, you handled the login. I don't want to deal with this." And at this point, the user has left our app temporarily and is interacting directly with Google. The user is now asked to log into their Google account. And once that login is successful, Google confirms that this is in fact a real user with a real identity. Depending on the app, Google might now show the permission screen. Remember, these permissions aren't about our app's roles. They're just about the parts of the user's Google identity that our app can access. If the user agrees, Google sends our server a temporary one-time code or an approval code. This doesn't log anyone in. It simply represents the user's approval. Our server immediately sends that code back to Google along with our app's secret credentials. This lets Google confirm that it really was our back end that requested the login. And after all of that back and forth, Google replies with an ID token so we know who's logged in. Now our app knows that this user has been authenticated by Google and they're legit. So we log the user into our system. And that's delegated identity. Who knew that so much happens behind this super handy button? Notice that our app never handled passwords, never verified the user directly, and never stored the user's credentials. We let a trusted provider take care of that for us. But oorthth, as fancy as it is, also introduces brand new risks. So in the next scrim, we're going to look at some common oorthth pitfalls and what we can do about it. I'll see you there. Delegated identity and oorthth are fantastic because we never touch passwords at all. We let something like Google handle that part for us. But ooth also involves something unusual. We send the user away from our app and then we trust Google to send them back. Now, this round trip introduces a few places where things can quietly go wrong. Pitfall one, asking for too much information from Google. Remember this oorthth authorization screen. This is part of the authentication process, so we do have to keep an eye on it. Most apps will only ever ask for the name, profile photo, and email address. This helps give a personalized experience for sure, but sometimes apps ask for a lot more, more than is required. Now, this example is actually an AI powered personal assistant. So, this app does actually need access to my contacts, emails, and calendar events. But a lot of the time when setting up the oorthth flow with Google, a developer just takes all the options, usually by accident or they're not sure of what they actually need. But this causes two really big problems. If anything ever leaks, attackers get far more access than they should and users lose trust pretty quickly if an app feels nosy. And that first one is essentially an information disclosure issue or sensitive data exposure. So the rule of thumb is simple. Ask for the smallest amount of Google data that your app genuinely needs and nothing more. Pitfall two, a little ooth code that appears when it shouldn't. Remember that one-time code that Google sends the server, the one that we then send back in exchange for the real token? Sometimes that code ends up in places it really shouldn't, like the browser history, analytics tools, server logs, or the URL itself as part of a redirect. If someone or even a script running the page sees that code before it expires, they can use it to finish the login flow and impersonate the user. Now, this is a straight spoofing issue or broken authentication because leaking that little code lets someone else finish the login and then pretend to be the user. So, even though the code is small, inconspicuous, and expires pretty quickly, keep it from being exposed and will save ourselves from this particular pitfall. And finally, pitfall three, trusting Google's ID token without checking it. At the end of the flow, Google gives us an ID token, essentially a signed note saying, "This user is logged in. A very common mistake is to accept that note without verifying it because anyone can write a note. So our back end needs to check that the token was actually signed and sent by Google, that the token was meant for our app, and that it hasn't been tampered with. If we skip those checks, attackers can create fake identity tokens and pretend to be anyone. And just like the last pitfall, this is a classic spoofing or broken authentication issue. The right way to go is simple. Don't trust anything until you're sure that Google actually sent it. So, those are some big oorthth pitfalls. Scopes that ask for too much, little code that ends up in the wrong place, and identity tokens that must be checked properly. In the next grim, we'll have a look at a few small oorthth examples and try spotting what's risky. It'll help cement the concepts without any technical setup. I'll see you there. Welcome back. We now understand what delegated identity is doing under the hood. Google or another provider handles the login, sends our app a tiny code, and we exchange it for tokens that prove who the user is. So in this scrim, we're going to do a short simple challenge to practice spotting those issues in the real world. Here in delegated challenge.md, I've written a few short scenarios. Each one describes something that can quietly go wrong during an oorthth login flow. No code, no syntax, just tiny realworld situations. Also at the top are the three delegated pitfalls we learned about in the last scrim as well as instructions for this challenge. We'll do the first one together and then you can try the rest. So let's have a look at scenario one. Your app only needs the user's email to log in. But your oorthth request also asks Google for access to contacts, calendar, and drive files. Now this is definitely pitfall one, asking for too much information. Even if it's unintentional, this creates a couple of problems. If this token ever leaks, it exposes way more of the user's data than the app needs, and it makes the app feel nosy and untrustworthy. And the fix here is pretty straightforward. Only ask for the parts of the user's Google identity that your app will actually use. Nice and simple. Nothing technical, just the concept. Okay, now it's [clears throat] your turn for scenario two and onwards. For each scenario, jot down the pitfall, the implied risk or risks, and a potential fix. And when you're ready, come back and we'll walk through them together. I'll see you on the other side. Welcome back. Let's walk through these one by one and talk about the risks in each scenario. Scenario two. During login, the Google consent screen warns that your app wants permission to delete calendar events even though your app never uses Google Calendar. Now, this is another example of pitfall one, asking for too much information. The risk here is that a leaked token could cause some real damage. And even before that, users may even lose trust when they see permissions that don't make sense. The fix here is simple and basically the same as scenario one. Only request oorthth scopes that your app actually uses and nothing more. All right, scenario three. After the user logs in with Google, the page briefly shows the short-lived oorthth code in the URL. Now, this is pitfall number two, leaked approval code. A sensitive credential is ending up somewhere it shouldn't. And the risk is that URLs get logged, saved, and shared. So, if someone captures that code before it expires, they can finish the login flow themselves. The fix here is to never expose Oorthth codes in the URL, handle the exchange immediately, and keep credentials out of anything that can be logged. Scenario four, your back end receives the ID token from Google and immediately accepts it without checking the signature or whether the token was actually meant for your app. This is a classic pitfall three, blindly trusting the returned ID token. The risk is that anyone can create something that looks like a Google token, but only Google can sign it properly. If your app skips verification, attackers could forge a token and pretend to be any user. So, the fix is simple. Always verify the ID token signature and audience before you trust it. That way you know it's legit and meant for your app. Last one, scenario five. Your back end accepts an ID token that expired an hour ago. And this is another case of pitfall 3, blindly trusting the returned ID token. And here's the risk. Expired tokens can be reused. If the server accepts tokens regardless of expiry, an attacker could replay an alt token and log in as the user over and over again. And the fix, always check the token's expiry and reject it once it's no longer valid. And of course, our last pitfall scenario has to be expiry related. And that's the whole challenge. If you caught most of those issues, you're right on track. Oorth seems magical on the surface, but once you understand the flow, you immediately start recognizing the little places where things can drift off course. Now that we've explored all three identity models of stateful, stateless, and delegated, we can finally step back and compare them side by side. So, in the next grim, we'll zoom out and look at how they relate, where they shine, and why real apps often combine all three. I'll see you there. Welcome back. Now that we've explored stateful, stateless, and delegated identity on their own, we can finally zoom out and see the bigger picture and check out how they behave when you put them next to each other. So, let's take a look. Stateful systems anchor everything on the server. Identity lives there, trust lives there, and control lives there. When you check it out alongside the others, one thing really stands out. Stateful systems optimize for control and immediiacy over convenience. They're predictable, easy to update, and easy to revoke. But they also create this central point that has to scale, sync, and keep up with traffic, and that can be difficult the more servers you have to handle. Opaque bearer tokens point to the server in order to identify a user. Identity still lives on the server like in stateful systems, but only in a small token user mapping. This does remove the need for a big shared session store. So the OPEG bearer tokens standout trait is that they make the server lighter, although not completely free. You still need a small lookup, but the pressure on the back end drops dramatically. It's a pretty practical halfway point between the server remembers everything and the client carries everything. And speaking of which, JWTs extend the stateless idea to its logical extreme, placing the entire identity inside of the token itself. And once you compare it with the others, their defining characteristic becomes obvious. They prioritize distribution and speed above everything else. No lookup, no shed store, no coordination, and therefore no server load, just a signed object that the server can trust instantly. Although it is a harder fight when you need to revoke or roll back access. And finally, delegated identity is where we trust a third party like Google to provide identity services. It shifts the responsibility elsewhere outside of our system entirely. And this is of course super handy as we don't have to worry about any of that ourselves. But we do also inherit the complexity of that relationship. We have to learn how to work with that third party provider in order to get it right. So when you lay all three systems side by side, their purposes become clear. Stateful is for control. Stateless is for scale. And delegated is when you want to offload trust. This isn't about which one is the best overall. This is about figuring out which situation is best for which option. So, in the next grim, we'll look deeper into how to pick an identity for different situations. I'll see you there. Now that we can see the three identity models as a whole, the next step is understanding when to use each one. This isn't a checklist or best practices chart. It's a way of thinking. Every system makes trade-offs, and choosing the right one is really about deciding which trade-offs your app can live with. So, let's walk through it. When does stateful make sense? Stateful shines when the server must stay in charge. If your app needs instant logout, live roll updates, or tight control over user state, a server held session is the simplest, cleanest way to get you that. It's stable. It's predictable and ideal for traditional apps, dashboards, admin tools, and anything where trust and control matter more than horizontal scale. So, when does stateless make sense? Stateless models shine when your architecture needs room to stretch. If you're building APIs or really anything that needs to scale without coordinating shared session state, letting the client bring the token themselves removes that friction immediately. Opaque tokens keep it simple and JWTs remove the lookup entirely. Both options reduce the server load just at different extremes. And when does delegated make sense? Well, delegated identity makes sense the moment you realize you don't want to run a password system at all or if onboarding speed matters, if friction matters, or if you want a stronger security baseline without writing your own. Trusting a provider like Google or Apple is the fastest and safest way. Your app shifts from proving identity to consuming it. And here's the final mindset shift. Sometimes you don't just pick one. Real systems combine these approaches all the time. A delegated identity to prove who the user is, a JWT for API calls, and a simple session for the main website. Each of the three solve a different slice of the identity problem. Understanding how they fit together is the skill that lets you design authentication intentionally instead of reactively. So that's the big picture. Choosing an identity model isn't about memorizing features. It's about understanding what each approach gives you, what it takes away, and which trade-offs your app can live with. So with that mindset in place, you're ready to put it into practice in the next scrim. I'll see you there. Let's finish off with a quick challenge to check if we know what identity is best for what use case. I know I said at the beginning there would be one challenge per identity family, but I figured one more wouldn't hurt. So, here in the editor, there are a bunch of scenarios that need an identity solution. Which identity model would you choose for each and why? Let's do this first one together. As always, a classic web dashboard used by internal staff. Admins need instant logout. Permission changes should apply immediately. And security is more important than scale. This is a perfect job for a stateful identity. Why? Because the server is in charge. If you change someone's role or want to log them out straight away, it takes effect instantly. And for a normal web page in a browser, sessions are simple and reliable. So, stateful is the safest, cleanest option here. Stateful identity. The server needs to stay in control. Okay, your turn. Give each of the remaining scenarios a go and think about what identity solution you would use for each of these. Think it through, choose your model, and write up a short explanation. I'll see you in a little bit. Welcome back. Let's get right to it. Scenario 2 is a public API for a mobile app. For these, we usually don't want the server to keep track of lots of user sessions. It's much easier if each request brings a token and the server can quickly check it and move on. So, stateless tokens are the best fit here. Either opaque tokens or JWTs. They keep the backend simple and easy to handle as more people use the app. Moving right along to scenario three. This scenario has a large micro service architecture. When lots of small services need to talk to each other, you don't want them all checking with a central server to see who's allowed to do what. It's much easier if each service can quickly identify a token on its own. And that's why JWTs will work well here. They're self-contained and every service can trust them straight away. Scenario four is a consumer app with easy sign up, ideally with Google or Apple. Well, this one is very clear. If your whole goal is to sign in with Google and fast onboarding, then you don't want to handle passwords at all. So, delegated identity is definitely the right choice here. Scenario 5 is a single server hobby project. When it's just you, one server, and a small app, the simplest option wins. Stateful sessions are easy to set up, easy to understand, and you don't need anything fancy. No tokens, no oorthth, just a small session table and a single cookie. And that's it. Nice work. Choosing the right identity model isn't about memorizing features. It's about learning how to think about control, scale, and trust. You've now seen how stateful, stateless, and delegated identity each solve different problems. Now, let's finally move on and wrap up our identity journey in the next scrim. Well done. Seriously, well done. You've just made your way through a fundamental part of back-end security, understanding how modern apps handle identity. In this section, we first learned the difference between authentication and authorization, who the user is, and what they're allowed to do. We then learned how to think about identity three different ways. Stateful identity when the server remembers who the user is. Stateless identity when the client brings proof every time. And delegated identity when another provider does the logging in for you. You learn how to reason with them, how to spot weak points and what made each one safe or unsafe and what threats they defend against and what they're prone to. Most importantly, you can now look at any login system. cookies, tokens, JWTs, oorthths, and understand the trade-offs behind it. You can ask questions like where does identity actually live? How does the server know I am who I say I am? What happens if this part leaks or expires or is tampered with? Which model fits my app and why? And this is the exact thinking that shapes real security decisions. From here, every backend you build and every OOS button you click in the wild will look different. You'll see the patterns, the risks, and the design choices hiding underneath. So, take a moment because this is a huge achievement. Most developers only ever learn these ideas indirectly, but you've taken the time to understand them properly. Well done again. Truly, thanks for hanging out with me, and I'll see you next time. Welcome to this course on rate limiting and throttling. My name is Jonathan Hill and I'm really excited that you are here. We're going to be learning what rate limiting is, the core concepts, the difference between rate limiting and throttling, client identification, time windows, and some common rate limiting algorithms, fixed window counter, sliding window log and counter, token bucket, and leaky bucket. And then there's going to be a section near the end on throttling, and of course, challenges along the way. So, what is rate limiting? So it can be used to control traffic flow to web servers, APIs or other online services. There are three main points here. Fair use helps organizations to ensure fair use of their APIs avoiding resource hogging by single clients. Ensures legitimate users can still access the service. Security preventing brute force attacks, login attempts and also mitigating those denial of service attacks. However, sophisticated DDoS attacks often use distributed sources, making per IP rate limiting less effective. So, this can require additional mitigation strategies like geographic filtering, behavioral analysis, or upstream protection services. And resources, we want to help protect resources by preventing overload, which can cause them to slow down or become unavailable. We want to maintain consistent performance, fast response times, and a smoother experience for those legitimate users. So, some core concepts now. Rate limiting is like a hard cap on requests per time period, whereas throttling is slowing down responses when the limit approaches. Client identification. So, this can be by IP address, an authenticated user ID, an API key, or a JWT claim. So there are a few different types of rate limiting. IPbased is commonly used to prevent DDoS attacks. Serverbased rate limiting is preventing resource exhaustion and ensuring fair use of server resources. And then geographicalbased is preventing attacks from specific regions such where like a large number of malicious requests might originate. When we're talking about rate limiting, we want to think about differentiating between user level limits and systemwide limits. And time windows can be per second, per minute, or per hour. Do we want a certain number of requests in 30 seconds or 1 minute? So now you know about those core concepts, a little about me. My name is Jonathan Hill. I'm a School of Code boot camp graduate. I used to teach music and perform music on stage. I worked a few years on cruise ships and I'm a proud cat dad to two Siberian fluffs. If you want to reach out, find me on the Scriber Discord community. The name's just Jonathan Hill. and I'm also on LinkedIn. Okay, let's get cracking. See you in the next scrim. Okay, the first rate limiting algorithm we're looking at is the fixed window counter. This is when the system counts requests in a specific window length and if this count reaches a set limit, it will start rejecting requests. So, it's quite a simple algorithm. The count resets at the end of the window. And you'll see in this example I give you that the state management required is quite simple because you just need to keep track of the count and the timer. So in my example, we have a parking garage. The window is 30 seconds and the limit is five requests or five cars in that 30-cond window. So here you can see window one is open because we are at the beginning of window one. T equals 0 and window 2 is closed for now. But at 30 seconds it will open. As long as there's a space free, i.e. we haven't hit our limit, new cars will be allowed to park, i.e. new requests will be accepted. So here we are at t equals0. A request arrives or a car gets to the barrier. Since there is space for the car, it is accepted. We progress to t= 5 seconds and we have two requests arrive. These are also both accepted because the count was only at one. Now it's at three. At 15 seconds, two more requests. These are both accepted, but the count is now at five. So, the barrier comes down and no further requests will be accepted in window one. So, when at 25 seconds, a new request arrives, I'm afraid it is rejected. As window one ends at t= 30 seconds and window 2 begins, we reset our current count to zero and the car park barrier rises. The system does not need to remember the count from the previous window. We progress through window 2 and at t= 50 seconds, two requests arrive. And these, as you can see, are both accepted. At 55 seconds, two more requests arrive. And at 60 seconds, as window 2 closes, window three opens and two more requests arrive, which are both accepted. Now, I want to show you something. Let's imagine that each car was given a ticket on arrival. And on that ticket, it has the time they arrived. So, let's have a look at the times on those tickets for windows 2 and 3. We've got two cars here that arrived at 50 seconds, two at 55, and two more at 60. Now, here we have seven cars, and they arrived between t= 50 and t= 60. Now, that's only a 10second period of time, isn't it? Hang on. This is over our limit of five requests in a 30-cond window. But since these cars arrived over two different windows with the fixed window counter algorithm, they were all accepted. This is called the window boundary issue where bursts can occur around the window edges i.e. at the end of one window or at the beginning of another window because of the very basic we're in one window that ends count goes back to zero. There is no flexibility there is there. Another point to make is that if say at the beginning of a window you had all five requests arriving, you would then have a drought because you wouldn't be able to have any requests after that because they will have all been accepted and reached the limit. And as I mentioned, any state management required for this algorithm is fairly simple. You just need to know where you are in the window with a timer and the current count that you're on. Okay, on to the next algorithm. See you in the next scrimm. Welcome. It's time to work on a simple practical fixed window counter example. For this, we're going to use an express API so we can fire multiple requests at an endpoint and see exactly how the rate limiter works. So, a little bit about our current setup. I have a server.js file here with a single endpoint at /appi/data. The JSON response is just going to be a timestamp and a little request count property. I've added a start script in the package.json so that we can use the scrimma runner to run our server. There it is. And so that we don't have to keep refreshing the browser to run multiple quick requests. I've written a test requests.js testing file. Let me briefly run through this for you. You're welcome to pause the video at any time to have a deeper look through this code if you wish. The make request function here returns a promise that wraps an HTTP get request. This is a common pattern for handling asynchronous operations in NodeJS. The response is going to be logging the request number and the status code and the JSON data. So the promise has a resolve and a reject. Resolve is called when the request succeeds passing the result data. reject is called when the request fails, passing the error. And if we scroll down, we have this demo rate limit function here. Here's where we're going to be making 15 very quick requests with a small delay between them. Here's our make requests function being called. So the flow of this is the HTTP request starts and HTTP.get is called, the response arrives and data event fires. The response completes and the end event fires. We process our response. Resolve is called with the result object. And if any error occurs, the error event fires and reject is called. And as I mentioned, set timeout when it's wrapped in a promise creates a delay between requests. This will make sure that the requests arrive in order. So request one, request two, if they all go at the same time, they won't necessarily all arrive in order. Let's see this in action. So in the terminal, I just need to run node test- requests.js. And we see it happening very fast. So let's scroll back up. We've got request and the request number, the status code, and then if we look back in server.js, we see a timestamp and request count unlimited because we do not have a rate limiter set up yet. And we go down and we have 15 in order. Brilliant. So for rate limiting, we're going to use this npm package express rate limit. If you could click this title to bring you to the docs, you're going to be using them later. This is middleware which sits between the request and the endpoint. It counts requests in a specified time window and blocks requests if it exceeds a set limit. Now it's important to make a point here. If in the docs you could search in the configuration part for the window MS configuration property. I told you in the theory scrim earlier that the windows in fixed window counter keep ticking along regardless of if requests are hitting the API. This package is a little bit different to that. We can see in the docs that the window ms that we're going to be specifying later, the length of the window is quote a time frame for which requests are checked remembered. The time window for each user starts at their first request. After it elapses, the user's hit count is reset to zero. A new time window is then started on their next request. So it's not going to be a pure fixed window counter where the window resets on schedule regardless of activity. We call this maybe a lazy initialization of a window. It only starts when the user makes a request. Please keep that in mind as we use this package and learn more about the fixed window counter. So it's a bit like a club bouncer who counts people and stops them at the door if the capacity has been reached. So I'm going to install this using npm i express rate limit. And then we import the library at the top. It's called rate limit. There we go. Join me in the next grim where we're going to create the limiter in this server.js file. Okay. Time for some collaboration. Now here's your challenge. I'd like you to use the package docs to create a rate limiter using the rate limit function. I want you to allow five requests per 60-second window. And let's set a response message of too many requests. Please try again later. Now, if you don't have the package docs ready, you can always click on the slides. Here they are. Let me go back for you and click this title here. Remember that I've already imported rate limit here and that's what you're going to be using. You can code just below the challenge text here. And the quick start usage part of the docs may be helpful, but if you want to get a bit deeper, have a look in configuration. Okay, good luck. See you in a minute. I hope that went okay. So, let's create a limiter. So, as I said, we're going to use this rate limit that I imported earlier, and we pass to it an object. And that's going to have a few different properties. Limit, window, ms, and message. Those are all the things that I ask for. So the limit, I ask for it to be five. The window I want it to be 60 seconds. So since we're in milliseconds, millie is three zeros and then we put however many seconds before that. So that's going to be 60,000 milliseconds. And let me copy the message so I don't make any typos. There we go. Now as you saw in the docs hopefully you have to create a variable which is going to be the limiter. So let's call it limiter. So original. There we go. Let's get rid of the text. Now where are we going to use this limiter we've just created. So in the docs it says to use it only for a certain endpoint. Add the limiter as a middle argument to app.get or app.post etc. So we can see here here's the limiter. it's between the path and the handler. Now, one thing to note here is that once you've applied the rate limiter here in between these two, the middleware then attaches data to the request object. So, remember here's the request object that we can use down here in the JSON response. So, if we wanted to say create another property here to remind us of the limit, we would use wreck and then it's attached as dot rate limit. Remember wreck is the request object and then the middleware once it's in between here which is what you're going to do in a second attaches this rate limit object to the request object. And there's a few properties that we can access here. We can go into it and find limit or if you wanted you could find the remaining requests allowed before the rate limiter kicks in or reset which is when the window is going to reset. Now, a bit of a warning here. Including weightlimiting info like this in the JSON response is not the final way we're going to be doing this. It's worth knowing that it's there as an option, but it's much better somewhere else in the headers and we'll talk about that later in the course. Okay? But for now, it's just good to know and I'm going to get you to do it just so we can see some of the data. So, next challenge. Here we go. Use the package docs to apply the rate limiter to the endpoint. Now, I just mentioned where that needs to go. Keep the time stamp in the JSON response, but change the request count to a remaining requests property. Take this new property's value, the number of remaining requests allowed before the rate limiter kicks in. Use the optional chain operator to safely access this property. Okay, so everything you need to do there, I have just gone through that. Good luck. I'll see you in a second. Okay, I hope that was all right. So we take our limiter and we put it in between a path and the handler. There we go. Now the limiter is applied. We're going to change request count to remaining requests and the value of this is going to be the remaining requests allowed. So remember I said that the attaches data to the request object. So here's the request object and we need to go into rate limit property and in there we want remaining use the optional chaining operator. So to safely access the remaining property even if rate limit is undefined or null let's use our question mark there. And if we wanted to go above and beyond, we could use the nullish coalesing operator at the end of here, the two question marks to provide a fallback value if the left side of the question marks is null or undefined. So why don't we go for unknown? There we go. Okay. Every time we change any code in server.js, we need to rerun the runner. So here we go. Rerunning that. Brilliant. And now we can test node test requests.js. Oh, something's different here. How many 200s have we got? 1 2 3 4 5. But then after five at six, we start getting 429s. Too many requests. Please try again later. And because they happen so fast, our 1 minute window did not finish. But you can imagine if id spaced these out every 10 seconds then we could have seen that once the window had reset we would start getting our five 200 success again and the remaining requests has worked as well because after one request we have four left after two three you can see that and then at five requests we have no remaining hence why request six is 429 rejected. Brilliant. See you in the next scrim where we're going to talk about headers. We have our basic fixed window counter example rate limiter working. That means I should probably change this single endpoint with rate limiter. That's better. So I mentioned in the last scrim that including rate limit info in the JSON response wasn't going to be the final way we were going to do this. Headers are where metadata system information about the communication should live for best practice. So we've got rate limits, we've got content type and status codes. But the JSON is for the application data, what your app actually needs. And without headers as well, you only know you've hit the limit when you get a 429 too many requests. So we're going to be modifying this and taking this rate limiting info out of the JSON data and using the headers instead. Headers also show the user accurate information potentially about cost management. We know that many APIs cost per request or have a sort of tiered pricing while headers can help you track usage in real time. Avoid wasting paid requests and budget API calls across different features and they're fantastic for debugging and monitoring purposes. So there we have it. Standard practice. They are the official way to communicate rate limiting information according to HTTP standards. Headers are sent with every response, even when rate limited with a 429 status. And they're easy to read. Any HTTP client can easily read headers without passing JSON. Now, we have an old format that rate limiting headers used to be written. That was with an X- rate limit dash and then either limit, remaining, or reset. A new format of headers became standard around 2021 2022, which look like this. They're called rate limit dash instead of x rate limit. But the old legacy headers are still seen out in the wild. So it's good for you to be aware of both. Now you may have seen while looking at the mpm docs earlier that there are some other properties that we can add here to this object that we're passing to rate limit and they're going to be standard headers and legacy headers. Standard headers actually defaults to false and legacy headers defaults to true. But because we're going to be forward thinking, we're going to change these by specifying true for standard headers and false for legacy headers. So let's save that. Now in the next screen, I'm going to show you how we can see these headers when we send a request to this API. See you there. Time for us to see these standard headers that we have turned on here. So, I've got a little challenge here for you. I'd like you to navigate in the mini browser to the / API/data endpoint. Then, I'd like you to bring up your browsers developer tools. And in Chrome, that's F12. In other browsers, I'm sure you can find that information using Google. And open the network tab. And then with that open, I want you to refresh the Scriber mini browser which will send a request to the API endpoint. You should see in the developers tools a little data request payload. If you click on that and select headers, you should see the rate limit headers. And because we've turned on standard headers, it should look a little bit like this. You should see rate limit- limit, rate limit- policy, rate limit- remaining, and rate limit- reset. So this is the little data payload I mentioned. And you'll only see this after you've refreshed the mini browser, i.e. you've sent a request. And here is the little headers menu you'll need to see. And you may need to scroll down in this box to see the rate limit headers. Okay, good luck. Okay, I hope that worked. Don't worry if it didn't. We're actually going to see the headers in a different way in a second in the terminal. So the way we're going to do that, let me clear this up, is I'm going to go into test requests and we're going to actually extract the headers. So I'm going to do that up here and I'm going to make some variables. I'm going to make one called rate limit limit. So we're going to extract the rate limit headers from the HTTP response. So that is res and we use headers and then in square brackets we specify as a string which header we want. And because this is the limit, it's going to be called rate limit dash limit. Now, I feel like you could do the other two for me. So, here's a quick challenge for you. In a similar format to rate limit limit, continue to extract the rate limit headers for rate limit remaining and rate limit reset. So, this can be just under here. Good luck. See you in a minute. Okay, I hope that made sense. So, let's make some more variables. Let's keep the same format. So, we're going to go rate limit. And this is going to be remaining. And I'm going to just copy the rest of this. And instead of rate limit, limit, we're going to go rate limit remaining. There we go. And let's copy the whole thing just to speed things up. And this is going to be rate limit reset. Brilliant. I hope that was all right. Just keeping the same format there. So now to use this, I'm going to add some console logs here so we have all of the information in a nice format and then I'll explain what's going on. Okay, so at the top here, I've got our current date and then I've worked out what time the rate limiter will reset by getting the time from the current date, adding how long until the reset, times it by 1 second, and that's going to be our reset date. Then here are the headers that we extracted. We've got rate limit limit, rate limit remaining, and rate limit reset. And then here's the reset time. So it's our reset date to do to local time string and the current time. So we can see the difference if we want to and the response. You'll see this all in a second in the terminal and it will make sense. But now because we're extracting the headers, we don't need to use it in the JSON response. So we're going to remove this line here and just leave the time stamp. And because we modified server.js, let's rerun the runner. and in the terminal. Let's see what happens. There we go. Now, as you can see, we have a lot more information now. So, we have request number one. So, we have which request it is and the status code. We then have a line for headers. It's telling us the limits five, remaining four, and we're going to reset in 60 seconds. It tells us the reset time, 604. Current time here is 603. So that's in 60 seconds. And there's our little timestamp response. Now, as we get to request two, obviously remaining goes down by one. Remaining goes down again. This is similar to what we saw in the previous scrim, but now it's coming from the headers. Then we get our 429 after five successful requests. Now, you might ask, why is reset not going down? Well, because test requests, we've got such a tiny set timeout here. They're all essentially happening within a second. So fast that we're not actually seeing the reset go down at all. So in the future, we're going to space these out so we can see that changing. Okay, fantastic. We're going to modify our limit now and see how that affects the results. See you in the next scrim. Time for us to modify the rate limit configuration here. So far, we've seen five requests being successful and then the rest of our 15 all failing. This is because our 60-second window does not have time to reset. The requests are getting thrown at the API so fast, all within 1 second. I'm keen for us to modify this so that we see requests being successful, being limited, and us getting 429 failures, but then the window resetting and us getting successes again. So, time for another challenge. I'd like you to modify the rate limiter window to allow a maximum of three requests in a 10-second window. Then modify the demo rate limit function that's over in test requests. So it waits 2 seconds before making the next request. So if we scroll down here, here's demo rate limit. And remember that here is where we are pausing between requests. Then rerun the runner because remember whenever we change code in server.js js. Before we run the test requests.js file, we need to rerun the runner and run the test requests to see the limiter in action. And that's just node space test- requests.js. Okay, good luck. Welcome back. I hope that was all right. So, three requests. So, our limit is not five anymore, but three in a 10 second. So, this is 60 seconds. So, I'm going to change 60 to 10. There we go. Modify the demo rate limit function so it waits 2 seconds. Okay. So, we go back over here. We've got 50 milliseconds, but we're going to modify that. So, if we have three zeros, anything in front of the three is going to be seconds, and we want 2 seconds. So, 2,000 milliseconds is 2 seconds. Let's save that file. And we now save this file. I need to rerun our runner. There we go. In the terminal node. Here we go. So, lot slower now. You can see we've got 1, two, three, and the reset is changing. Right. We started at 10 seconds, we came to 8 seconds, then yeah, every 2 seconds. Brilliant. And if we scroll up, yes, because our limit is now three. So after request three is 200 success. We have request 4 429. Request five 429 and resets in 2 seconds. And then it's reset. It's gone back up to 10 seconds. And hey presto, we have a 200. Success. 200. 200. There's our three. So request six, 7, and 8 are the three. That hits the limit. And by nine, we're back to 429. Reject. And then we're back again. Request 11 to 200 when it resets. So the burst problem that I mentioned in the theory scrims, we can kind of imagine many quick requests will just all flood through and that counter resetting gives you that potential of a burst which may overwhelm the system. Okay, next grim we're going to be talking about client identification. See you there. We're now at the stage that we want to start talking about client identification. Rate limiting only really works if you can consistently identify who is making requests. The identification strategy that you choose determines fairness. Are you limiting the right entity? Effectiveness. Can users bypass your limits? User experience. Are legitimate users unfairly restricted? And security, can malicious actors exploit your identification methods? Make sure you always ask yourself who or what are you actually trying to limit? Now, the first common identification strategy is using the client's IP address as the unique identifier. Pros here that we have no authentication required. It works for anonymous users. It's simple to implement and it can't be easily changed by normal users. The cons there can be shared IPs. So sometimes multiple users are behind the same NAT proxy or VPN and they appear as one user. In corporate offices you might have hundreds of employees all working behind one IIP. In coffee shops and libraries that might be all one IP address and mobile carriers maybe are all one IP address. Dynamic IPs where the user IPs change that would mean they would get a fresh limit and there are IPv6 complications where users get different IPs from the same subnet. This could punish innocent users who are sharing the same IP. So this strategy is best for public endpoints with no authentication, DDoS protection and basic abuse prevention. So without realizing it, we've been actually using this strategy up to now in the package docs. By default, the client IP address is used. If you still have the package docs available, if you search key generator, you can start reading about how we can specify the client identification. So if we were going to add it here, we add a key generator property. We're told that this needs to be a function that accepts the express request and response objects. So that means we need wreck and res arrow. And this needs to return a string. So to use the IP, we're going to need to import something else from express rate limit. IP key generator. And then we use that here. and we pass to it the IP from the request just like that. So nothing's changed because as I mentioned this is just the default for express rate limit but it's good to see that here as we're going to be modifying in future scrims the value of this key generator property. Next we're going to mock up some orth so we can talk about using a user ID as the client identification instead. See you in the next scrimm. The second way to identify the client is using an authenticated user ID. So this could be from a session, a JWT or a database. The pros here are that each real user gets their own limit because they are the authenticated user. It's fair. Users don't interfere with each other. Users get the same limit regardless of location, device, or network. So, it's portable and you can't bypass it by changing IPs, so it's enforcable. The cons are you would require obviously an authentication system. It doesn't protect unauthenticated endpoints and it won't catch abuse before account creation. So, this is best for authenticated API endpoints, user specified quotas, SAS applications with tiered pricing, and per user feature limits. So, I've made a little mock orth here. I know this isn't the real way the orth works, but it's just to simulate it for the purposes of this scrim. We're going to be checking for this header in the request. We're then going to attach the user object to the request, and then we're going to be asking our rate limiter to use that user ID as the identifying characteristic. So, over in test requests, I've had to modify this a little. I'm now passing an options object to the get request. And here's the options object. And this is the custom header that we're going to be sending. It's going to be called x- user- ID. I've added it here in the console log. So, we're going to see that when we read about the response. And then at the bottom here, I've modified our demo rate limit function because we're going to be making three different demos. The first one is going to be with user one, the second one with user two, and demo three is going to be actually alternating between user one and user three. So this is quite a real world situation where we have multiple users firing requests at the API. So back up to the top, you can see here we're passing that user ID to make requests. Now in a real world authentication flow, we would not be sending the user ID in the headers, but this is the only way that it can work here in this script. In a real world flow, the user would login with credentials. The server would validate the credentials and create a token, maybe a JWT or a session cookie. The client then stores that token and sends it with every request. The server then validates the token and extracts the user ID from it. But this is just a more direct way because we don't have real orth here. Right? A little challenge for you. So I'd like you to add the property down here to this object we're passing to rate limit to specify the key for the rate limiter to use. In the previous screen when we were talking about IP addresses, we used a specific property name and then we used that special IP key generator. Oh, we can actually get rid of that, can't we? Because we're not doing IP anymore. So, have a think back. If you need to look at that previous scrim, be my guest. But we're going to make the key this time the user ID from the mock orth middleware. So, you can have a look up here and think where we're going to access that user ID. So yeah, it's going to be quite similar to the PR scrim, but the value of the property here is going to be different. Don't worry if you can't work it out. I will show you in a second. Okay, good luck. Okay, hope that was all right. So remember the property is called key generator and it needs to be a function that accepts the express request and response objects and returns a string. So before we passed rec res, we had our arrow and then this needs to return a string. Now we don't need to use that import from before because we now need the user ID and the user ID has been attached to the rec do user. So we're going to go for rec do user here and then access it with the dot and then ID. And you see how res isn't being used. So actually we don't need it necessarily. We could just clean it up like that. Brilliant. I hope that was all right. Don't worry if you didn't quite get there. Now, we can see up here that mock is gray because we're not actually using it. So, we need to add it to this end point. Now, Express executes middleware left to right. So, we want the mock to work before the limiter. So, we're going to put it just there. So, we want the mock to run first. It sets the wreck do user ID. And the limiter runs second. It uses rec do user ID for rate limiting and then the root handler runs last and sends the response. Okay, let's run this. But before let's just have a little prediction of what's going to happen. So user one is going to fire five requests. User two is going to run five requests. And then user one and three are going to go back and forth. Okay, hopefully they're going to have their own limit because they're different users. Okay, let's rerun the runner and let's run this. This is going pretty fast. Don't worry, we're going to go through it together. So, demo one, user one, we have a 200, two remaining, 200 one remaining, 200 remaining, and then 429 429. Okay, that's pretty normal. Then immediately if we look at the current time here 5850. So yeah pretty much immediately afterwards demo two starts and user two since we've already got 8 seconds till reset. But demo two starts with user two having a fresh limit because they've got a 200 and they're back to 10 second reset. So user two has a 200 two remaining 200 1 remaining 200 remaining and then two 429s. Now this is where it gets interesting. Demo three. So user three is a new user. They have a fresh limit. But user one, they're still 4 seconds to reset. So they're still 429. So user one's reset time has stayed counting. And then user three is still on 200. One remaining. User one still not quite reset. User three, there's their last success. User one then has reset. Back to 200 success. All right. Fantastic. So we see how each user has their own rate limit window and counter when we specify that the key for the rate limiter should be a user ID instead of the IP address. Next up, we're going to be talking about API keys and session IDs. See you there. The third client identification strategy is using an API key. This is common in developer APIs. Pros here are that it ties to a specific application or integration. You can have different tiers, free, pro, enterprise. It's revocable if abused. and it's easy to track usage. The cons though keys can be shared or leaked. It doesn't identify the end user. One key could serve thousands of users and it requires key management infrastructure. This is best for third-party API integrations, B2B APIs, and tiered service plans. So API keys are commonly sent via headers. So we could set this up in a similar way to before using key generator and we only need the request object. So we're going to say wreck and [clears throat] then we go into wreck and use headers as we did before. And let's imagine it's called X API key. This isn't going to work with our actual setup. It's just a little example for you. And then to show you how this could work for a tiered system, let's imagine the limit is actually a function. So we could pass the request object as well. And let's imagine we had different limits per tier. So we could make a tier variable and then say if we had a get user tier function earlier in the program, we call that. We could then pass in our API key which should be accessed in the same way and this function could return if tier is say pro let's use a question mark then the limit could be a th00and and if it's not maybe 100. So that's just an example of using an API key as client identification and then making a tiered limit. The final solution for a client identification could be session ID. This could be a cookie or a session token. This works well for logged in and guest users. It's more persistent than an IP and it can span multiple requests in a user journey. The cons, users can clear cookies or sessions to reset. There are session fixation concerns and it doesn't work for stateless APIs. So this solution would be good for web applications with sessions, shopping carts, checkout flows, and form submissions. So you're going to start seeing some repetition here, but we could again pass the request object our arrow and then you go into that request object and if there was a session, you could access the ID inside it. So again, this won't actually work here in practice, but it's just to see how we would use the session ID for client ID. So in the real world, you might want a hybrid approach. So combine multiple identification methods with fallbacks. So you could start with an authenticated user ID and if there isn't one of those, you could use an API key for integrations. And then if there's not one of those, the session ID for guests, and then use the IP address as a final fallback. Okay, well done there. We've finished this section on the fixed window counter example. Any questions you have, please ask them in the Discord community or use some AI. Take a quick break if you need it and then crack on with the rest of this course. Our second common algorithm is the sliding window log algorithm. Instead of the window existing and resetting regardless of traffic like in the fixed window counter, this window is being calculated dynamically when each request arrives. In sliding window log, the system looks back a certain length of time, the window length, and counts how many successful requests have occurred in that time range. It then decides whether to allow or reject the current request on that calculation. We're therefore going to have to store timestamps for each request. So the system knows exactly when each successful request arrived. It's more accurate than the fixed window counter since there's no boundary issue, but it's more memory intensive. It's called sliding window log because as requests arrive on a timeline, you'll see this later on in the slides. The window the system is looking back is sort of sliding along, constantly checking the window length behind each new request and counting the successful requests in it. So an example, we're back to the parking garage. We've got a 30-cond window and the limit is five requests. So at t=0, the first request arrives. You can see below the car, we are tracking what time the request arrived. At t= 5 seconds, two more requests arrive. And because 30 seconds behind 5 seconds is all of the seconds we've had so far, the system counts requests and only counts up one. And that's below the five limit. So we allow both of those. At t equals 15 seconds, it looks back 30 seconds and counts the successful requests and it gets to three which is below five. So they are both accepted. And at the current time point 15 seconds, we are now at the limit of five requests in the previous 30 seconds. At t= 25 seconds, another request arrives. The system looks back 30 seconds, which is from 0 to 25 seconds, and counts five. So we reject. However, at t= 35 seconds, the system looks back 30 seconds and that window is now from 5 to 35 seconds. That means the car that arrived and was accepted at 0 seconds is not in the window. So that sort of falls out of the window and the count is at 4. So that means this request at 35 seconds is accepted. Now at t= 40 seconds, we get three requests arrive. Can you have a think about what's going to happen now? The window is now from 10 to 40 seconds. So the two cars that arrived at 5 seconds and were accepted fall out of the window. We have a current count of three cars. So two are allowed, one is rejected. So on a timeline, this looks like this. The green are accepted requests and the red are rejected. We had one at zero, two at five, two at 15. And then when the request arrived at 25 seconds, the window going back 30 seconds, it can't go further than zero. So to zero, counts up 1 2 3 4 5 highlighted in yellow, therefore rejects. When we get to the request arriving at 35 seconds, the window now looks back to 5 seconds and it counts 1 2 3 4. Therefore, this fifth one is accepted. When the three requests arrive at 40 seconds, the window is now, as you can see, it slides to the right. It's counting these two at 15, the one at 35, 1 2 3. Therefore, it allows four and five, but rejects any more than five. Hopefully, that visual aid helps you see how that window is sort of sliding along behind each new request. See you in the next scrimm. Onto the sliding window counter. This is an approximation of the log method. It's not perfectly accurate, but close enough. We start by defining two fixed windows. Our window is still 30 seconds. So the first window will be from 0 to 30 seconds and then the second 30 to 60 seconds. This sliding window counter algorithm is sort of a combination of a fixed window and sliding window. We've just used the fixed window part of it by defining these windows and then we're going to count the accepted requests in the current window and the previous window. Therefore, the memory needed for this is just two counters. There's no need for the system to look back through the logs at timestamps of when requests arrive as we did before. So we start pretty much thinking like a fixed window and we've got five requests that have been accepted here in this initial window and then at t= 25 we're already at the limit. So this would be rejected. Now as soon as we get into the second window which is now the current window if we think about time progressing to t= 35 the count of the previous window here is moved to five. We're going to work out with an equation a weighted count and then use this to work out if the new request here at t= 35 is accepted or rejected. So x here is the proportion of time in the current window. So because this request is coming at t= 35, it's the proportion of time that has elapsed in the current window. So from t= 30 to t= 35 that 5 seconds. And since it's the proportion, it's 5 seconds of the 302 window we're in. So that's 5 over 30, which is a 6th. So when we work out 1 minus a 6th, let's focus on that part. Here is when we start thinking about a sliding window going back from our current time. We're working out the fraction of the previous window which overlaps with our sliding window look back. So if we know this is a sixth, when we do 1 minus a sixth, we get the rest of the sliding window look back here, a proportion of the time. Okay, we then do that times the previous window count, which we know is five, plus the current window count, which is currently zero. And that's our weighted count. And if that weighted count plus one is smaller or equal than our limit of five requests, we will accept this new request. So there's our 1 - a 6 which is 56 * 5 + 0 that's the previous window count and it's our current window count is about 4.17. Now that plus one is 5.17 which is larger than five and because remember it has to be smaller or equal to for accept that means we're going to reject this request. Join me in the next scrimm where we continue to work out if requests are accepted or rejected using this sliding window counter and we see how it compares to the sliding window log. So the whole part here 1 - x* previous that's estimating how many of the previous Windows requests fall within our 60-cond look back. That's our sort of sliding window idea. We then add that to our current window count. And then if that + one is smaller than the limit, we are allowing it. So let's move to t= 40. We've got a new request. So we calculate again. Now this time we're a third, not a sixth of the way into our current window. So you can think that our sliding window look back is now not going as far. So we're now 1 minus a3* 5 the previous window total plus 0. But we're still at zero with our current window. That's 3.33. Now 3.33 + 1 is smaller than 5. So accepted. If another request has also come in at t= 40. Well, our current window count is now one. So we're going to be adding one at the end of this to get back to 4.33, which takes us back to 5.33 when we add the one. And now we are bigger than five. So that one is rejected. And you can imagine that anymore no number has changed, right? We're still the same fraction into this window. The previous count has stayed the same. The current window count has stayed the same. So any more requests at t= 40 are going to keep rejecting. Now if we compare this to the sliding window log, we can see that we have more green accepted requests here. But the t= 30 and 2 from 40 are accepted in the sliding window log. So it's actually more lenient than the sliding window counter. When we do the calculation for the sliding window counter, we are taking into account all of the accepted requests in this previous window, aren't we? Therefore, the system is thinking the capacity is more constrained than it really is. Whereas for the log, remember we just look back the window length from the current position. So if you think about t= 40 here, we're going back to 10. So we're cutting out these three. Hence why it's more lenient here. In the sliding window counter, the algorithm assumes that all of the requests are sort of nicely spaced evenly in that previous window when actually here we can see they can be quite close to the beginning of the window. So we see that when requests are near the start of the window, the sliding window log is more lenient. But let's have a look now when the requests are more bunched up at the end of the window. So for the sliding window log because these requests have come in at t= 45 30 seconds before that takes us to equals 15. So it's including the four around here and then the one at t45 and rejecting the other three. But in the sliding window counter the counter is actually underestimating recent traffic. So becoming more lenient. This is all because the counter at the bottom here assumes that requests were evenly spread because remember it doesn't know exactly when they came in. It's working out an estimated weighted count using the fraction of the previous window that overlaps times the previous window plus the current window. So at the bottom here we'd have a half * 4 which is 2 + 0 initially and then that 2 + 1 is definitely below five. So that's why we'd allow one here, two, and then finally three, but not the fourth, making it more lenient. Okay, onto the next scrim. Our next algorithm is the token bucket algorithm. I'm going to use a plant metaphor with leaves growing and being eaten. So my plant has a capacity of five leaves and the leaves grow three per day. So we're at the start of the first day, and three leaves grow. two caterpillars arrive. Each caterpillar needs one leaf to survive. So, caterpillar one eats a leaf and caterpillar 2 eats another leaf. That means we're down to one leaf on our plant. It gets to the second day and three more leaves are grown. Now, we have five caterpillars arrive, but there are only four leaves. So, four caterpillars eat their fill. And unfortunately, the fifth doesn't make it. On the third day, three more leaves are generated. No caterpillars arrive. On the fourth day, because we have a capacity of five leaves, only two more can grow. So, you can see here that each leaf represents a token. Usually, one request takes up one token. And the bucket or the plant in this case has a limited capacity. It can't hold more tokens than the capacity. And that the tokens or leaves are replenished at a steady fixed rate. So, it's flexible for shortterm bursts. If we had a bucket that was full at that moment, you could use up all of the tokens in a burst. If each user was to have a bucket themselves, then this could be a potential memory issue because you'd have to keep track of a lot of tokens in lots of different buckets due to these potential spikes. We don't get a smooth request rate. And the configuration required of what the capacity of the bucket is, the replenish rate and how long to wait for each refill means it's not quite as simple as other algorithms. But this is very popular for public APIs to prevent server overload to handle occasional peaks while maintaining overall traffic stability. See you in the next scrim. Time to see a token bucket algorithm in action. I've developed a sort of game where the user is told the capacity of the bucket, the refill rate and refill interval of the bucket and asked how many requests they want to send. Each second is a round or a new question in the game. We are going to be modifying the parameters together and seeing how this affects the game play. I'm going to go through the code that we have so far. Then I'll set you a few challenges to help me finish it off. Playing the game should help you see a token bucket algorithm in action and modifying parameters at the end should ensure we really understand how it works. So the game mechanics work like this. We start with a welcome message logged in the terminal. This gives the player the rules, the capacity of the bucket, the refill rate and interval. As I mentioned, each round or question the user gets asked is like 1 second passing. The user gets asked how many requests. They answer with either a number or some special commands like exit to exit the game or reset to start again. They then get given the round results. The round number, the number of requests that they made, the number that were accepted and the number that were rejected, tokens remaining in the bucket, was it refilled, and how long until the bucket is next refilled. Then the loop restarts and they get asked how many requests for the next second or round of the game. So we've got a tokenbucket game.js file. Let's go through this. Read line is just so that we can play this game in the terminal and it works in a logical manner. So don't worry about that. We'll see a bit more read line later. Then I'm using some object-oriented programming here by making a token bucket class. We have a constructor with a capacity, the refill rate, and the refill interval passed. And then some instance properties. We've got the capacity of the bucket. We've got the refill rate and the refill interval. You're going to be finishing off these last two properties, how many tokens are in the bucket, and how many seconds until the last refill. And you can imagine at the start of the game, that would be zero since there hasn't been a refill. Then we have this process requests method. So, when the player decides how many requests per round, process requests will be fired. We need to check if it's time to refill, we'll have to process the requests, consume the tokens, and we're going to return number of accepted and rejected requests for that turn of the game. We need a method to get how many tokens are in the bucket at a particular point. We need to know how many seconds until the next refill. Here's just a separator for cosmetic purposes. And as I mentioned at the start of the game, the user is going to be told a lot. So here's all the console logs. They're going to be told the capacity, the refill amount, the refill interval, starting tokens. We're actually going to start the bucket always full, and then some game rules, and some special commands that they can use per go. Here's a function to print the round results. They're going to be told how many requests they made, how many were accepted, rejected, how many tokens remaining, and how long until the next refill of the bucket. And here's the important play game function. So, we have a few default values in case no arguments are provided, but we will be providing arguments, don't worry. We create a new instance of the token bucket class. We set the round number to zero. Here's some more read line stuff. Let's not worry about that. We print the game info, passing the configuration, and we ask that question, how many requests do you want to make? User input is the answer that's been trimmed and made lowerase. We handle any special commands they might make. We then do some input validation and num requests is the final number of requests. After validation, we increment the round number because it starts at zero and once we've asked a question, that will mean we're into round one. We get how many tokens are in the bucket. We process the requests returning how many are accepted and rejected. We find out how many are now in the bucket after they're processed. This helps us find out if bucket was refilled at this round and we work out how many seconds until refill because we're going to be passing a lot of information to the print round results function so the user can see where they're up to at the end of that round. Then we continue the loop by asking another question. And then we have a main function with our game configuration and passing that to the play game function. Okay, I know that's a lot to take in, but as I mentioned earlier, when you play the game and you see the structure of it, it will make more sense. But do pause now and go through that again in your own time if you'd want to. Okay, a challenge awaits in the next scrim. See you then. Let's finish off these instance properties then. Here's a challenge for you. Number one, create a tokens property that starts with the full capacity. So remember, we have capacity here. And number two, create a second since last refill property that starts at zero. So these instance properties are where we're setting up the initial state of the class. So, we've got a refill interval property, a refill rate property, and a capacity property. So far, I want you to make a tokens property that's initial value is the capacity that's passed to the constructor when we make a new instance of it. Okay, good luck. See you in a minute. Right, so hope that was all right. So we need to go for this dot and we're going tokens and this is going to be the capacity of the bucket. So we're going to start with full bucket. Now we need a second since last refill property. So again we use this dot and this is going to start at zero. That's all it was. Okay. I'm going to continue with process requests and then you're going to finish it off. So here we have the number of requests that the user makes for this round. Now if each round is 1 second, then as we process requests, we need to increment the seconds since last refill. Cuz remember I mentioned that down here in play game, we increment the round number before we process requests. So if the round number's gone up, that means the seconds since last refill needs to go up as well. So, we're going to take this and we're going to increment it by one. So, we can use plus equals 1. Check if it's time to refill. Now, what have we got that's going to help us? We've got the refill interval. How often in seconds to refill? So, if refill interval is three, which I think we're starting it as if our seconds since last refill gets to three, then it should be refilled, right? because if it's been 3 seconds since and it should refill every 3 seconds, that's going to prompt a refill. So, let's use an if statement and we're going to say if seconds since last refill is the refill interval. But we could use some defensive programming and use a bigger or equals just in case for some reason it gets bigger the refill interval. Then we're going to refill. So to refill, what do we need to do? We need to add the refill rate to the tokens amount, but we need to make sure that the tokens can't exceed the bucket capacity. So why don't we use our math.min and we're going to pass the two things that we want it to find the smaller of. So it can't be bigger than the capacity of the bucket, can it? So we got this dot capacity and then if we add the current tokens to the refill rate, this is how many the bucket gets refilled with. So if the current amount of tokens plus the refill is bigger than the capacity, then it will return the capacity. But if not, it'll return the right hand side of the comma. And all of this is going to be the new amount of tokens in the bucket. So we're just going to assign it to this tokens. Great. And if it's been refilled, then this needs to go back to zero, doesn't it? So we'll just add that below. Bingo. Now we need to process the requests, consume the tokens, and return the accepted and rejected requests. That's what you're going to do in the next scrim. See you there. Another challenge for you. Wow, I do work you hard, don't I? I need you to determine how many requests to accept or reject. So, num requests is how many the user has requested in this round. I want you to define a variable accepted as the minimum of Oh, we did that earlier, didn't we? Hint hint. Requests made and tokens available. and then define a variable rejected as the remaining requests that were not accepted. So you can do that below the challenge text here. Good luck. See you in a minute. I hope that went okay. So we need const accepted and as I mentioned we did the math.mmin earlier. So we need the same thing. I gave you quite a big hint with this bracket here. So math dominer of the requests made which we know is num requests and the tokens available that's this do tokens because if the tokens available is a larger number than the requests made then we just want the requests made as the accepted number. But if it's the other way round the number of requests is bigger than there are tokens in the bucket then we can only accept the available tokens. now rejected and this is the remaining requests that were not accepted. So it's going to be the number of requests and we need to remove how many were accepted. There we go. Well done. Not too bad at all, eh? So let me consume the tokens. This dot tokens is how many we have at the moment and we need to remove from it how many are accepted. So we can use minus equals done and return the number of accepted rejected requests. So we return accepted and rejected. Brilliant. In the next grim, we're going to play the game finally. See you there. Time to finally play this game. Let's have a look at the readme. And we're told we can use either node tokenbucket game.js JS or npm start. So I'm going to go for npm start. And we are given the rules. We've got a bucket capacity of 10 tokens, a refill amount of six every 3 seconds. And we know that each round is essentially 1 second passing and the bucket starting with 10 full capacity. Here are the rules. We should know about that by now. We can either enter in a number or quit or exit or reset. Okay, here's that question. So, let's go for in the first second, three requests. Here's the round results. Round one, we made three requests and because we started with 10, all three were accepted, none rejected. We now have seven tokens remaining and we'll refill again in 2 seconds. We start with a refill interval of 3 seconds, but because one round has now finished, we're down to 2 seconds. So, next one. Let's go for five requests. They are all accepted again in round two. Two tokens remaining, but we are refilling in the next round. So, if I went for more requests than tokens are in the bucket, let's go for seven. We're told that the bucket's been refilled now has eight because we did have two and we are refilling with six. So, 6 + 2 is eight. We made seven requests. All were accepted. Only one token remaining. Let's try and see some rejections, shall we? So, let's go for nine. Only one is accepted because we had one token left. Eight are rejected and there's no tokens remaining. So, it doesn't matter how many I try and fire at the API, they're all rejected until the bucket's refilled again and I get out with exit. Okay, let me scroll down. It's time for another challenge. for you to modify the game parameters. So, I'd like you to run the game and play a few rounds to get used to how it all works. Then, I'd like you to modify the game parameters, these here. So, the bucket has a capacity of eight tokens and refills two tokens every 10 seconds. Then, before running the game again, I want you to predict here the behavior. Don't worry if this is going to sound a little obvious. It's good to put this sort of thing into words. Maybe think how it will act differently to the last configuration you just watched me play. Then run the game and check if your prediction is correct. Don't forget to save the token bucket game file before running the game again. Okay, see you in a minute. Right, I hope that was okay. So, we're just modifying this to now a capacity of eight tokens and a refill of two tokens every 10 seconds. There we go. I'm going to save and let's have a quick play. So, we start with eight tokens. So, let's start three. Three are accepted, five remaining. So, let's go for five. Brilliant. All five accepted. But now we have no tokens left and we've got 8 seconds to refill. That is a long time. So I can keep firing requests at the API, but I am not going to get any accepted. Gosh. Uh let's go for 24. All rejected. So this is a real long time to wait until it refills. But now only with two tokens. So that's not many, is it? So when I think about what prediction I would have made, well, as a user, you'd have to be a lot more selective about when you send requests to the API because a lot of them are going to get rejected because you've only got those two tokens. They're quite valuable, aren't they? So understanding rate limits, you can see how it really affects the users's experience. The behavior can really be affected by different parameters. Okay, fantastic work. See you in the next scrimm. We've arrived at our final algorithm, the leaky bucket algorithm. So imagine we have a bucket with a hole in it. Water is filled. The bucket has a fixed capacity, but because of the hole, water leaks at a fixed rate. By now, you probably realize that the water being filled are the requests. We're going to be holding those requests in the bucket and processing them as they leak out of the bucket. But if the bucket is filled faster than the water leaks out, it will eventually overflow and that excess water will be discarded. So let's have a look at an example here. The capacity of our bucket is five requests and the system can process two requests per second. So the system starts idle and in the first second four requests arrive. Those are added to our first in first out FIFO Q. We know that the system can process two requests per second. So request number one is processed and request number two is processed. We start the second and four more requests arrive in our queue since there are only space for three requests. Those three are added to the queue and that final request 8 is discarded. We process two requests and we get to the third second. No new requests arrive. We process two requests. We get to the fifth second. No new requests arrive and that final number seven is processed. So you can see that requests are processed at a fixed rate. This can prevent overload as we have the control to set how many are processed each second or per whatever window length we decide. It's a FIFO Q, meaning the request that arrives the earliest will be processed first and requests are discarded if that capacity is full. So, we can see that this is good for smoothing out bursts. The queue prevent overloads and it's quite easy to understand and implement this algorithm. But the cons, it lacks flexibility in handling sudden traffic spikes. We can see it prioritizes system stability over user experience. If there's legitimate burst traffic, this would get cued or delayed. In hight traffic scenarios, users might even have to wait when the system could handle the burst absolutely fine. Yep, just said that part here. And this is often used for network bandwidth management, video streaming, and server request handling. Yes, of course, we've got that constant output rate leaking from the bucket. I like to think of token bucket as here are tokens. Spend them whenever you want. and this leaky bucket as get in line. I'll process you at my pace. Okay, well done. I realize that's quite a lot of algorithms to get your head around. Might be worth pausing and trying to write down as much as you can remember about each of the different algorithms and then go back and check. Looking forward to seeing you in the next scrim. We have finally reached the part of the course on throttling. This is when we slow down API calls to prevent the overload of your servers or other systems. Throttling is similar to rate limiting, but instead of a hard cap, we're going to be slowing down requests after a certain number have gone through so that they don't crowd the system. It's a bit like an attendant forcing kids to wait a certain time before launching down a water slide. So, we're back to having just a single endpoint with no rate limiting or anything. I have made a bit of a change to test requests though. I'm now passing test start time to make requests and we're then here working out the elapsed time in the test. We're then going to display this in this console log. And the demo throttle function has changed a bit. Here's us working out the test start time and passing it each time to make request. But we have a few bursts now. We have five rapid requests in burst one. Then we're going to wait 15 seconds for burst one to complete. Then we're going to start burst two and another five requests. Then we'll wait another 5 seconds before console logging that the test is completed. So let's see this in action, shall we? Okay, there's five finished and then we'll wait a little bit before the next five burst. There we go. And the t equals that's the elapsed time. So, as you can see, 15 seconds has gone by before burst 2 has fired. And because there's no rate limiting, they're all 200 success. So, we're going to use another mpm package here. It's called express slow down. Just as before, please click on this title to navigate to the docs. Again, this is middleware that sits between the request and the endpoint. It's going to count requests in a specific time window, but we're going to delay requests after a certain amount. So, we might say allow five through, but any more than five start delaying. And this also works with the previous mpm package. So, later on, we're going to see them working in harmony. So, let's install the package npm express slow down. And then at the top here, we're going to import the library. Now, we're going to work together to configure this. So, let's make a throttle this time. And it's going to be our slowdown that we imported. And just as before, we pass to it an object of configuration. We're going to have to decide a few things. the window, how many requests should succeed before the delay is implemented and then how much to delay by. Is it going to be like a fixed delay or incremental maybe? So I'm going to do the delay ms which hopefully if you had a look at the docs you see that that's one of the configuration properties they require and then you are going to finish off this with the window length and the delaying after. So delay ms value of this property needs to be an arrow function. Now the simplest way is to just add a millisecond amount that we want each delay to be. So this would be a fixed delay. I'm going to go for 5 seconds. But later we're going to see how we can modify this to make it incremental. Okay. In the next scrim you're going to finish this configuration object off. See you there. Your turn now. Here is the challenge text. I'd like you to configure the throttling middleware by setting the window length to 10 seconds. Then set the middleware to start delaying after two requests per window. Do you remember to use the docs for this? Then I want you to apply the throttling middleware to the end point. So do you remember where that went for the rate limiter? Same thing here. Then restart the runner and run node test requests to see the effect that that's had. Okay, good luck. See you in a minute. I hope that went okay. So window length is going to be window ms and we want 10 seconds. So 10 and then milliseconds is three zeros. Then to start delaying responses after two, as you saw in the docs, we need delay after and that's just a number. Okay, fantastic. Apply the throttling middleware to the endpoint. So I'm going to change this first throttled endpoint and it needs to be in between the path and the handler. And you can see it's grayed out because it's not being used yet. And then as soon as we place it here, it's no longer grayed out. I'm going to save this. We're going to rerun the runnerup and then run our test requests. Aha. One and two have gone very fast, but now we've got that delay. Oh, three, four, five. Okay, interesting. So, we can see that request one and two have both been allowed at tals 0. And then request 3 has arrived at t=0 but been delayed to t= 5. So has request 4. So has request 5. And then at t= 15 as before the next burst has fired. And we've got our two six and seven here that have been processed at the time of firing. But then we hit our limit of two. And 8 is delayed by 5 seconds. After 15 takes us to 20. Then t has clicked on one second but essentially all at 20 seconds. There we go. So remember that all of the requests in the burst all hit the endpoint at essentially the same time. So 1 to five have all arrived at t=0 but two have been processed and the rest in this burst have been delayed. So three's been delayed 5 seconds, four has been delayed 5 seconds and five has as well. And then because our window length is 10 seconds at t= 10 seconds the window will have closed and we'll start a new delay after two limit. So we have the two that are not delayed and then subsequent requests all delayed by 5 seconds or essentially 5 seconds. Great. Let's get rid of this challenge text. We're going to talk more about this delay MS time in the next scrim. See you there. All right, let's start talking more about the delay MS part of this middleware. In the previous scrim, we just returned an amount of milliseconds. So that meant every delay after the two requests that were not delayed are going to be delayed by 5 seconds. So on a timeline, we could see this that the five requests all in burst one arrived at tals 0. The middleware doesn't start counting requests until that first request arrives. Okay. Express slowdown uses sliding windows. That means every subsequent request, remember we sent more at t= 15, looks back the window ms length, which was 10 seconds in our case to count hits. Now the docs use the word hits for requests that hit the API. So we're going to continue in that way. If no requests have been made for longer than the window MS length, then this new request that we'll see here essentially starts a fresh count. Okay, the five in the burst one arrive and the middleware starts counting and it gets to two and then it starts to delay and the three others are delayed by 5 seconds. Then at t= 15, burst 2 arrives. And this is where the middleware looks back 10 seconds and it says did any requests arrive initially arrive not being delayed but initially arrive within this window. Now these three remember were delayed from t equals z. So they don't count and the middleware then starts a new count and it goes one two it allows two and then the three more from this burst all get delayed by 5 seconds. So in green we've got accepted requests that arrived at this point and then yellow are delayed requests. So we have other delay options available to us. This would be a fixed 5-second delay. We can actually pass the hit number to this arrow function. So if we here then went for hits minus 2 because remember we're delaying after two and then we multiply that by 1 second. As we get to the first delayed hit which would be number three. Hit would be three. We'd have 3 - 2 which is 1 * 1 and that would be delayed by 1 second. And then for hit number four it would be delayed by 2 seconds. So it' be an incremental delay. But we can go one step further and we can make an exponential delay. So we could use hits times hits time 1,000. So that at hit number three, that would be 3 * 3 9 seconds. And then hit four would be 4 * 4 16 seconds and so on. So that would be an example of an exponential delay. So before we test this, let me just change something in our test requests file. I'd like us to wait 30 seconds rather than 15 seconds. And you'll see why in a minute. Okay, awesome. Let's rerun the runner and see what happens now. So, there's our two accepted and then request three. Let's see how long that's delayed. It should be 3 * 3. Ah, t= 9. Brilliant. And we're going to have to keep waiting longer and longer as we progress through. Oh, there's 416. That's 4 * 4. That makes sense. And then what's going to happen now? We Well, five should be 5 * 525. Brilliant. Then we should expect burst two. There it is. Because the window is reset at 30 seconds when it arrives, they're both processed. And then 8 should be That's it. 9 seconds after 7 and then 9 we imagine should be 16 seconds or it's gone to 17 seconds after that's okay. It's essentially the same. And then request 10. Yep. Fantastic. So we can see that exponential delay there. Here's a little table to explain what's going on. We've got the first burst all arriving at t equals0. Request one and two not delayed. and then request three delayed three * three four time four and five five time five process stack is then the arrived at time plus the delay and then the new burst 6 to 10 all arriving at t= 30 and the same sort of pattern forming and remember that our window is only 10 seconds. So at t= 10 the window ended or essentially if anything after t= 10 had come in as a new request. The middleware would have looked back 10 seconds and it would not have seen requests 1 to five because remember they all arrived at zero. Here we have the first two accepted. Request three is delayed by 9 seconds, 16 seconds and then 25 seconds. And when the new burst arrives at t equals 30 seconds, the middleware looks back the window amount which is 10 seconds. And it says are there any requests that initially remember arrived in that 10-second look back? And no, they didn't. All of these five all arrived at zero, but some were delayed before they were processed. So, it starts a new count and it counts one, two, and then any subsequent are all delayed. Think back to the water slide metaphor I used. The attendant has allowed two children down the water slide and given the child a timer of 9 seconds, the next timer of 16 seconds, and the next child a timer of 25 seconds to wait before they are allowed. And then five more children arrive at t equals 30 seconds. The attendant thinks back 10 seconds and says to themselves, "Did any children arrive within that window?" No. Okay, I can allow two to go and then give delayed timers to the others. Okay, the fun begins in the next scrimm when we combine a rate limiter with this throttling middleware. See you then. Let's now bring back the rate limiter to see how these two will work together. This is a great opportunity for you to practice installing the express rate limit middleware, configuring it, and applying it to the endpoint. So, I'd like you to install it and import the library at the top. Configure the limiter to allow three requests per 20 second window along with an appropriate message. Set all responses to include standard headers rather than the legacy headers. Apply this rate limiter to the endpoint after. So if we look at our endpoint here, we've got the throttle here. We are going to want progressive throttling before the rate limiter cuts us off. So that's why we need the throttle first because remember it works from left to right. And then after this comma, we're going to have the limiter. And then restart the runner and run node test requests. Okay, good luck. Remember the docs are there for your assistance. So I'm going to run mpmi express rate limit and at the top I'm going to import the library and then we define our limiter. We use rate limit and there's the configuration object. So we need limit, we need window ms, we need a message and then standard headers and legacy headers. So our limit is three in a 20 second window. 20 three zeros. message. Why don't we go for too many requests? And we're going to go for standard headers true and legacy false. And then we want to apply this rate limiting middleware to the endpoint after the throttling middleware. So here's the throttling middleware. So we're going to put our limiter after it. There we have it. And this is now endpoint with rate limiter. Now I'm just going to uncomment these now that we're going to have some headers. Okay, before we run the test code, let's have a think about what we're going to expect. So we know we have a limit of three requests in a 20- second window. So we'd expect the first three requests here, 1, 2, and three, to all be successful. Now request four is processed at t= 16 seconds. If we look back because remember it's a sliding window for the rate limiter. If we look back 20 seconds that will be all of the time elapsed so far. So it will count 1 2 three successes and that will hit the limit and we're expecting to reject four. Now five is being processed at t= 25. If we look back 20 seconds from then it'll be from 5 seconds. So that means these two will fall out of the window. So it'll count one and this will be a reject. So one and we should see request five being successful. So if you're feeling up to it, why don't you pause the video now and see if you can work out, I know you've probably seen this when you finished your challenge, maybe without looking back at those results, see if you can predict with what you know about the rate limiter, what the outcome should be for requests 6 to 10. I'll see you in the next scrimm where we're going to run the code and talk it through. It's time to run our test file and check our predictions. So, let's rerun the runner. And we've got node test requests. Okay, one and two success. Now, we said three was going to be successful after a delay. There we go. And then four, we were going to say we've run out our remaining zero. Can you see that? We've got two left after one, one left after two, zero left after three. That means four is going to be failure. But because we're resetting in 4 seconds, our window resets, and five is success, six is also a success. Seven is a success, but eight is a failure because the window hasn't reset yet and we're down to zero remaining. I've extended our chart to help us really see what's going on here. So, I've now got a rate limit count column and an outcome column. So, as request one comes in, the count of how many we've had in the previous window is at zero. So, it's success. Two comes in, we've now got one in the previous window. So that's 200. Request three comes in, we've got two, the previous two. So that's success. But then when request four comes in, the window is 20 seconds behind 16. So all of the time we've had elapsed so far. The counts up to 1 2 3. So we fail because three, remember, is our rate limit limit by five. Process at 25. So 20 seconds before that is 5 seconds to 25. So it won't be counting the first two here. So it's just this one is our successful one. Won't count that because it was failure. So that's where we get one. So it's a success. 30 seconds. That means this 9 seconds processed is dropped off as well. So we've just got this is the one that's counting here. And so on. Same thing happens. We get to a count of three. 1 2 3. So we get a 429 failure. And then process stack keeps getting later and later. So requests behind it get dropped out of the window and we get two successes. Join me in the next grim where we have a final throttling challenge. See you then. Welcome to the final challenge in this section of the course. I'd like you to configure rate limiting and throttling middleware to fulfill the below brief. This states that my system shows signs of performance degradation if it receives a short burst of more than three requests in a 10-second period. To give the system time to recover, subsequent requests should be processed. Request four would be 1 second after arrival. Request five 4 seconds after arrival. Request six 9 seconds after arrival. And so on. To ensure fair use of the API, no more than seven total requests in a 30- secondond period should be allowed. Then you can restart the runner and run our test request file to see this in action. So have a think about the pattern that's forming there. It's not going to be exactly the same as we've done in the past. Now a quick mention in test requests, I've modified the demo throttle function. We now have three bursts. So, we start with burst one, seven rapid requests. We're then going to wait 15 seconds for that to complete. Then burst two is another seven rapid requests, another wait, and then a third rapid requests. That's not going to affect how you complete the challenge, but when you look at the results in your terminal, do take that in mind so the results hopefully make sense. Here, I've set up your limiter and your throttle. you're going to have to configure it as we have been getting used to. They're both already applied to the endpoint, so you don't need to worry about that. Okay, take it slow. Good luck. See you in a minute. Okay, let's go for it. So, we've got limiter first here. So, let's think about what's going to be part of the limiter. Well, I think it's the end here. to ensure fair use of the API, no more than seven. So that sounds like it's going to be our limit in a 30se secondond period. So we're going to go 30 and three zeros. Okay, that wasn't too bad. Now the throttling part is going to be the above part, isn't it? So my system shows signs of performance degradation if it receives a short burst of more than three requests. So it sounds like we're going to be delaying after three successes in the window in a 10 seconds. So that window ms is going to be 10 seconds. There we go. Now this delay MS is going to be a little bit more complex. So this isn't going to be exactly the same as we had before where we had hits time hits time 1 second because hits at this point is four and we're not looking for four time four here. We're looking for 1 as the final answer. Well, if I look at this pattern, 1 is 1 * 1, 4 is 2 * 2, and 9 is 3 * 3. Gosh, my maths has never been better than this. So, let's write this here. 1 * 1. So, we could think, how do we get to one from four? How do we get to two from five? Well, it looks like we're always minusing three. So, if we pass hits and then we need our arrow and then hits minus three at request four, that would be one. We need this times itself. So, I know there's other ways of doing this, but for just for now, let's do it manually. There we go. So, that's 1* 1, and then we always need it to be times a second. Now, is that going to work for request five? So hits should be five. 5 - 3 is 2 * 2 again is four times a second. Yes, that's four. Okay, I think we've got there. Okay, great. So I saved this and in the next scrim, we're going to run this test file to see the results. See you there. Let's run the test file and see the results. So I rerun the runner and we run node test requests. Okay. So let's think about the limiter first. We have a limit of seven. So we should be processing 1 2 3 4 5 6. Oh, seven is not there. Burst two seems to have started before seven has been processed. So let's scroll down until we find seven. There's our 7 429. So that means that the seventh request that's been processed 200 is actually here. [laughter] As you can see, we have remaining one and then remaining zero and then subsequent requests of 429. So let's think about the throttling. Now we've got a delay after three. So here's our three that have all been processed at arrival time. T equals 0. Request four, that's our 1* 1. And then request five should be 2 * 2 is 4. Yep. 6 should be 3 * 3 is 9. And then seven should have been processed at 4 * 4. Let's go back down to 7. 4 * 4 16. Brilliant. So we have a good learning opportunity here. This is actually realistic behavior for throttling systems. It's not necessarily a FIFO first in first out queue. Delayed requests don't necessarily process in arrival order. Each request gets its own delay timer based on when it arrived. So request 8 basically jumped ahead in the limiter queue and became the last the seventh successful request because request 7 had a timer on it. It was waiting 16 seconds and by that time the limiter had already got to its limit. And then we have request 11 12 13 and the same thing's happened. There's no 14 because 14 is being delayed. Let's find it below. There it is. And by the time 14 gets to the end of its delayed time, the limiter window is reset and we get a 200. 200 200. All right. I would recommend spending some time and looking at those results on your own just to get your head around it. You could easily make another chart like I did previously. Now, I know we don't have any client identification here, but if we did, we could prevent one user hogging the service by delaying their requests, but allowing other new users requests to be processed immediately. I recommend you work on this in your own time separately. So, so you do some work with a rate limiter, a throttler, and using client identification in different ways and then bring them together as we can see here that the results can become quite complex quite quickly. Do ask on Discord or using AI if you have any questions around this topic. See you in the next scrim. Congratulations, you've made it through this course on rate limiting and throttling. You even helped with some practical examples of different algorithms used to rate limit applications. Let's go through what we've learned. So, we started with talking about what rate limiting is. I enjoy talking about this topic because these concepts directly impact how your applications perform in the real world. When you build APIs or services, users can overwhelm your servers with too many requests. Without rate limiting, a single user could accidentally or maliciously crash your application. It's kind of like leaving your front door wide open and being surprised when too many people walk in at once. If we think about it, almost every modern application uses external APIs and they all have rate limits. If you don't understand these limits, your code will break in production when you exceed them. Nobody wants to see those cryptic 429 too many request errors, right? With this knowledge, you can have better cost management. Many services charge based on usage. Without throttling requests, you could rack up huge bills. We talked about the core concepts rate limiting versus throttling having a hard cutff versus slowing down requests client identification. Are you going to use IP address user ids or API keys? Time windows in some of the different algorithms. Here are those algorithms. We had fixed window counter where the system just counts requests in a fixed window. We had the sliding window log or counter where the window slides along the timeline as you keep making requests. We had the token bucket. Here's the number of tokens. When you've used them up, you have to wait for that to refresh. And the leaky bucket. When requests are processed at a fixed rate, and if while they're waiting to be processed, the queue exceeds the limit, they get discarded. Understanding throttling helps you design better retry logic and error handling. Instead of bombarding a server when it's struggling, you can implement exponential backoff, waiting progressively longer between retries, which is more respectful and effective. Rate limiting and throttling topics always come up in interview questions, especially for back-end roles. Interviewers want to see what you think about scalability and system design, not just making code work on your laptop. And of course, you had lots of challenges along the way. Before we finish, I could not stop myself from putting this gif in. The perfect throttling gif if I've ever seen one. What now then? I recommend taking a break, getting a snack, and then carrying on your learning here on Scriber. Put the momentum from this course into good use. I've been Jonathan Hill. It's been fantastic to go through these topics with you. If you have any questions or would just like to reach out, check out Jonathan Hill on the Scriber Discord. Good luck with the rest of your learning.
Generated algorithmically for Search Engine
Indexing.