- NestJS Course by Academind (YouTube)
- Description: A complete playlist of videos that cover different aspects of NestJS, including practical coding examples.
- Length: Several hours of content spread across multiple videos.
- NestJS Tutorials by Traversy Media (YouTube)
- Description: Playlist of detailed tutorials on NestJS, including a crash course and various advanced topics.
- Length: Several hours of in-depth content.
- NestJS Full Course by FreeCodeCamp (YouTube)
- Description: A comprehensive full-length course covering NestJS from the ground up.
- Length: Over 4 hours of content.
Author: saqibkhan
-
YouTube Playlists and Series
-
Extended Tutorials and Articles
- Building a REST API with NestJS and TypeORM
- Description: Detailed tutorial on creating a RESTful API with NestJS and integrating it with TypeORM for database management.
- Length: Long-form article with multiple parts.
- NestJS Microservices Tutorial by DigitalOcean
- Description: A comprehensive guide to building microservices using NestJS, covering setup, communication, and deployment.
- Length: Extensive tutorial with in-depth explanations.
- GraphQL with NestJS Tutorial by the Official Documentation
- Description: Detailed guide on integrating GraphQL with NestJS, including setup and advanced usage.
- Length: In-depth documentation with code examples.
- Advanced NestJS Patterns by Medium
- Description: Article focusing on advanced design patterns and best practices for building scalable applications with NestJS.
- Length: Long-form blog post with comprehensive coverage.
- Testing NestJS Applications
- Description: Official documentation on testing strategies, including unit tests, integration tests, and end-to-end tests.
- Length: Extensive documentation covering various testing approaches.
- Building a REST API with NestJS and TypeORM
-
In-Depth Courses
- NestJS Zero to Hero by Udemy
- Description: A comprehensive course that covers NestJS from basics to advanced topics. Includes real-world projects and detailed explanations.
- Length: Over 20 hours of content.
- NestJS Masterclass by Udemy
- Description: A deep dive into building robust applications with NestJS, including best practices, advanced patterns, and real-world examples.
- Length: Over 15 hours of content.
- NestJS Fundamentals on Pluralsight
- Description: Detailed course focusing on foundational aspects of NestJS, including architectural patterns and best practices.
- Length: Approximately 3.5 hours of content.
- NestJS and TypeScript – The Complete Guide by Udemy
- Description: In-depth course covering NestJS in conjunction with TypeScript, including setup, core concepts, and advanced topics.
- Length: Over 10 hours of content.
- Complete Guide to NestJS by Eduonix
- Description: A thorough guide that covers NestJS in detail, from basic to advanced concepts.
- Length: Extensive course with multiple modules and lessons.
- NestJS Zero to Hero by Udemy
-
Caching
Caching is the term for storing reusable responses in order to make subsequent requests faster. Every browser ships with an implementation of a HTTP cache. All we have to do is ensure that each server response provides correct HTTP header directives to instruct the browser on when and for how long the response can be cached by the browser.
Following are some benefits of including caching in your web apps −
- Your network costs decrease. If your content is cached, you’ll need to send less of it for every subsequent request.
- Speed and performance of your website increases.
- Your content can be made available even if your client is offline.
We’ll be using the koa-static-cache middleware to implement caching in our app. Install these middleware using −
$ npm install --save koa-static-cacheGo to your app.js file and add the following code to it.
var koa = require('koa'); var app = koa(); var path = require('path'); var staticCache = require('koa-static-cache'); app.use(staticCache(path.join(__dirname, 'public'), { maxAge: 365 * 24 * 60 * 60 //Add these files to caches for a year })) app.listen(3000);The koa-static-cache middleware is used to cache server responses on the client side. The cache-control header is set according to the options we provide while initializing the cache object. We have set the expiration time of this cached response to 1 year. Following are the comparisons of request we have sent before and after the file was cached.
Before this file was cached, the returned status code was 200, which is OK. The response headers had multiple information regarding the content to be cached and had also given an ETag for the content.

The next time the request was sent, it was sent along with the ETtag. Since our content hadn’t changed on the server, its corresponding ETag also remained the same and the client was told that the copy it has locally is up-to-date with what the server would provide and should use the local one instead of requesting again.

Note − For invalidating any cached file, you just need to change its file name and update its reference. This will ensure that you have a new file to send to the client and the client can’t load it back from the cache.
-
Compression
Compression is a simple, effective way to save bandwidth and speed up your site. It is only compatible with modern browsers and should be used with caution if your users use legacy browsers as well.
When sending responses from the server, if compression is used, it can greatly improve the load time. We’ll be using a middleware called koa-compress to take care of the compression of files as well as setting appropriate headers.
Go ahead and install the middleware using −
$ npm install --save koa-compressNow in your app.js file, add the following code −
var koa = require('koa'); var router = require('koa-router'); var app = koa(); var Pug = require('koa-pug'); var pug = new Pug({ viewPath: './views', basedir: './views', app: app //Equivalent to app.use(pug) }); app.use(compress({ filter: function (content_type) {
}, threshold: 2048, flush: require('zlib').Z_SYNC_FLUSH })); var _ = router(); //Instantiate the router _.get('/', getRoot); function *getRoot(next){ this.render('index'); } app.use(_.routes()); //Use the routes defined using the router app.listen(3000);return /text/i.test(content_type)This puts our compression middleware in place. The filter option is a function that checks the response content type to decide whether to compress. The threshold option is the minimum response size in bytes to compress. This ensures we don’t compress every little response.
Following is a response without compression.

Following is the similar response with compression.

If you look at the size tab at the bottom, you can very well see the difference between the two. There is more than 150% improvement, when we compress the files.
-
Authentication
Authentication is a process in which the credentials provided are compared to those on file in the database of authorized users’ information on a local operating system or within an authentication server. If the credentials match, the process is completed and the user is granted authorization for access.
We’ll be creating a very basic authentication system that’ll use Basic HTTP Authentication. This is the simplest possible way to enforce access control as it doesn’t require cookies, sessions, or anything else. To use this, the client has to send the Authorization header along with every request it makes. The username and password are not encrypted, but are concatenated in a single string like the following.
username:passwordThis string is encoded with Base64, and the word Basic is put before this value. For example, if your username is Ayush and password India, then the string “Ayush:India” would be sent as encoded in the authorization header.
Authorization: Basic QXl1c2g6SW5kaWE=To implement this in your koa app, you’ll need the koa-basic-auth middleware. Install it using −
$ npm install --save koa-basic-authNow open your app.js file and enter the following code in it.
//This is what the authentication would be checked against var credentials = { name: 'Ayush', pass: 'India' } var koa = require('koa'); var auth = require('koa-basic-auth'); var _ = require('koa-router')(); var app = koa(); //Error handling middleware app.use(function *(next){ try {
} catch (err) {yield next;
} }); // Set up authentication here as first middleware. // This returns an error if user is not authenticated. _.get('/protected', auth(credentials), function *(){ this.body = 'You have access to the protected area.'; yield next; }); // No authentication middleware present here. _.get('/unprotected', function*(next){ this.body = "Anyone can access this area"; yield next; }); app.use(_.routes()); app.listen(3000);if (401 == err.status) { this.status = 401; this.set('WWW-Authenticate', 'Basic'); this.body = 'You have no access here'; } else { throw err; }We have created an error handling middleware to handle all authentication related errors. Then, we have created 2 routes −
- /protected − This route can only be accessed if the user sends the correct authentication header. For all others, it’ll give an error.
- /unprotected − This route can be accessed by anyone, with or without the authentication.
Now if you send a request to /protected without an authentication header or with the wrong credentials, you’ll receive an error. For example,
$ curl https://localhost:3000/protectedYou’ll receive the response as −
HTTP/1.1 401 Unauthorized WWW-Authenticate: Basic Content-Type: text/plain; charset=utf-8 Content-Length: 28 Date: Sat, 17 Sep 2016 19:05:56 GMT Connection: keep-alive Please authenticate yourselfHowever, with the right credentials, you’ll get the expected response. For example,
$ curl -H "Authorization: basic QXl1c2g6SW5kaWE=" https://localhost:3000/protected -iYou’ll get the response as −
HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Content-Length: 38 Date: Sat, 17 Sep 2016 19:07:33 GMT Connection: keep-alive You have access to the protected area.The /unprotected route is still accessible to everyone.
-
Sessions
HTTP is stateless, hence in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. However, they are both readable on the client side. Sessions solve exactly this problem. You assign the client an ID and it makes all further requests using that ID. Information associated with the client is stored on the server linked to this ID.
We’ll need the koa-session, thus install it using −
npm install --save koa-sessionWe will put the koa-session middleware in place. In this example, we’ll use the RAM to store sessions. Never use this in production environments. The session middleware handles everything, i.e. creating the session, setting the session cookie, and creating the session object in context object.
Whenever we make a request from the same client again, we will have their session information stored with us (given that server was not restarted). We can add more properties to this session object. In the following example, we will create a view counter for a client.
var session = require('koa-session'); var koa = require('koa'); var app = koa(); app.keys = ['Shh, its a secret!']; app.use(session(app)); // Include the session middleware app.use(function *(){ var n = this.session.views || 0; this.session.views = ++n; if(n === 1)
elsethis.body = 'Welcome here for the first time!';
}) app.listen(3000);this.body = "You've visited this page " + n + " times!";What the above code does is, when a user visits the site, it creates a new session for the user and assigns a cookie. Next time the user visits, the cookie is checked and the page_view session variable is updated accordingly.
Now if you run the app and go to localhost:3000, you’ll get the following response.

