I think you are the best on RUclips for making video tutorials. A completely new beginners can easily understand your content. I wish you were there when i start learning these tutorials 😂. Try to explore pagination and more.
However, @Tom, I am facing the same issue twice when learning from your wonderful tutorials. There is the issue of Nanoid not being able to work with my projects. Even after using dynamic imports, I still cant get it to work. I had to revert to uuid instead of nanoid for both projects. Any help?
Your content is amazing, really high quality. I would love to see a full stack graphql version of this, with nextjs and SSR where you also show us about security best practices, like where to store the access token, how to deal with refresh tokens when access one expires. Damn that could be something I would pay for!
Hey Tom, wanted to join in with other commenters and thank you for probably the most useful content on MERN stack on RUclips! Compare to other channels, your tutorials are actually very in depth and useful due to very sensible use of typescript. Without going crazy and over typing the code to the point where it’s already unreadable! I would love to see if you could incorporate architectural patterns into say the mern playlist by making code modular with ability to switch between mongoose and say prisma with Postgres. Also would be great to see how you handle react testing library for the front end. ;) thanks again!! Such an underrated channel it’s unbelievable..
Mate, absolutely epic tutorial. Learnt a shitload and really enjoyed the entire walkthrough. Please keep making these epic videos man, you've got the knack for it! Rock on bro 🤘
Your content is amazing and the quality is really high the practises you use really cleared a lot of concepts and teached me how to not make a hotchpotch
Hi Tom, I have recently discovered your videos. This is the best video I have seen on how to use typescript with node and some of the practices you use I will be using as standard from now on.
Hi Tom! Thank you for making this video. I've already implemented your folder structure into my own projects! However, typescript is so overwhelming..., like Request. Its gonna take me a while to digest all of this ahhh!
This tutorial was amazing. I learnt a lot of new things. I have just one suggestion.. when you make a mistake, please mention which part you fixed (even if its obvious and straightforward) rather than just fixing it and edit that part out.
Thanks again for this. I report you just a small issue, which can be really annoying in certain cases: In validateResource you're just validating the req, without parsing it. This means that every pre/postprocess applied by zod is not took into consideration by the controllers, possibily lending to errors
Suggestion for video: Implementing a OAuth2 and OpenID Authorization server. Maybe even include a resource service which would use it. I've notice that there are barely any videos on this.
Hi, I am wondering if this video is an incomplete example or if there is something I have missed. In the refreshAccessTokenHandler you find a session by its id. But never at any point in the video did you call .save() on the SessionModel?
This is amazing! I am learning so much from this, and am going to be watching your other tutorials. I do have some questions though (with my limited knowledge). Is it safe to say this tutorial isn't handling NoSQL injection? 40:03 I guess we can simply have the validateResources to check for the correct types (anything be JSON), or use mongoose sanitizeFilter with each property. 41:04 or at the handlers Do you have another video on how to properly protect against malicious inputs?
Thank you! Have some questions. 1) when we send a refresh token back (after logging) how a client has to save it to use later? should we send it back in cookies? 2) why do we need in config/default.ts emtpy 'accessTokenPrivateKey', 'refreshTokenPrivateKey'? we have them in custom-environment-variables.ts 3) why we have to save token data in .env instead keeping them in /config? 4) why do we even use 'config' module? we use config.get to get a property, but we could just import them directly from config.ts or something (config.port, config.dbUri)
1. yeah cookies are a good way to store tokens 2. if you don't need them in config then don't add them 3. private keys are secrets, config.ts gets committed 4. I like using config module, if you don't like it don't use it
Hello! I have a question. For example: I set access token expiry to 10 seconds, I login using Postman and can access /api/users/me route. After those 10 seconds my access token expires, I cannot access the /api/users/me route and the only way to get the new access-token is to call /api/sessions/refresh route. Shouldn't we send the refresh token with access token together to /api/users/me, implement /api/sessions/refresh logic there, so when the access token is expired we can generate a new access token and send it back to the user immediately? Also, let's say someone steals our 1 year refresh token, how would we revoke it? Would we just simply remove the session from the database or would we set valid to false? If so, why do we create the same session every time we log in, shouldn't we check if the session exists first and then attach it to the refresh token, because right now we create a new session every time we log in and it gets stored in the database again.
Why would you access token expire after 10 seconds? That's not enough time to do anything. You should implement the logic that makes sense for your system. What've I've shown you here is a generic approach that isn't going to work for every single application, rather it should be adapted to whatever makes sense for your use-case. As for stealing tokens, you should first try to prevent that. Secondly, you can use rotating keys. If you want to revoke the right to use the refresh token, set the session's valid prop to false if you want to keep the session record, otherwise delete it. When someone logs in, they are creating a new session, why would you not represent that as a new session object?
Thank you so much sir ... but I don't understand one thing ..Why will the session object remain in the database after the refresh token expires in 1 year?
Hello Tom! Please can you do a video on how to handle errors(boostrap both development error and production error) probably through an error class and setting a global error handler with express and typescript . You can also do a video on how to configure email an class or function based on different use cases in an application (development and production environment) because I'm having problems implementing mailing list to my API users at production level Thank you
I came across this while looking for a node typescript API lecture. Thank you for the truly amazing lecture. It was a bit of a difficult lecture for me. Will there be any problem if I apply the lecture source material in practice? Translated with Google Translator.
Really nice tutorial and learned alot about new ways to keep your code clean and other really nice tools like zod. However, I found that while writing schemas we usually we're repeating the code for validation. For eg. email, password, passwordConfirmation. What do u think about this, create a src/validations folder and have a common.validation.ts file and export named each of the zod validations. Then in the schemas we can just import these validations. And for some use case specific validations we can create a file for it.
Hello Tom! Whenever I try sending an email to the user with the verification code when they register I get an "Unexpected socket close" message. Do you know why this is happening?
Hey Tom! amazing stuff :) I realize this may not be the place but i'm getting back an error when trying the Login route - Error: secretOrPrivateKey must have a value any idea to the origin for it?
Hello Tom, came back to this video and wanted to ask a question. Instead of using { omit } from 'lodash' to send back private fields, is there a way you can use zod for readDto that way you only return the fields specified. And if that is not possible, is there a library you use to write Create, Read and Update Dto's on a requets?
Yeah, it is possible. You can parse your response through a Zod schema and it will remove the fields that aren't in the schema. I would personally still omit password, but just for peace of mind. It's easier with Fastify to be honest
Error: secretOrPrivateKey must be an asymmetric key when using RS256 at Object.module.exports [as sign] (C:\Users\pc\Desktop\Node-TS-Auth ode_modules\jsonwebtoken\sign.js:130:22) at signJwt (C:\Users\pc\Desktop\Node-TS-Auth\src\utils\jwt.ts:15:16) I have been having this issue for a week now. Please help
I am new in typescript, can you make a video on the FilterQuery function's functionality, how should I write it to sort, or filter the document based on particular fields like _id, name, email etc. does it filters based on what value is being passed into it ?? on do i have to customise the queryOptions part ?? its not clear in this video. please make another elaborated video on this.
How to logout? If We delete the session in logout route, not possible to generate new access token. But by that time the access token is still valid. We can access /me route with that access token. Btw great content man, very much appreciated.
A user can login on different devices. A session also doesn't get deleted, you can keep them to see how many times a user had logged in and what devices they logged in on
Thanks for the amazing video. Has someone achieved to configure swagger for auto api docs? I digged into swagger-ui-express but looks like its works only with controller based classes
I get a 400 bad request error on postman anytime I try to test the create user endpoint. Since I don't get any other errors, I don't know where to start debugging. Can anybody help me, please?
Mehn I have have different challenges with this tutorial. Please Tom or anyone, I need some help with these issues. VerifyJwt is not working as intended and it is technically affecting the refreshToken logic
I am getting `Object is possibly 'undefined'` on "this" inside the @pre of the User class. Is there a property I need to change in the tsconfig file to remove the error?
Correction: I was using an arrow function for the callback of the @pre save hook and read the documentation of typegoose only to find out that you can't use arrow function here. Typegoose docs: Arrow Functions cannot be used here, because the binding of `this` is required to get & modify the document
Hi Tom! How is config finding the environment variables? I'm getting the error "secretOrPRivateKey must have a value". the line `Buffer.from(config.get(keyName),"base64").toString("ascii") is returning undefined. I've included the dotenv config in app.ts.
Actually nvm, the problem was the file name, `custom-env.ts` threw that error, but `custom-environment-variables.ts` doesnt. Is `custom-environment-variables` a reserved file name or what?
kept typing, barely explained, super hard for beginner, especially the zod part so far. Thanks for the tutorial anyway. what's going on with schema.parse({ body: req.body, query: req.query, params: req.params, }); Really confused.
Since you're already implementing sessions, why use JWTs at all? My understanding is that the primary benefit of JWTs is that they can provide a form of stateless auth, but if authenticating statefully with sessions wouldn't standard session identifiers do the same thing with less computational overhead?
JWTs are great, but how do you revoke a session from someone? How do you provide them with a short-lived access token without having to get them to login every few minutes?
@@TomDoesTech To revoke a session identifier you just delete it from the database and then any future authenticated requests will fail. IIRC the concept of init access + refresh identifiers aren't used with sessions as they're just kept in a httpOnly cookie and if someone gets that then you're being man in the middled and already have other issues (same if someone gets your JWT refresh token). Do know I'm far from an expert here so I could be incorrect on a few points but thats my general understanding
@@departuream1440 Sorry. my question should have been, in a completelyt stateless system, how do you remove an access token? Using a JWT and a refresh token allows the access to be stateless as long as the access token lives, but also allows you to remove access if required. It's a "best of both worlds" approach.
1:25:55 on line 13, we have ...(options && options) , I don't understand why we need another 'options' and && operator there, anybody, explain it to me please..
Yes dude, it's simple! The && operator like this just returns the right variable only if the left one is defined. So in this case option will be returned only if it is not undefined or null.
What is the difference between the "ts-node" & "ts-node-dev" packages? I saw some of your previous videos where you were using "ts-node". But, in your recent tutorial, you're using "ts-node-dev".
What is the use of {...(options && options)} I know spread operator but never used like this. Can anyone comment what is the difference between { ... options } and {...(options && options)}
The second will spread opetions on the object if it is defeined. In the first spread, if options is undefined you will be spreading undefined and your application will throw an error.
Great tutorial! Ton's of excellent code and information. One thing that I'm a bit stumped by is this: return jwt.sign(object, signingKey, { ...(options && options), algorithm: 'RS256' }) What purpose does the ...(options && options) serve here? What's happening there?
The end result is the same, res.locals is generally used for passing data to a rendering engine. I use it instead of req.user because TypeScript doesn't complain
Have you followed the MVC design pattern? I think you have done the MVC design pattern. But you don't have a view folder there. Can you explain it? I can't understand the folder pattern. Thank you
Hey Tom, this tutorial is great and I'm already half way and stuck with this "Error: require() of ES Module not supported" from last 2 Days. I have tried changing downgrading Node Version to 14, but still stuck. Any suggestions or help would be great. It shows "Instead change the require of index.js in D:\Dev\Authentication\src\models\user.model.ts to a dynamic import() which is available in all CommonJS modules" but I don't have any "require" in any file of the project.
I was facing the same issue with nanoid, very frustrating I just decided to use another unique id maker library called cuid, as we just need a random uuid for verification code.
did you know why am i getting "code": "invalid_type", "expected": "string", "received": "undefined", "path": [ "body", "lastName" ], all the time doesnt matter what am i typping for all fields
I can't seem to figure out how to locate the environment variables in postman? I have imported the collection json file but there are still no environments available to choose from?
Hi Tom..absolutely love your videos. There's something I started getting obsessed with lately and that's the latency of the api requests and how to make them smaller. I noticed in this video the latency is really small, all below 50ms which is amazing. What is the main reason for such latencies because in another of your videos the latency was around 230ms. Thanks as I anticipate your response
I had a problem: res.locals.user is undefined. And my problem lies in: In my header, instead of having Authentization i named it x-access-authentization, therefore I couldn't parse it in deserializeUser
I think you are the best on RUclips for making video tutorials. A completely new beginners can easily understand your content. I wish you were there when i start learning these tutorials 😂. Try to explore pagination and more.
If only I have a way to make your videos appear first on youtube search, so that people that are looking for high quality content find you quicker
You are the best!!! @Tom. Thank you for being such a blessing.
However, @Tom, I am facing the same issue twice when learning from your wonderful tutorials. There is the issue of Nanoid not being able to work with my projects. Even after using dynamic imports, I still cant get it to work. I had to revert to uuid instead of nanoid for both projects. Any help?
Thank you soo much Tom for this amazing video...learnt alot!
As someone who has a supercomputer laying around that can only crack argon2 passwords I would like to thank you for finally giving it something to do
hahahaha so glad someone picked up on that
Your content is amazing, really high quality. I would love to see a full stack graphql version of this, with nextjs and SSR where you also show us about security best practices, like where to store the access token, how to deal with refresh tokens when access one expires. Damn that could be something I would pay for!
Hey Tom, wanted to join in with other commenters and thank you for probably the most useful content on MERN stack on RUclips! Compare to other channels, your tutorials are actually very in depth and useful due to very sensible use of typescript. Without going crazy and over typing the code to the point where it’s already unreadable!
I would love to see if you could incorporate architectural patterns into say the mern playlist by making code modular with ability to switch between mongoose and say prisma with Postgres. Also would be great to see how you handle react testing library for the front end. ;) thanks again!! Such an underrated channel it’s unbelievable..
Man the fact that you use typescript in your tutorials is so nice, I come to learn and this way I just learn more even if I want to use plain js.
Mate, absolutely epic tutorial. Learnt a shitload and really enjoyed the entire walkthrough.
Please keep making these epic videos man, you've got the knack for it!
Rock on bro 🤘
Your content is amazing and the quality is really high the practises you use really cleared a lot of concepts and teached me how to not make a hotchpotch
Hi Tom, I have recently discovered your videos. This is the best video I have seen on how to use typescript with node and some of the practices you use I will be using as standard from now on.
Awesome content Tom!! Thanks for sharing
Marvelous tutorial! I learned a lot of this project, thanks so much for share it 👏🏻🙌🏻
Glad it was helpful!
Hi Tom! Thank you for making this video. I've already implemented your folder structure into my own projects! However, typescript is so overwhelming..., like Request. Its gonna take me a while to digest all of this ahhh!
Learnt tons of stuffs from your videos, and you deserve more views.
Keep the good work and wish you all the best, my friend.
You've been missed. Welcome back
I didn't go anywhere, I've uploaded a video every Tuesday night for over 6 months and sometimes twice a week, but thanks?
It took me some time to get here, but i am finally understanding your content and it is gold. Thanks for the videos!
Thank you so much :)
Very Nice Tutorial
Thank you :)
This tutorial was amazing. I learnt a lot of new things.
I have just one suggestion.. when you make a mistake, please mention which part you fixed (even if its obvious and straightforward) rather than just fixing it and edit that part out.
Yea, that is pretty annoying
Great tutorial Tom! Thanks for your hard work. I'm using these techniques to build my graphql boilerplate with Typegraphql.
Amazing video!!!
gold content, thank you!
Glad you enjoyed it!
That last 30 minutes are pure fire! I'm trying to do the same thing but with Postgres and Prisma (ORM) and it's hard.
Have you managed to do it?
this is a good tutorial!!
Hello TomDoesTech, Please implement this api with frontend like React or Vue🔥 I like this amazing video tutorial.
hi man did you find a way to do that ?
Thanks again for this. I report you just a small issue, which can be really annoying in certain cases: In validateResource you're just validating the req, without parsing it. This means that every pre/postprocess applied by zod is not took into consideration by the controllers, possibily lending to errors
Suggestion for video: Implementing a OAuth2 and OpenID Authorization server. Maybe even include a resource service which would use it.
I've notice that there are barely any videos on this.
Hi, I am wondering if this video is an incomplete example or if there is something I have missed. In the refreshAccessTokenHandler you find a session by its id. But never at any point in the video did you call .save() on the SessionModel?
This is amazing! I am learning so much from this, and am going to be watching your other tutorials. I do have some questions though (with my limited knowledge). Is it safe to say this tutorial isn't handling NoSQL injection?
40:03 I guess we can simply have the validateResources to check for the correct types (anything be JSON), or use mongoose sanitizeFilter with each property.
41:04 or at the handlers
Do you have another video on how to properly protect against malicious inputs?
I have a feeling that maybe express along with typescript makes it safe by enforcing the data type, but I feel it isn't the case.
where (session/local/cookie) to store these token for reactjs
Thank you!
Have some questions.
1) when we send a refresh token back (after logging) how a client has to save it to use later? should we send it back in cookies?
2) why do we need in config/default.ts emtpy 'accessTokenPrivateKey', 'refreshTokenPrivateKey'? we have them in custom-environment-variables.ts
3) why we have to save token data in .env instead keeping them in /config?
4) why do we even use 'config' module? we use config.get to get a property, but we could just import them directly from config.ts or something (config.port, config.dbUri)
1. yeah cookies are a good way to store tokens
2. if you don't need them in config then don't add them
3. private keys are secrets, config.ts gets committed
4. I like using config module, if you don't like it don't use it
Hello! I have a question. For example: I set access token expiry to 10 seconds, I login using Postman and can access /api/users/me route. After those 10 seconds my access token expires, I cannot access the /api/users/me route and the only way to get the new access-token is to call /api/sessions/refresh route. Shouldn't we send the refresh token with access token together to /api/users/me, implement /api/sessions/refresh logic there, so when the access token is expired we can generate a new access token and send it back to the user immediately?
Also, let's say someone steals our 1 year refresh token, how would we revoke it? Would we just simply remove the session from the database or would we set valid to false? If so, why do we create the same session every time we log in, shouldn't we check if the session exists first and then attach it to the refresh token, because right now we create a new session every time we log in and it gets stored in the database again.
Why would you access token expire after 10 seconds? That's not enough time to do anything.
You should implement the logic that makes sense for your system. What've I've shown you here is a generic approach that isn't going to work for every single application, rather it should be adapted to whatever makes sense for your use-case.
As for stealing tokens, you should first try to prevent that. Secondly, you can use rotating keys. If you want to revoke the right to use the refresh token, set the session's valid prop to false if you want to keep the session record, otherwise delete it.
When someone logs in, they are creating a new session, why would you not represent that as a new session object?
Thank you so much sir ... but I don't understand one thing ..Why will the session object remain in the database after the refresh token expires in 1 year?
Hello Tom! Please can you do a video on how to handle errors(boostrap both development error and production error) probably through an error class and setting a global error handler with express and typescript .
You can also do a video on how to configure email an class or function based on different use cases in an application (development and production environment) because I'm having problems implementing mailing list to my API users at production level Thank you
Do you have a unit testing tutorial using node and typescript?
I came across this while looking for a node typescript API lecture.
Thank you for the truly amazing lecture.
It was a bit of a difficult lecture for me.
Will there be any problem if I apply the lecture source material in practice?
Translated with Google Translator.
Really nice tutorial and learned alot about new ways to keep your code clean and other really nice tools like zod.
However, I found that while writing schemas we usually we're repeating the code for validation. For eg. email, password, passwordConfirmation.
What do u think about this, create a src/validations folder and have a common.validation.ts file and export named each of the zod validations. Then in the schemas we can just import these validations.
And for some use case specific validations we can create a file for it.
Any other way to omit private fields without lodash and arrays?
Hello Tom! Whenever I try sending an email to the user with the verification code when they register I get an "Unexpected socket close" message. Do you know why this is happening?
Have you seen this thread? github.com/nodemailer/nodemailer/issues/830
Thank you , unique key not working of typegoose . How can I solve this ?
I want to learn express session management using typescript. Like storing user in session and pass that user to other routes of the same user.
amzing content Tom. can you implement secure Server Sent Events for realtime functionality in nodejs
Hey Tom! amazing stuff :)
I realize this may not be the place but i'm getting back an error when trying the Login route - Error: secretOrPrivateKey must have a value
any idea to the origin for it?
Log out the private key you're using to sign the token, it's probably not being read from your environment variables
Please is it recommended to add an expiration time to the user verification code? Maybe it will expire in 15min.
Sure, sounds good
what would you recommend to adding Google / Facebook Auth. Adding passport to this seems like it would be too complex or unncecessary
I made a video where I add Google OAuth to this app
@@TomDoesTech Thanks for the quick reply ! Will go through your channel. Your videos have been incredibly helpful.
hi, i did not understad the utility of adding and index in the user model, why should we do it?
Indexes make lookups faster
Hello Tom, came back to this video and wanted to ask a question. Instead of using { omit } from 'lodash' to send back private fields, is there a way you can use zod for readDto that way you only return the fields specified. And if that is not possible, is there a library you use to write Create, Read and Update Dto's on a requets?
Yeah, it is possible. You can parse your response through a Zod schema and it will remove the fields that aren't in the schema. I would personally still omit password, but just for peace of mind.
It's easier with Fastify to be honest
@@TomDoesTech got it! Thanks for the fast reply (:
Error: secretOrPrivateKey must be an asymmetric key when using RS256 at Object.module.exports [as sign] (C:\Users\pc\Desktop\Node-TS-Auth
ode_modules\jsonwebtoken\sign.js:130:22) at signJwt (C:\Users\pc\Desktop\Node-TS-Auth\src\utils\jwt.ts:15:16) I have been having this issue for a week now. Please help
I sir can i get any repo where we implemented req.file using typescript zod express
Need help
Very good content. I've learned a lot. The video is well done. I've follow twitter account.
default value nanoid throw an error and I don't know why that's happening
use this version
yarn add nanoid@^3.0.0
instead of the one in the video
@@Sfaatman Thanks, I don't knw why but for some strange reason it is working now, maybe a set up was wrong
Why do we need to encode jwt access keys to base 64. I mean is there any security advantage to this practice?
It means you don't have to worry about the formatting
Nice content Tom, really helpful, how can one declare an array data type containing enum values
MyEnum[]
I am new in typescript, can you make a video on the FilterQuery function's functionality, how should I write it to sort, or filter the document based on particular fields like _id, name, email etc. does it filters based on what value is being passed into it ?? on do i have to customise the queryOptions part ?? its not clear in this video. please make another elaborated video on this.
How to logout? If We delete the session in logout route, not possible to generate new access token. But by that time the access token is still valid. We can access /me route with that access token. Btw great content man, very much appreciated.
Why do we need 2 types(public and private)of secret keys?
public/private key pair
Hello, why isn't anything in the session unique? Meaning, there can be multiple sessions with the same user id
A user can login on different devices. A session also doesn't get deleted, you can keep them to see how many times a user had logged in and what devices they logged in on
Wouldn't it be better if you returned 401 instead of 403 in 1:58:32?
Yeah, probably
Thanks for the amazing video. Has someone achieved to configure swagger for auto api docs? I digged into swagger-ui-express but looks like its works only with controller based classes
Did you found a solution?
Hey man nodemailer is down what do i use alternatively?
I get a 400 bad request error on postman anytime I try to test the create user endpoint. Since I don't get any other errors, I don't know where to start debugging. Can anybody help me, please?
Start by putting console.logs around your app to see what exactly is returning the 400
I don't think that you need add index to email, cause unique is itself index
Mehn I have have different challenges with this tutorial. Please Tom or anyone, I need some help with these issues. VerifyJwt is not working as intended and it is technically affecting the refreshToken logic
I am getting `Object is possibly 'undefined'` on "this" inside the @pre of the User class. Is there a property I need to change in the tsconfig file to remove the error?
you should enable this one "experimentalDecorators": true in the tsconfig.json file
@@danandvan It is actually enabled but the problem persists
Correction: I was using an arrow function for the callback of the @pre save hook and read the documentation of typegoose only to find out that you can't use arrow function here.
Typegoose docs: Arrow Functions cannot be used here, because the binding of `this` is required to get & modify the document
Yeah the function keyword and arrow functions have different scoping
@@TomDoesTech hahaha yes, learned that the hard way 😅 thanks for your reply!
Hi Tom! How is config finding the environment variables? I'm getting the error "secretOrPRivateKey must have a value". the line `Buffer.from(config.get(keyName),"base64").toString("ascii") is returning undefined. I've included the dotenv config in app.ts.
Actually nvm, the problem was the file name, `custom-env.ts` threw that error, but `custom-environment-variables.ts` doesnt. Is `custom-environment-variables` a reserved file name or what?
[Confused]
Don't you have 3 of these already?
I have 2 that are very similar, this one focuses on auth more
kept typing, barely explained, super hard for beginner, especially the zod part so far.
Thanks for the tutorial anyway.
what's going on with
schema.parse({
body: req.body,
query: req.query,
params: req.params,
});
Really confused.
It's parsing the request through a schema
Can you do the same approach using graphql api instead of the rest api ?
I do have a tutorial that builds a GraphQL API with Typegraphql
Error: "User.email"'s Type is invalid! Type is: "undefined" is fixed at 44:35. I wasted 1hr fixing this on my own. 😞
Well that's silly, I showed you in the video how to fix that error.
@@TomDoesTech lol savage
Since you're already implementing sessions, why use JWTs at all? My understanding is that the primary benefit of JWTs is that they can provide a form of stateless auth, but if authenticating statefully with sessions wouldn't standard session identifiers do the same thing with less computational overhead?
JWTs are great, but how do you revoke a session from someone? How do you provide them with a short-lived access token without having to get them to login every few minutes?
@@TomDoesTech To revoke a session identifier you just delete it from the database and then any future authenticated requests will fail. IIRC the concept of init access + refresh identifiers aren't used with sessions as they're just kept in a httpOnly cookie and if someone gets that then you're being man in the middled and already have other issues (same if someone gets your JWT refresh token).
Do know I'm far from an expert here so I could be incorrect on a few points but thats my general understanding
@@departuream1440 Sorry. my question should have been, in a completelyt stateless system, how do you remove an access token?
Using a JWT and a refresh token allows the access to be stateless as long as the access token lives, but also allows you to remove access if required. It's a "best of both worlds" approach.
@@departuream1440 There are tones of articles on refresh tokens, might be better looking up one of them.
@@TomDoesTech Ah yes, but this specific implementation isn't really stateless is it? Sessions are inherently stateful.
1:25:55 on line 13, we have ...(options && options) , I don't understand why we need another 'options' and && operator there, anybody, explain it to me please..
Yes dude, it's simple! The && operator like this just returns the right variable only if the left one is defined. So in this case option will be returned only if it is not undefined or null.
@@Korazza aha, I understand now, thank you
What is the difference between the "ts-node" & "ts-node-dev" packages? I saw some of your previous videos where you were using "ts-node". But, in your recent tutorial, you're using "ts-node-dev".
You can read the README for ts-node-dev, it will tell you
@@TomDoesTech Thank you for your quick response. 😊
What’s your recommendation for a production server?
TIA 🙏
@@arifulalamarif3748 Neither, they are for running your TS app. You should build your app and run it with Node
@@TomDoesTech sorry, I meant for development. 😅
@@arifulalamarif3748 use ts-node-dev or tsx
What is the use of {...(options && options)} I know spread operator but never used like this.
Can anyone comment what is the difference between { ... options } and {...(options && options)}
The second will spread opetions on the object if it is defeined. In the first spread, if options is undefined you will be spreading undefined and your application will throw an error.
Guy is so nice to do it for free.
i think you should go to udemy and earn some money.
Can we use this API for android app authentication?
Yeah, I don't see why not. You'd probably need to do a few modifications, but it should work
Great tutorial! Ton's of excellent code and information. One thing that I'm a bit stumped by is this:
return jwt.sign(object, signingKey, {
...(options && options),
algorithm: 'RS256'
})
What purpose does the ...(options && options) serve here? What's happening there?
It's going to add the options object to the object, but only if options is defined.
@@TomDoesTech why not something like (options || {})? Seems a bit clearer IMO but I guess it doesnt really matter
@@departuream1440 That doesn't produce the same resule. That would produce {{}, algorithm: 'RS256'}
@@TomDoesTech ah makes sense then, thanks!
Why you using res.locals insdead of req.user?
The end result is the same, res.locals is generally used for passing data to a rendering engine. I use it instead of req.user because TypeScript doesn't complain
Have you followed the MVC design pattern? I think you have done the MVC design pattern. But you don't have a view folder there. Can you explain it? I can't understand the folder pattern. Thank you
He is building a rest api there won’t be a view folder. Because the frontend part will be controlled by a different project altogether.
because this is backend, not client side, that's why we don't have any view for layout here
Do you have specific question? I explained the structure int he video.
@@jahiddev Thanks
@@TomDoesTech ok thanks.
Hey Tom, this tutorial is great and I'm already half way and stuck with this "Error: require() of ES Module not supported" from last 2 Days. I have tried changing downgrading Node Version to 14, but still stuck. Any suggestions or help would be great.
It shows "Instead change the require of index.js in D:\Dev\Authentication\src\models\user.model.ts to a dynamic import() which is available in all CommonJS modules" but I don't have any "require" in any file of the project.
try changing the type to "module" in your package.json
@@TomDoesTech Thanks for the reply! But already tried that still shows "Error: Must use import to load ES Module: D:\Dev\Authentication\src\app.ts"
@@shlok6 bro try downgrading nanoid version. In my case that was the problem.
@@devanshsharma2106 Nope, still facing the same issue. If you're too facing the same issue, let's connect and figure it out together.
I was facing the same issue with nanoid, very frustrating I just decided to use another unique id maker library called cuid, as we just need a random uuid for verification code.
did you know why am i getting
"code": "invalid_type",
"expected": "string",
"received": "undefined",
"path": [
"body",
"lastName"
],
all the time doesnt matter what am i typping for all fields
Did use use the express body parser middleware?
@@TomDoesTech yeah
Why don't you create an Udemy course, I think it would be the best course:)
I can't seem to figure out how to locate the environment variables in postman? I have imported the collection json file but there are still no environments available to choose from?
You should have an environment in the dropdown, if you don't create one.
You work in infosys?
no
Hi Tom..absolutely love your videos. There's something I started getting obsessed with lately and that's the latency of the api requests and how to make them smaller. I noticed in this video the latency is really small, all below 50ms which is amazing. What is the main reason for such latencies because in another of your videos the latency was around 230ms. Thanks as I anticipate your response
Which endpoint was 230ms? If it uses bcrypt, that can be expected, it's slow by design
I had a problem: res.locals.user is undefined. And my problem lies in: In my header, instead of having Authentization i named it x-access-authentization, therefore I couldn't parse it in deserializeUser
1st comment 😄
Why using Typegoose ?
I like getting the interface from the model
Second 😂
looks like you are using nestjs.....
I'm not
@@TomDoesTech why? It's good framework with a lot of embedded tools
@@angrysmilex What? I'm not using it in this tutorial.
1:12:21