Your videos are amazing!! This tutorial is the perfect balance of explanation vs. instruction for a beginner-to-intermediate JS learner. Thank you so much for making these concepts super accessible and easy to follow. Subscribed!
this is really the best explanation , please do we can create more than one token , for example a token for admin to access some routes and another token for simple users
absolutely beautiful video. wow, thank you! Hope to see content from you on the authorisation you mentioned. Also any chance we could get a video that continues from this where we can pull content just for that particular user. for e.g. they can see a list of all articles they created on the site
What is the most secure way to store a JWT token on the client side ? local storage, session storage, cookies all are vulnerable to XSS or CSRF attacks.
I think it will be benefical to make the same video with PERN stack but combining two table that user can only his/her data instead of seeing everything
After if(!match) you should return the response: return res.status(400).json({error....}). This returns from the function and does not continue the execution of the next lines. This is why you received 'LOGGED IN' even with the wrong password. You should exit the function with return.
What a video. I understand it easily. Thank you very much. Permission to ask, because I'm still a beginner. I don't know how to make logout feature?? if there is your video related to this. please send the video link.
Thank you for this video. I have an error. const accessToken = req.cookies["access-token"]; It gives me "User not Authenticated! because accessToken is undefined. I checked it with console.log. It seems like it runs validateToken twice, and the first time, it gets the token, but for the second time, it gets undefined. What can be the problem? I have looked for the solution for a long time, but couldn't find it.
Awesome video Pedro thank so much :3. With the cookie created or the jwt, is it possible send it to the frontend to use the data of the user for example in a welcome message or the classic button on the right corner(sign-in / sign-out) ?
Really enjoyed the video, clear and to the point. Wanted to ask you about cookies, req.cookie sets the cookie for localhost:5000 (backend), how to set the cookie for the frontend? Like localhost:3000
@@PedroTechnologies Figured it out. I use axios in the front end so needed to add "withCredentials = true". I believe it works like cors does for the backend.
Amazing!! Could you go ahead and make requests that belongs only for the authenticated user? Another nice tip is showing how to do expiration and refresh with frontend :)
Thank you! I plan on making a video on refresh tokens and maybe include a logout functionality in it as well! With what we wrote in the video you can make requests that only belong to certain users, but that is authorization and not authentication.
Pedro as suas aulas são ótimas !!! Seria possível me ajudar em uma dúvida? após o login o usuário precisa ser direcionado para uma página principal, por exemplo... no seu código desta aula o roteamento seria feito no index.js ? Dentro da função app.post("/login", async (req, res) => { ... ?
@@PedroTechnologies Eu estou estudando o seu código mesmo, deste vídeo. Imaginei que após o login o usuário seria direcionado automaticamente para uma página principal, por exemplo. Eu estou usando o ReactJS
@@mbfreitas0 Apos o logi, vc tem que redirecionar através do React. Eu fiz um video falando sobre os diferentes metodos que vc pode usar pra redirecionar: ruclips.net/video/tiAlSpyWIDs/видео.html
Hey Pedro, thanks for making this video - it was really helpful! I successfully implemented this in the back-end of a project I'm currently working on. However, in the front-end (I'm using React), where should I store whether a login is successful or not? I know in previous videos you created a state called loginStatus and set it to true if the login was successful, but this doesn't seem secure to me as a user could just change that state to true! What is the most secure way to do this? Looking forward to your reply! Thanks bro!
Hey, there are many ways of doing this! You can save it in your sessionStorage, in a global state, and many different places. This won't be insecure because even if they change the state to logged in (which wouldn't work because you cant change a state through the browsers js), you should be validating every api request through the tokens!
@@PedroTechnologies Hey, thanks for the prompt reply. So I would set a global state in sessionStorage to true if they are logged in. Then would check the value of the global state before rendering the new page. If it is set to true, then render the new page. If I did it this way, then someone could still set their sessionStorage state to true and bypass the api request and end up rendering the new page? I know you said that changing a state through browser js isn't possible, but if someone managed to somehow set it true, wouldn't the new page end up rendering? Thanks so much bro!
@@PedroTechnologies Maybe a video on this might be a good idea! I couldn't find anything online which explained how to render a new page in React once a user has been authenticated (using JWT and a HTTP cookie)... Thanks bro!
@@edoardopavan6128 Hey, I realised much later after doing many projects using React that Pedro's original answer to my question is correct. The state cannot be easily changed and even if it is, any request to the back-end should have authentication (using sessions). If the authentication fails, the request will fail meaning the front-end won't display the data. So the way shown in this video is secure, providing your backend is secure..
Validating with sessions is a different type of authentication. In this case you can indeed use a protected route which is defined in the frontend. You can make a request to your server to check if you have a valid token in your http only cookie, then if so, you set some global state to allow you to login.
Awesome video, thanks man... Can you do the front-end implementation of this same auth flow? How will you use httpOnly cookies on the front-end.. I heard they only work on same domain, which isn't possible in development since server and frontend are on different ports What's your solution for this
Please, can you help me with a question ? when the user successfully logs in, do we usually handle the user redirection to a new page on the server or on the client side ?
@@PedroTechnologies Thank you Pedro for your response, I have rectified my error, I got the error because I'm sending a request to the backend without including a token in the headers. I have changed a little bit code from yours, you used "req.cookies["token']" to get the token from front-end, I used "req.headers["cookie"]", this is because I'm sending it as "cookie : ", through the headers, from the front-end.
Working quite well but I do have a question when I make the post request from my frontend(reactjs) the cookie won't automaticly go in the application of my browser i am using chrome and it's really frustrating , I can see my cookie in the request's cookie and I don't know how to get that cookie. If you could help with that I would be so gratefull
Thank you :) Well, you can store the access token in somewhere accessible when someone logs in (Ex. cookies, session/local storage (although not recommended)) and just verify them to get the information!
@@PedroTechnologies Yes...I did...I verified n got back the data which I stored into the jwt... Thank You So Much for this tutorial...This cleared my mind about jwt auth... seriously...thanks a lot... This Tutorial is quite helpful...😊
@@PedroTechnologies And make a video or videos on Admin Bro... please...😊...They way you teach, it clears every doubt...Thanks Again...Jwt video helped me out from JWT AUTH infinite loop of not understanding of the concept...😂😂
This Channel Shares so much Good Content and it was hidden from me a long time . thats sad but now i got this i am sure i will able to be into web dev and make proper apps . Thank You So Much Pedro Thanks Again! Also Can u share the Extensions you use for VS Code for Website Development
it's a really nice video but i am facing a problem. when i'm using postman i'm getting the thing done but when i use react post request i'm getting req.cookies as a [Object: null prototype] {} do u have any idea why :(
Your videos are amazing!! This tutorial is the perfect balance of explanation vs. instruction for a beginner-to-intermediate JS learner. Thank you so much for making these concepts super accessible and easy to follow. Subscribed!
Your explanation & tutorial helped me *finally* understand how to implement JWT! Amazing job
This is a really great intro to JWT. definitely helped me understand how to implement for my own project. Thanks!
Great to hear!
hands down the best tutor to leaarn from
your channel is a hidden gem! I'm so glad I found it
Welcome aboard! Happy to hear you are liking it!
this is really the best explanation , please do we can create more than one token , for example a token for admin to access some routes and another token for simple users
great explanation.
but I want to integrate this with my react js frontend, I am confused about how to display the errors in the frontend.
Your video is really beginner friendly, thank you so much for your help !!
Thank you sooo sooo sooooooo much . This is the only video that helped me
You are a life saver ! Do you have any video on the same stuff on front end ? How to set it on local storage ?
absolutely beautiful video. wow, thank you! Hope to see content from you on the authorisation you mentioned. Also any chance we could get a video that continues from this where we can pull content just for that particular user. for e.g. they can see a list of all articles they created on the site
What is the most secure way to store a JWT token on the client side ?
local storage, session storage, cookies all are vulnerable to XSS or CSRF attacks.
Caraca, tu tá lendo pensamento...tava pesquisando isso ontem!!! Valeu pelo vídeo.
kkkkkkk fico feliz que vc gostou!
I like the way you explain. It's clear and easy to understand.subscribed!
your tutorials are the easiest to follow, thanks!
This is my 100th time watching JWT on RUclips :) OMG nice video.
Hahaha Hope you like the video!
Same...🤣😂
most detailed video on this topic!
thanks, i learned a lot
your channel made me discover the gem of gems, sequelize...
I think it will be benefical to make the same video with PERN stack but combining two table that user can only his/her data instead of seeing everything
After if(!match) you should return the response: return res.status(400).json({error....}). This returns from the function and does not continue the execution of the next lines. This is why you received 'LOGGED IN' even with the wrong password. You should exit the function with return.
man you should teach us how to redirect after registeration in react and express
I have videos on how to use React Router Dom! You can use the component! I should make more videos on this soon!
@@PedroTechnologies yes please i am waiting for that and thanks :)
please make a video on how to implement "Log out from all other devices."
What a video. I understand it easily. Thank you very much. Permission to ask, because I'm still a beginner. I don't know how to make logout feature?? if there is your video related to this. please send the video link.
Thank you so much! It helped me a lot as a self-taught. I'm crying finally I can do it now T^T
Thank you for this video. I have an error. const accessToken = req.cookies["access-token"]; It gives me "User not Authenticated! because accessToken is undefined. I checked it with console.log. It seems like it runs validateToken twice, and the first time, it gets the token, but for the second time, it gets undefined. What can be the problem? I have looked for the solution for a long time, but couldn't find it.
Waah! Kya baat hai pedro dost ❤
Thanks Pedro! 👏
Simple and informative
Can please continue on this video and connect with react for font-end Thank you so much.
thank u guy. But i have a question about refresh Token. When Token is expried, how can i refesh. Please
Waah mast video hai ❤
Can please continue on this video and connect with react for font-end Thank you so much. please i beg pedro.
Awesome video Pedro thank so much :3. With the cookie created or the jwt, is it possible send it to the frontend to use the data of the user for example in a welcome message or the classic button on the right corner(sign-in / sign-out) ?
Yeah, after you make the request in the frontend you can just check to set a global states to be logged in!
Should I use this video as reference or your other video titled "Authentication With JWT Tutorial - React, NodeJS | How To"?
I feel like this one is more complete!
@@PedroTechnologies thank you so much for the response! Have a good day!
stucked in "Please install mysql2 package manually" issue. might go back and use your old auth tutorial :(
Really enjoyed the video, clear and to the point. Wanted to ask you about cookies, req.cookie sets the cookie for localhost:5000 (backend), how to set the cookie for the frontend? Like localhost:3000
Edit: You have backend as localhost:3001. But how to send cookie to diff url?
The cookie is set to the frontend! When you write res.cookie() it sets to the client side!
@@PedroTechnologies Figured it out. I use axios in the front end so needed to add "withCredentials = true". I believe it works like cors does for the backend.
Amazing!! Could you go ahead and make requests that belongs only for the authenticated user? Another nice tip is showing how to do expiration and refresh with frontend :)
Thank you! I plan on making a video on refresh tokens and maybe include a logout functionality in it as well! With what we wrote in the video you can make requests that only belong to certain users, but that is authorization and not authentication.
Pedro as suas aulas são ótimas !!! Seria possível me ajudar em uma dúvida? após o login o usuário precisa ser direcionado para uma página principal, por exemplo... no seu código desta aula o roteamento seria feito no index.js ? Dentro da função app.post("/login", async (req, res) => { ... ?
Boa Marcelo, obrigado! Após o login vc pode redirecionar dependendo de como seu frontend é. Você esta usando react? Ou somente html?
@@PedroTechnologies Eu estou estudando o seu código mesmo, deste vídeo. Imaginei que após o login o usuário seria direcionado automaticamente para uma página principal, por exemplo. Eu estou usando o ReactJS
@@mbfreitas0 Apos o logi, vc tem que redirecionar através do React. Eu fiz um video falando sobre os diferentes metodos que vc pode usar pra redirecionar: ruclips.net/video/tiAlSpyWIDs/видео.html
Legal Pedro vou assistir agora !!! Muito Obrigado pela Atenção \0/ ...Estou aprendendo muito com suas aulas !!! Valeu !!!
Nice content 🤝💥But what about to stop the user after logged in not to come back to login/register page?Like how to protect that routes after loggedin?
Thank you! I've been showing how to do this in my new series about full stack development!
Really well explained !! thankx Pedro 👍
Glad you liked it!
Please do bulk email sending tool by using MERN stack
Amazing tutorial
Glad you think so!
Hey Pedro, thanks for making this video - it was really helpful! I successfully implemented this in the back-end of a project I'm currently working on. However, in the front-end (I'm using React), where should I store whether a login is successful or not? I know in previous videos you created a state called loginStatus and set it to true if the login was successful, but this doesn't seem secure to me as a user could just change that state to true! What is the most secure way to do this? Looking forward to your reply! Thanks bro!
Hey, there are many ways of doing this! You can save it in your sessionStorage, in a global state, and many different places. This won't be insecure because even if they change the state to logged in (which wouldn't work because you cant change a state through the browsers js), you should be validating every api request through the tokens!
@@PedroTechnologies Hey, thanks for the prompt reply. So I would set a global state in sessionStorage to true if they are logged in. Then would check the value of the global state before rendering the new page. If it is set to true, then render the new page. If I did it this way, then someone could still set their sessionStorage state to true and bypass the api request and end up rendering the new page? I know you said that changing a state through browser js isn't possible, but if someone managed to somehow set it true, wouldn't the new page end up rendering? Thanks so much bro!
@@PedroTechnologies Maybe a video on this might be a good idea! I couldn't find anything online which explained how to render a new page in React once a user has been authenticated (using JWT and a HTTP cookie)... Thanks bro!
@@FrostGhost were you able to find any online resources?
@@edoardopavan6128 Hey, I realised much later after doing many projects using React that Pedro's original answer to my question is correct. The state cannot be easily changed and even if it is, any request to the back-end should have authentication (using sessions). If the authentication fails, the request will fail meaning the front-end won't display the data. So the way shown in this video is secure, providing your backend is secure..
i love your videos so much bro!! thanks! also pleaase do refresh tokens as well
PROTECTED ROUTE ? Login user cant access Signup page. until logout.
and login user cannot login again .
and store token Database and validate session
Validating with sessions is a different type of authentication. In this case you can indeed use a protected route which is defined in the frontend. You can make a request to your server to check if you have a valid token in your http only cookie, then if so, you set some global state to allow you to login.
How to add Google authentication ? Can you make a video on it
I can definitely do one!
Awesome video, thanks man... Can you do the front-end implementation of this same auth flow?
How will you use httpOnly cookies on the front-end.. I heard they only work on same domain, which isn't possible in development since server and frontend are on different ports
What's your solution for this
Please, can you help me with a question ? when the user successfully logs in, do we usually handle the user redirection to a new page on the server or on the client side ?
On the front using use navigation from react router from library
Thanks for the video pedro!!!
this video is banging! thanks pedro
hi 32:00 i did same thing with react and node Js .I cant see any cookie on my client side .Please help me
hi, did you mange to figure out how to login / verify from client
Thank you so much. It is really helpful
Thanks a lot pedro !!! How can I implement this on my frontend ?
I have a video on it: ruclips.net/video/KgXT63wPMPc/видео.html
@@PedroTechnologies thanks ! but how can you retrieve user data and display it in your page ?
in validateToken method i'm unable to get the accessToken, it is saying "cannot read property token"
Interesting, this might be a typo. Are you using typescript or js? Can you paste your code here for the token?
@@PedroTechnologies Thank you Pedro for your response, I have rectified my error, I got the error because I'm sending a request to the backend without including a token in the headers. I have changed a little bit code from yours, you used "req.cookies["token']" to get the token from front-end, I used "req.headers["cookie"]", this is because I'm sending it as "cookie : ", through the headers, from the front-end.
Working quite well but I do have a question when I make the post request from my frontend(reactjs) the cookie won't automaticly go in the application of my browser i am using chrome and it's really frustrating , I can see my cookie in the request's cookie and I don't know how to get that cookie. If you could help with that I would be so gratefull
hello , i am encountering the same error when trying to connect with frontend
if you got the solution for it can you please comment it down
Thanks...it is the very simple jwt auth I have Ever watched... Superb...🔥♥️. Bt how to get current logged in user's details...???
Thank you :) Well, you can store the access token in somewhere accessible when someone logs in (Ex. cookies, session/local storage (although not recommended)) and just verify them to get the information!
@@PedroTechnologies Yes...I did...I verified n got back the data which I stored into the jwt... Thank You So Much for this tutorial...This cleared my mind about jwt auth... seriously...thanks a lot... This Tutorial is quite helpful...😊
@@PedroTechnologies And make a video or videos on Admin Bro... please...😊...They way you teach, it clears every doubt...Thanks Again...Jwt video helped me out from JWT AUTH infinite loop of not understanding of the concept...😂😂
Hey Pedro, whenever I add in the wrong password in the login it crashes my server. Is there a way to make nodemon not crash.
This Channel Shares so much Good Content and it was hidden from me a long time . thats sad but now i got this i am sure i will able to be into web dev and make proper apps . Thank You So Much Pedro Thanks Again!
Also Can u share the Extensions you use for VS Code for Website Development
This makes me happy! Hope you like the videos!
I plan to make a video on my vscode extensions
it's a really nice video but i am facing a problem. when i'm using postman i'm getting the thing done but when i use react post request i'm getting req.cookies as a [Object: null prototype] {} do u have any idea why :(
Interesting, can you paste ur code here so i can take a look?
@@PedroTechnologies /// React Axios
handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('username', this.state.username);
formData.append('password', this.state.password);
const res = await axios.post('localhost:3001/api/login', formData).then( response => {
this.setState({resMessage: response.data.message});
this.setState({resStatus: response.data.status});
if(response.data.status === 'good'){
alert(response.data.status);
}
else{
alert(response.data.status);
}
});
}
/********** Express index.js ***********/
const express = require('express');
const app = express();
// Cookie Parser
const cookieParser = require('cookie-parser')
// Cors
const cors = require('cors');
// Body Parser
const bodyParser = require('body-parser');
app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
// > //
const userRouter = require('./routes/User');
app.use('/api', userRouter)
// Listen
app.listen(3001, () => { console.log(`Running on port 3001`) })
//*********** USER ROUTER **********/
const express = require("express")
const router = express.Router()
// Database Connection
const db = require("./../connection/conn")
// Login Route
router.post('/login', async (req, res) => {
const username = req.body.username;
const password = req.body.password;
const fecthUsersQuery = "SELECT id, username, password FROM users";
db.query(fecthUsersQuery, (err, results) => {
if(err){
return res.json({
status: 'bad',
message: "Something went wrong"
});
}
for(let user of results){
if(username === user.username && password === user.password){
const accessToken = createTokens(user);
res.cookie("access-token", accessToken, {
maxAge: 60 * 60 * 24 * 30 * 1000
})
console.log(req.cookies["access-token"]);
return res.json({
status: 'good',
message: "Test"
})
}
else{
return res.json({
status: 'bad',
message: "Username or password does not exist"
});
}
}
})
})
Thanks A lot!!! Really good video!
Hi perdro,
can you tell me please , after the authentication , how can i pass the username and id from login to profile .
This is gold
can i do this with react as frontend and use MySQL as database
What’s your vs code theme ?
Amazing tutorial!!
you didnt show how you setup your workbench
Thank you man 👌👌
superb explaination thnx
Thanks and welcome
@@PedroTechnologies can you please make a vidoe on how to automatically logout the first device when second device gets connected 😊😊
Hey Pedro ! How can you get httpOnly cookies with React ?
Brabo irmão!!
Obrigado mano!
The video is educative
Great pedro ❤️❤️🙌🏻🙌🏻
thanks a lot!
Noice go go go
Thanks ❤
great Thanks :)
Glad you liked it!
Amazing!!
Thanks!!
great content
Teşekkürler.
Desteği takdir ediyorum!
Thankyou
awesome
Thank you!
Do you have a job now, Pedro ?
Yeah, after months of studying interview questions I got an internship at Twitch hahaha
@@PedroTechnologies That's so cool
@@PedroTechnologies so cool. I am haapy for you. Keep hacking!
Thank you! Really appreciate it!
Thank you so much! The support you guys give me is unimaginable!