Professional Documents
Culture Documents
Theory Lectures PDF
Theory Lectures PDF
slides for
theory lectures
(DON’T SKIP THEM, THEY ARE SUPER
IMPORTANT 🤓)
Follow me here
📖 TABLE OF CONTENTS: THEORY LECTURES (CLICK THE TITLES)
1 What Is Node.js and Why Use It? 13 APIs and RESTful API Design
2 Blocking and Non-Blocking: Asynchronous Nature of Node.js 14 Middleware and the Request-Response Cycle
5 Static vs Dynamic vs API 17 Intro to Back-End Architecture: MVC, Types of Logic, and More
7 Processes, Threads and the Thread Pool 19 How Authentication with JWT Works
11 How Requiring Modules Really Works 23 Credit Card Payments with Stripe
LECTURE
WHAT IS NODE.JS AND WHY USE IT?
WHAT IS NODE.JS?
NOD E . J S
NODE.JS
NODE.JS IS
IS A
A JAVASCRIPT
JAVASCRIPT RUNTIME
BUILT ON GOOGLE’S OPEN-SOURCE
V8 ENGINE. 🤔
V8 JAVASCRIPT ENGINE.
NODE.JS: JAVASCRIPT OUTSIDE OF THE BROWSER
V8
BROWSER NODE.JS
JAVASCRIPT ON THE SERVER!
NODE. J S P R O S USE N O D E . J S
👉 Single-threaded, based on event driven, non-blocking 👉 API with database behind it (preferably NoSQL);
I/O model 🤯 😅
👉 Data streaming (think YouTube);
👉 Perfect for building fast and scalable data-intensive 👉 Real-time chat application;
apps;
👉 Server-side web application.
👉 Companies like have
started using node in production;
LECTURE
BLOCKING AND NON-BLOCKING:
ASYNCHRONOUS NATURE OF NODE.JS
SYNCHRONOUS VS. ASYNCHRONOUS CODE (BLOCKING VS. NON-BLOCKING)
SYNCHRONOUS ASYNCHRONOUS
BLOCKING 👎 NON-BLOCKING 👍
THE ASYNCHRONOUS NATURE OF NODE.JS: AN OVERVIEW
U S
(Oversimplified
NODE.JS PROCESS
version)
SYNC H R O N O
This is where our app runs WAY
Read large
text file
Login
SINGLE
Requesting
THREAD
data
BLOCKED
This is where our
Requesting
code is executed.
data Only one thread 👉 It’s YOUR job as a developer
to avoid this kind of situation!
Login
THE ASYNCHRONOUS NATURE OF NODE.JS: AN OVERVIEW
U S
(Oversimplified
NODE.JS PROCESS
version)
ASYNCH R O N O
This is where our app runs WAY
Read large
Display
text file
read data
Login
SINGLE “BACK-
Requesting
THREAD GROUND”
data
This is where our This is where
code is executed. time-consuming
Requesting
Only one thread tasks should be
data
👉 Non-blocking I/O model
executed!
Login More on this later!
👉 This is why we use so many
callback functions in Node.js
👉 Callbacks ≠ Asynchronous
THE PROBLEM: CALLBACK HELL...
C K H E L L
CAL L B A
LECTURE
AN OVERVIEW OF HOW THE WEB WORKS
WHAT HAPPENS WHEN WE ACCESS A WEBPAGE
REQUEST
CLIENT
SERVER
(e.g. browser)
* 🌐
RESPONSE
WHAT HAPPENS WHEN WE ACCESS A WEBPAGE
GET /maps HTTP/1.1 Start line: HTTP method + request target + HTTP version
DNS LOOKUP
1 <BODY> Request body (only when sending data to server, e.g. POST)
HTTP REQUEST 3
CLIENT
SERVER
(e.g. browser) 2 TCP/IP socket connection
* 🌐
h"ps://www.google.com/maps HTTP RESPONSE 4
HTTP/1.1 200 OK Start line: HTTP version + status code + status message
GET /maps HTTP/1.1 Start line: HTTP method + request target + HTTP version
DNS LOOKUP
1 <BODY> Request body (only when sending data to server, e.g. POST)
HTTP REQUEST 3
CLIENT
SERVER
(e.g. browser) 2 TCP/IP socket connection
* 🌐
h"ps://www.google.com/maps HTTP RESPONSE 4
5
index.html is the first to be loaded HTTP/1.1 200 OK Start line: HTTP version + status code + status message
Process is repeated for each file <BODY> Response body (most responses)
SECTION
INTRODUCTION TO BACK-END WEB
DEVELOPMENT
LECTURE
FRONT-END VS. BACK-END WEB
DEVELOPMENT
FRONT-END AND BACK-END
FRO N T - E N D B A C K - E N D
WEB SERVER
HTTP
BROWSER App DATABASE
Server
Files
LECTURE
STATIC VS DYNAMIC VS API
STATIC WEBSITES VS DYNAMIC WEBSITES
STATIC
BROWSER
👉 JavaScript ≠ Dynamic
SERVER-SIDE RENDERING
DYNAMIC
GET BUILD
DATABASE BROWSER
DATA WEBSITE
TEMPLATE
👉 Web application = Dynamic website + Functionality
DYNAMIC WEBSITES VS API-POWERED WEBSITES
GET BUILD
DATABASE BROWSER
DATA WEBSITE
TEMPLATE
CLIENT-SIDE RENDERED
BUILDING API CONSUMING API
GET BUILD
API
TEMPLATE
ONE API, MANY CONSUMERS
BROWSERS
h"ps://www.jonas.io/api/myCourseData NATIVE
MOBILE APP
NATIVE
MOBILE APP
API
NATIVE
APP
NATIVE
APP
SECTION 4 —
HOW NODE.JS WORKS:
A LOOK BEHIND THE
SCENES
SECTION
HOW NODE.JS WORKS: A LOOK BEHIND
THE SCENES
LECTURE
NODE, V8, LIBUV AND C++
THE NODE.JS ARCHITECTURE BEHIND THE SCENES
JS & 100%
C++ JS
OUR
JAVASCRIPT
CODE
JS &
C++
C++
Thread Thread
#3 #4
LECTURE
PROCESSES, THREADS AND THE THREAD
POOL
NODE PROCESS AND THREADS
Initialize program
THREA D P O O L :
Execute “top-level” code
D ING
F LOA 👉 File system APIs
START EVENT LOOP OF
Thread Thread
👉 Cryptography
#3 #4
👉 Compression
👉 DNS lookups
SECTION
HOW NODE.JS WORKS: A LOOK BEHIND
THE SCENES
LECTURE
THE NODE.JS EVENT LOOP
THE HEART OF NODE.JS: THE EVENT LOOP
NODE.JS PROCESS
SINGLE THREAD
EVEN T L O O P :
EVENT LOOP
New HTTP
E
👉 All the application code that is inside
request
callback functions (non-top-top-level code)
Timer expired
E 👉 Node.js is build around callback functions
Finished file
👉 Event-driven architecture:
reading E
START
CALLBACK
QUEUES
YES
I/O polling and callbacks C C C C
Close callbacks C C
SUMMARY OF THE EVENT LOOP: NODE VS. OTHERS
SINGLE THREAD
WITH EVENT LOOP DON’T B L O C K !
NG
OFFLOADI
NEW THREAD
SECTION
HOW NODE.JS WORKS: A LOOK BEHIND
THE SCENES
LECTURE
EVENTS AND EVENT-DRIVEN
ARCHITECTURE
THE EVENT-DRIVEN ARCHITECTURE
OBSERVER PATTERN
Attached
Event emitter Event listener
EMITS CALLS
callback function
EVENTS
EMITTER LISTENER
‘request’
event
NEW REQUEST
Request received
ON SERVER
LECTURE
INTRODUCTION TO STREAMS
WHAT ARE STREAMS?
STR E A M S
👉 More efficient data processing in terms of memory (no need to keep all data in
memory) and time (we don’t have to wait until all the data is available).
NODE.JS STREAMS FUNDAMENTALS
👉 Streams are instances of DESCRIPTION EXAMPLE IMPORTANT EVENTS IMPORTANT FUNCTIONS
the EventEmitter class! 👇 👇 👇 👇
LECTURE
HOW REQUIRING MODULES REALLY WORKS
THE COMMONJS MODULE SYSTEM
👉 Core modules
PATH RESOLVING: HOW NODE DECIDES WHICH MODULE TO LOAD
LECTURE
WHAT IS EXPRESS?
WHAT IS EXPRESS, AND WHY USE IT?
LECTURE
APIS AND RESTFUL API DESIGN
WHAT IS AN API ANYWAY?
API
Application Programming Interface: a piece of software that can be used by
another piece of software, in order to allow applications to talk to each other.
👉 ...
THE REST ARCHITECTURE
Expose structured,
2 resource-based URLs
5 Be stateless
THE REST ARCHITECTURE
ENDPOINT
3 Use HTTP methods (verbs)
/getTour
Send data as JSON
4 (usually) 👉 Endpoints should contain
/updateTour
only resources (nouns),
B A D 👎
/deleteTour and use HTTP methods
5 Be stateless for actions!
/getToursByUser
/deleteToursByUser
THE REST ARCHITECTURE
Tour id
Expose structured,
2 resource-based URLs RESPONSE
FORMATTING
👉 Stateless RESTful API: All state is handled on the client. This means that each
request must contain all the information necessary to process a certain request.
The server should not have to remember previous requests.
Separate API into logical
1 resources
👉 Examples of state: loggedIn currentPage
Expose structured,
2 resource-based URLs
WEB
5 Be stateless GET /tours/page/6
SERVER
send(6)
LECTURE
MIDDLEWARE AND THE REQUEST-
RESPONSE CYCLE
THE ESSENCE OF EXPRESS DEVELOPMENT: THE REQUEST-RESPONSE CYCLE
MIDDLEWARE STACK
👉 E.g: parsing body 👉 E.g: logging 👉 E.g: setting headers 👉 E.g: router
REQUEST-RESPONSE CYCLE
SECTION 7 —
INTRODUCTION TO
MONGODB
SECTION
INTRODUCTION TO MONGODB
LECTURE
WHAT IS MONGODB?
MONGODB: AN OVERVIEW
> >
DATABASE
users user
reviews review
WHAT IS MONGODB?
MON G O D B
“MongoDB is a document database with the scalability and flexibility that you want
with the querying and indexing that you need”
👉 Document based: MongoDB stores data in documents (field-value pair data structures, NoSQL);
👉 Scalable: Very easy to distribute data across multiple machines as your users and amount of data grows;
👉 Flexible: No document data schema required, so each document can have different number and type of fields;
👉 Performant: Embedded data models, indexing, sharding, flexible documents, native duplication, etc.
Unique ID
LECTURE
WHAT IS MONGOOSE?
WHAT IS MONGOOSE, AND WHY USE IT?
SCHEMA MODEL
SECTION
USING MONGODB WITH MONGOOSE
LECTURE
INTRO TO BACK-END ARCHITECTURE:
MVC, TYPES OF LOGIC, AND MORE
MVC ARCHITECTURE IN OUR EXPRESS APP
BUSINESS LOGIC
tourModel.js
MODEL userModel.js
...
APPLICATION LOGIC
tourRouter.js
userRouter.js
tourController.js overview.pug
...
userController.js tour.pug
...
VIEW login.pug
...
PRESENTATION LOGIC
APPLICATION VS. BUSINESS LOGIC
👉 Code that is only concerned about the application’s 👉 Code that actually solves the business problem we set
implementation, not the underlying business problem out to solve;
we’re trying to solve (e.g. showing and selling tours);
👉 Directly related to business rules, how the business
👉 Concerned about managing requests and responses; works, and business needs;
👉 Bridge between model and view layers. 👉 Creating new tours in the database;
LECTURE
AN OVERVIEW OF ERROR HANDLING
ERROR HANDLING IN EXPRESS: AN OVERVIEW
ERROR
Problems that we can predict will Bugs that we developers introduce
ERROR
happen at some point, so we just need into our code. Difficult to find and ERROR
to handle them in advance. handle.
ERROR
👉 Invalid user input (validator error 👉 Passing a number where an object ERROR
HANDLING
from mongoose); is expected;
MIDDLEWARE
👉 Failed to connect to server; 👉 Using await without async;
LECTURE
HOW AUTHENTICATION WITH JWT WORKS
HOW JSON WEB TOKEN (JWT) AUTHENTICATION WORKS
CLIENT SERVER
1
POST /login {email, password} 2
If user && password,
4
LOGIN
5
GET /someProtectedRoute JWT 6
ACCESS
If Valid JWT,
HTTPS Allow access
PROTECTED DATA
7
WHAT A JWT LOOKS LIKE
SECRET
HOW SIGNING AND VERIFYING WORKS
VERIFYING
HEADER + HEADER +
JWT CLIENT JWT
PAYLOAD PAYLOAD
ORIGINAL TEST
SIGNATURE
SIGNATURE SIGNATURE
SECRET SECRET
SIGNING
test signature === signature 👉 Data has not been modified 👉 Authenticated
test signature !== signature 👉 Data has been modified 👉 Not authenticated
👉 Without the secret, one will be able to manipulate the JWT data, because they cannot create a valid signature for the new data!
SECTION
AUTHENTICATION, AUTHORIZATION AND
SECURITY
LECTURE
SECURITY BEST PRACTICES
SECURITY BEST PRACTICES AND SUGGESTIONS
👉 COMPROMISED DATABASE 👉 NOSQL QUERY INJECTION
✅ Strongly encrypt passwords with salt and hash (bcrypt) ✅ Use mongoose for MongoDB (because of SchemaTypes)
✅ Strongly encrypt password reset tokens (SHA 256) ↘ Sanitize user input data
✅ Use bcrypt (to make login requests slow) ✅ Always use HTTPS
↘ Implement rate limiting (express-rate-limit) ✅ Create random password reset tokens with expiry dates
⚛ Implement maximum login attempts ✅ Deny access to JWT after password change
✅ Don’t commit sensitive config data to Git
👉 CROSS-SITE SCRIPTING (XSS) ATTACKS
✅ Don’t send error details to clients
↘ Store JWT in HTTPOnly cookies
⚛ Prevent Cross-Site Request Forgery (csurf package)
↘ Sanitize user input data
⚛ Require re-authentication before a high-value action
↘ Set special HTTP headers (helmet package)
⚛ Implement a blacklist of untrusted JWT
👉 DENIAL-OF-SERVICE (DOS) ATTACK ⚛ Confirm user email address after first creating account
↘ Implement rate limiting (express-rate-limit) ⚛ Keep user logged in with refresh tokens
✅ Avoid evil regular expressions ↘ Prevent parameter pollution causing Uncaught Exceptions
SECTION 11 —
MODELLING DATA AND
ADVANCED MONGOOSE
SECTION
MODELLING DATA AND ADVANCED
MONGOOSE
LECTURE
MONGODB DATA MODELLING
“DATA... WHAT? 🤔”
M O D E L L I N G
DATA
Example
👇
Different types of relationships
1 between data
Real-world Online
scenario shop
Referencing/normalization vs.
2 embedding/denormalization
categories
cart
Unstructured suppliers
customers Embedding or referencing
data
orders
3 other documents?
products
orders cart
1. TYPES OF RELATIONSHIPS BETWEEN DATA
review log
movie actor
(One movie can have many actors, but
MANY:MANY movie actor
one actor can also play in many movies)
movie actor
2. REFERENCING VS. EMBEDDING
Main
document
movie
Referencing
(child) EMBEDDING/
DENORMALIZATION
movie
actor
Embedded
documents
REFERENCING /
NORMALIZATION
actor
👉 1:MANY
1 RELATIONSHIP TYPE 👉 1:FEW
(How two datasets are 👉 1:TON
👉 1:MANY
related to each other) 👉 MANY:MANY
Movies + Images (100) ?
app
movie
app
2M
log
log
actor
log
S O L U T I O N
BEST
log
👉 1:MANY 👉 MANY:MANY
👉 1:FEW 👉 1:TON
SUMMARY 🥳
👉 The most important principle is: Structure your data to match the ways that your application queries and updates data;
👉 In other words: Identify the questions that arise from your application’s use cases first, and then model your data so that
the questions can get answered in the most efficient way;
👉 In general, always favor embedding, unless there is a good reason not to embed. Especially on 1:FEW and 1:MANY
relationships;
👉 Also, favor referencing when data is updated a lot and if you need to frequently access a dataset on its own;
👉 Use embedding when data is mostly read but rarely updated, and when two datasets belong intrinsically together;
👉 Don’t allow arrays to grow indefinitely. Therefore, if you need to normalize, use child referencing for 1:MANY
relationships, and parent referencing for 1:TON relationships;
LECTURE
DESIGNING OUR DATA MODEL
THE NATOURS DATA MODEL
userID: [<id>,
<id>, ..., <id>]
▶ 1:MANY ▶ FEW:FEW
📗 Parent referencing 📙 Embedding
tourID: <id> P
C ▶ FEW:FEW ▶ 1:MANY
userID: <id>
tour guides
📘 Child referencing 📗 Parent referencing
or
▶ 1:MANY
📙 Embedding
📗 Parent referencing
P
P C
users reviews
▶ 1:MANY
C Child
SECTION 13 —
ADVANCED FEATURES:
PAYMENTS, EMAIL,
FILE UPLOADS
SECTION
ADVANCED FEATURES: PAYMENTS, EMAIL,
FILE UPLOADS
LECTURE
CREDIT CARD PAYMENTS WITH STRIPE
STRIPE WORKFLOW
BACK-END
SECRET KEY
PUBLIC KEY
SECRET KEY
LECTURE
FINAL CONSIDERATIONS
CHALLENGES (API) 🤓
👉 Implement restriction that users can only review a tour that they have
actually booked;
👉 On the tour detail page, if a user has taken a tour, allow them add a
review directly on the website. Implement a form for this;
👉 Hide the entire booking section on the tour detail page if current user has
already booked the tour (also prevent duplicate bookings on the model);
👉 On the user account page, implement the “My Reviews” page, where all
reviews are displayed, and a user can edit them. (If you know React ⚛,
this would be an amazing way to use the Natours API and train your skills!);
👉 For administrators, implement all the “Manage” pages, where they can
CRUD (create, read, update, delete) tours, users, reviews, and bookings.
END