If you revisit the page, the page counter will increase. In this case, the page was refreshed 12 times.

-
Cookies
Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps keep track of the users actions. There are numerous uses of HTTP Cookies.
- Session management
- Personalization(Recommendation systems)
- User tracking
To use cookies with Koa, we have the functions: ctx.cookies.set() and ctx.cookies.get(). To set a new cookie, let’s define a new route in our Koa app.
var koa = require('koa'); var router = require('koa-router'); var app = koa(); _.get('/', setACookie); function *setACookie() { this.cookies.set('foo', 'bar', {httpOnly: false}); } var _ = router(); app.use(_.routes()); app.listen(3000);To check if the cookie is set or not, just go to your browser, fire up the console, and enter −
console.log(document.cookie);
This will produce the following output (you may have more cookies set maybe due to extensions in your browser).
"foo = bar"Here is an example of the above.

The browser also sends back cookies every time it queries the server. To view a cookie on your server, on the server console in a route, add the following code to that route.
console.log('Cookies: foo = ', this.cookies.get('foo'));Next time you send a request to this route, you’ll get the following output.
Cookies: foo = barAdding Cookies with Expiration Time
You can add cookies that expire. To add a cookie that expires, just pass an object with the property ‘expires’ set to the time when you want it to expire. For example,
var koa = require('koa'); var router = require('koa-router'); var app = koa(); _.get('/', setACookie); function *setACookie(){ //Expires after 360000 ms from the time it is set. this.cookies.set('name', 'value', {
} var _ = router(); app.use(_.routes()); app.listen(3000);httpOnly: false, expires: 360000 + Date.now() });Deleting Existing Cookies
To unset a cookie, simply set the cookie to an empty string. For example, if you need to clear a cookie named foo, use the following code.
var koa = require('koa'); var router = require('koa-router'); var app = koa(); _.get('/', setACookie); function *setACookie(){ //Expires after 360000 ms from the time it is set. this.cookies.set('name', ''); } var _ = router(); app.use(_.routes()); app.listen(3000);This will unset the said cookie. Note that you should leave the HttpOnly option to be true when not using the cookie in the client side code.
-
Static Files
Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default doesn’t allow you to serve static files.
We need a middleware to serve this purpose. Go ahead and install koa-serve −
$ npm install --save koa-staticNow we need to use this middleware. Before that create a directory called public. We will store all our static files here. This allows us to keep our server code secure as nothing above this public folder would be accessible to the clients. After you’ve created a public directory, create a file named hello.txt in it with any content you like. Now add the following to your app.js.
var serve = require('koa-static'); var koa = require('koa'); var app = koa(); app.use(serve('./public')); app.listen(3000);Note − Koa looks up the files relative to the static directory, so the name of the static directory is not part of the URL. The root route is now set to your public dir, so all static files you load will be considering public as the root. To test that this is working fine, run your app and visit https://localhost:3000/hello.txt
You should get the following output. Note that this is not a HTML document or Pug view, rather it is a simple txt file.

Multiple Static Dirs
We can also set multiple static assets directories using −
var serve = require('koa-static'); var koa = require('koa'); var app = koa(); app.use(serve('./public')); app.use(serve('./images')); app.listen(3000);Now when we request a file, Koa will search these directories and send us the matching file.
-
File Uploading
eb applications need to provide the functionality to allow file uploads. Let us see how we can receive files from the clients and store them on our server.
We have already used the koa-body middleware for parsing requests. This middleware is also used for handling file uploads. Let us create a form that allows us to upload files and then save these files using Koa. First create a template named file_upload.pug with the following contents.
html head
bodytitle File uploadsform(action = "/upload" method = "POST" enctype = "multipart/form-data") div input(type = "text" name = "name" placeholder = "Name") div input(type = "file" name = "image") div input(type = "submit")</code></pre>Note that you need to give the same encoding type as above in your form. Now let us handle this data on our server.
var koa = require('koa'); var router = require('koa-router'); var bodyParser = require('koa-body'); var app = koa(); //Set up Pug var Pug = require('koa-pug'); var pug = new Pug({ viewPath: './views', basedir: './views', app: app }); //Set up body parsing middleware app.use(bodyParser({ formidable:{uploadDir: './uploads'}, //This is where the files would come multipart: true, urlencoded: true })); var _ = router(); //Instantiate the router _.get('/files', renderForm); _.post('/upload', handleForm); function * renderForm(){ this.render('file_upload'); } function *handleForm(){ console.log("Files: ", this.request.body.files); console.log("Fields: ", this.request.body.fields); this.body = "Received your data!"; //This is where the parsed request is stored } app.use(_.routes()); app.listen(3000);When you run this, you get the following form.

When you submit this, your console will produce the following output.

The files that were uploaded are stored in the path in the above output. You can access the files in the request using this.request.body.files and the fields in that request by this.request.body.fields.