Live Class 80 Cookies and Sessions
Duration: 1 hr 37 min
This video lesson is available to enrolled students.
AI summary & chapters
AI Summary
An AI-generated summary of this video lecture.
This lecture series covers the integration of MongoDB into a Node.js application's 'Favourite' feature, followed by an in-depth exploration of cookies and sessions for user authentication. The initial segment focuses on refactoring file-based storage to a database-driven architecture using Mongoose, involving schema creation and method updates. The second half transitions into session management, explaining the mechanics of cookies through diagrams and browser inspection tools. Practical implementation includes setting up login functionality, handling middleware for authentication checks, and debugging common initialization errors in Express applications. The course progresses from data persistence strategies to state management techniques essential for full-stack web development.
Chapters
0:00 – 2:00 00:00-02:00
The video begins with a slide titled '16.11 Adding MongoDB to Favourite', outlining a four-step refactoring plan for migrating from file-based storage. The instructor lists specific actions: removing all file handling code from the Favourite Model, deleting the data folder, updating methods like fetchAll and addToFavourites to use MongoDB operations, and changing StoreController usages to promise syntax. This sets the stage for transitioning the application's data architecture from local files to a database-driven system.
2:00 – 5:00 02:00-05:00
The instructor continues detailing the migration steps, emphasizing the need to update model methods for MongoDB compatibility. The slide explicitly lists 'fetchAll', 'addToFavourites' (changing to save method), and 'deleteById' as key methods requiring modification. The instructor also instructs students to change the usages of the Favourite model in StoreController to utilize promise syntax, ensuring asynchronous operations are handled correctly within the new database context.
5:00 – 10:00 05:00-10:00
The lesson shifts to practical implementation, showing the instructor coding a new Mongoose schema for Favourites in an IDE. A slide titled '17.9 Using Mongoose for Favourite' appears, instructing to delete existing code and create a new schema. The instructor demonstrates defining the `favouriteSchema` with a reference to a home ID, while the frontend displays a list of homes. This segment bridges theoretical steps with actual code writing for schema definition.
10:00 – 15:00 10:00-15:00
Implementation continues with the instructor defining routes to fetch registered homes and filter them based on user favorite IDs. The code shows `exports.getFavourites` retrieving `req.session.favouriteIds` and `exports.postAddToFavourites` handling POST requests with `req.body.id`. The frontend displays pages like 'Here are all the homes' and 'Summer Home 2.0', illustrating how backend logic integrates with user interface elements for adding favorites.
15:00 – 20:00 15:00-20:00
The instructor demonstrates the 'remove from favorites' feature, implementing `exports.postRemoveFavourite` to delete entries and redirect users. A slide explains a Mongoose pre-hook `homeSchema.pre('findOneAndDelete')` that automatically deletes associated favorite records when a home is deleted. The frontend shows 'Remove from Favourite' buttons, and the instructor tests this functionality via the UI to ensure data consistency.
20:00 – 25:00 20:00-25:00
Focus shifts to Mongoose middleware for cascading deletes. The instructor writes `homeSchema.pre('findOneAndDelete', async function(next) {` and corrects the logic from `deleteOne` to `Favourite.deleteMany({ homeId: homeId })`. Console logs show the deletion process, and a slide presentation updates the logic to ensure all favorites are removed when a home is deleted. This emphasizes handling related data deletion automatically.
25:00 – 30:00 25:00-30:00
The video transitions from coding to a lecture slide titled '18. Cookies & Sessions'. The agenda lists topics including login functionality, checking login state, and using cookies. This marks a shift from data fetching implementation to theoretical concepts regarding user state management. The instructor prepares the class for understanding how cookies facilitate persistent authentication across requests.
30:00 – 35:00 30:00-35:00
A diagram titled 'How Cookies Work?' is displayed, illustrating the interaction between user, browser, and backend server. The instructor underlines key phrases like 'small pieces of data' and 'stored in the user's browser by server'. Red annotations mark authentication flows, showing REQUEST1 for login and REQUEST2 for viewing pages with the cookie. This visual aid explains the fundamental mechanism of state persistence.
35:00 – 40:00 35:00-40:00
The instructor demonstrates inspecting cookies and session data using browser Developer Tools. They navigate to the Network tab to view request headers containing authentication tokens and session IDs, then switch to the Application tab to show local storage. This practical demonstration helps students understand how web applications manage user state client-side, specifically locating authentication tokens in headers.
40:00 – 45:00 40:00-45:00
Debugging begins as the server crashes with a 'ReferenceError: Cannot access authRouter before initialization'. The instructor fixes the code by ensuring `authRouter` is required and initialized before use in the app configuration. The server successfully restarts on localhost:3001, displaying a login page and home page with 'Winter home 2.0'. This segment highlights the importance of module dependency order in Express applications.
45:00 – 50:00 45:00-50:00
The instructor implements login functionality, starting with a syntax error fix for duplicate variable declarations. They create an auth controller to handle GET requests for the login page and add a POST route for form submission. The code shows `exports.getLogin` rendering the UI and handling redirection upon successful login. This step-by-step implementation connects frontend forms to backend routes.
50:00 – 55:00 50:00-55:00
Middleware implementation is demonstrated using `app.use()` to mount routers for authentication, hosts, and stores at paths like '/auth', '/host', and '/store'. The browser view transitions from a login page to an 'Add your Home' form, confirming routing functionality. The instructor checks the console for server restarts, ensuring the middleware integration is working correctly within the Express application structure.
55:00 – 60:00 55:00-60:00
The lesson covers implementing cookies and sessions in a Node.js Express application. Objectives include understanding why global variables fail for state management, setting cookies on login, and reading them via middleware. The instructor shows code for authentication routing and verifies cookie storage in Chrome DevTools, demonstrating how to set a cookie on successful login.
60:00 – 65:00 60:00-65:00
The instructor demonstrates how cookies manage user authentication state. Browser developer tools inspect cookies for 'localhost:3001', highlighting a session cookie named '_ga'. Middleware logic checks `req.cookies['isLoggedIn']` to determine if a user is logged in, redirecting them if not. This segment reinforces the practical application of cookies for session management.
65:00 – 70:00 65:00-70:00
The instructor continues exploring middleware authentication logic, showing how `req.isLoggedIn` is set based on cookie values. The code snippet `if (!req.isLoggedIn) return res.redirect('/login');` is visible, demonstrating protection of routes. The instructor explains how modifying the cookie from the browser affects application behavior, providing hands-on experience with state manipulation.
70:00 – 75:00 70:00-75:00
The session moves to debugging common issues in cookie implementation. The instructor addresses scenarios where cookies might not be set correctly or middleware fails to read them. They review the `app.use` configuration and ensure that cookie parsing middleware is initialized before route handlers. This ensures robust authentication checks across the application.
75:00 – 80:00 75:00-80:00
The instructor demonstrates setting a cookie on successful login using `res.cookie()`. They show the code in the auth controller and verify the cookie appears in the browser's Application tab. The lesson emphasizes the importance of setting secure flags and httpOnly attributes for production environments, though these details are briefly mentioned.
80:00 – 85:00 80:00-85:00
The focus shifts to reading cookies using request syntax and defining middleware. The instructor shows `req.get('Cookie').split('=')[1]` as a method to extract cookie values. They define middleware that sets this value to the request object, making it accessible across all routes. This abstraction simplifies authentication checks in subsequent route handlers.
85:00 – 90:00 85:00-90:00
The instructor demonstrates changing the cookie from the browser to see the result. They manually modify the session ID in DevTools and observe how the application responds, either by redirecting to login or allowing access. This interactive testing helps students understand how cookies control application state and security.
90:00 – 95:00 90:00-95:00
The video concludes with a review of the entire authentication flow. The instructor summarizes how cookies are set, read, and used to maintain session state across requests. They reiterate the importance of middleware in protecting routes and ensuring only authenticated users can access specific features like adding homes or viewing favorites.
95:00 – 96:40 95:00-96:40
The final segment wraps up the lecture with a brief Q&A or summary of key takeaways. The instructor reinforces the distinction between file-based storage and database-driven architectures, as well as the mechanics of cookies versus sessions. The screen shows the final state of the application with all features integrated, providing a complete picture of the lesson's objectives.
The lecture series provides a comprehensive guide to transitioning from file-based storage to MongoDB using Mongoose, followed by an in-depth exploration of cookies and sessions for user authentication. The initial phase focuses on refactoring the 'Favourite' feature, where students learn to remove file handling code, delete data folders, and update model methods like fetchAll and addToFavourites to use MongoDB operations. The instructor demonstrates creating a new Mongoose schema, defining routes for fetching and adding favorites, and implementing remove functionality with cascading deletes via Mongoose pre-hooks. This practical segment ensures students understand how to manage data persistence and consistency in a Node.js environment.\nThe second phase transitions to session management, introducing the concept of cookies through diagrams and browser inspection tools. Students learn how cookies store small pieces of data in the user's browser to maintain state across requests. The instructor demonstrates inspecting cookies and session data using Developer Tools, highlighting authentication tokens in request headers and local storage. Practical implementation includes setting up login functionality, handling middleware for authentication checks, and debugging common initialization errors like ReferenceErrors in Express applications.\nKey technical concepts covered include the use of `app.use()` for mounting routers, setting cookies on successful login with `res.cookie()`, and reading cookies via middleware to protect routes. The instructor emphasizes the importance of module dependency order, secure cookie attributes, and the distinction between global variables and cookies for state management. By the end of the series, students have a clear understanding of how to integrate database-driven architectures with robust session management techniques essential for full-stack web development.