Using reCAPTCHA in React and Node

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
bots they can be good but they can also be bad when you've got a user registration form you want humans submitting form data not robots by accident submitting junk data so how can you stop that from happening you can use google recaptcha this video looks at how to add it both on the client side and react but also on the server side and the way it works is in the client you get access to this token you send the token to the back end and then google lets us know whether it's a success or not basically whether it's a bot or a human and then we can use that to decide whether we want to save the data that's being submitted to our backend or not so to get started this is the form we're working with i admit it's not very pretty but it does the trick it asks for the name of the user the email the password and they have to agree to our terms so we're going to be adding recaptcha to this in react so my previous video video showed how to build this form using react hook form we're going to sort of be adding on to that but this video is all about how to use recaptcha so just to give you an overview of what we're working with let's get out of our tests so this component here home that's the home page of this next.js application has a form with client-side validation it submits it to the server here and the server basically responds with success or failure so what we'll be adding is basically in around here we'll be adding in recaptcha on the client we'll submit that token to the server and then we'll go into the server side and verify whether it's a real human or a robot so the first thing you need to do when you're dealing with recaptcha is register a new site i've already gone into the recaptcha admin clicked register a new site and the first thing you're faced with is do you want v3 or v2 you may think of v3 it's better than v2 because it's one version more advanced but they sort of do different things v3 gives you a score between zero and one of basically how likely it's a human or not whereas v2 is the one that pops up an image and it says like click all of the fire hydrants or whatnot and you have to choose which one works the best for for your app the problem with v3 sometimes is there's no user interaction where they they get to interact so sometimes a real user gets a score of like point three and you have to force them through like a a two factor authentication so it's not always the best way to to go but we're going to be using v2 which is still the most popular approach so in v2 you can either have the where they have to check a checkbox or you can do the invisible badge which we'll be doing which is actually fairly similar to v3 except it doesn't give us a score it just gives us a true or false you have to add in your domain that you're doing it on agree to the terms and then you can submit so what this gives you is a site key this is the public one and then a secret key which is what you use on the back end because we're working in next.js when you're developing locally you can put your environment variables in this dot end.local so i already had a previous one i was playing with why don't i update it with the new one i'd like to take a minute to talk about app signal who has partnered with me on this video i was excited to partner with them because i've used them professionally on multiple websites and what it is is an all-in-one monitoring tool that gives you detailed insight into what your users are actually experiencing are they encountering errors either in the browser in your react code or on the server in your node or your ruby code are there any performance issues that are sort of slowing down your api is it database calls is it external apis what's actually making things slow how are your servers doing are they almost out of memory is their disk filling up etc but then you can take all of this information and customize it into different dashboards change the time frame that you're looking at and then set up anomalies so say you have an endpoint that typically responds in 200 milliseconds if it suddenly bumps up to two seconds you get notified via email or slack or whatever you set up so thanks to app signal head on over to their website at appsignal.com and you can try them out for one month for free and if you use the code l-e-i-g-h that's lee you get 10 off for the full year thank you paste this in here so there's one thing i wanted to point out that's sort of next js specific if you want your token visible in the client you add a next underscore public underscore ahead of it if you want it to remain a secret on the server only you leave that off and it won't via webpack expose this key on the server because if you add your secret key visible it's not so secret anymore is it so with that in place let's go to the terminal reboot our next js app so that it picks up the changes to the environment variables and then we can go in and start adding in the react code so i have already imported recaptcha from the react google recaptcha package and what we need to do now is go uh it doesn't matter where somewhere inside of our component i'll put it maybe above my server errors so we'll do this like this so it's telling us that there's an issue and we have to pass it a few props for it to work correctly so the first one is the site key and because we put that into an environment variable we can access that via process end and then the name of the environment variable so we'll just go and copy that the next thing we need to do is basically tell it that we want to use the invisible one versus the click a checkbox one and we do that strangely by saying the size is invisible and when you're dealing with invisible you have to sort of programmatically tell it to execute so you have the code and in order to be able to do that you need access to a ref to get to this so we'll define a ref as re-ref the recapture ref that we need to go up here and define so we pop up here and now we can say the re-ref is equal to use ref just like that so now we have access to it i think we can even define the the types here which is sort of cool we can say what type of ref is it going to be it's going to be a raft the recaptcha and now we have access to the ref when do we actually use it so when we want to use it is when the form is uh prior to the form being submitted to the server so what we can do is we can say prior to posting data to the server we want to get access to the token that this recapture thing gives us so cons token is a weight re-ref dot current dot and it is called execute async just like this so with the token in hand which is uh nicely working with type string typescript it's a string we can basically pass this token up to the server so we'll just come down here and pass this if we want to take a look at it just to make sure that it's working so let's just say token like that we'll go to our application and if things are working you should see this little protected by recaptcha showing up here now and if we fill in the information so lee email email.com password and agree to terms so what did i not do there we go so here is the token that we want to submit to the server um as we're playing around i don't want to have to fill out this form data every time so i'm just going to come back up here and say the default values for the form are lee email is email email.com the password is p word i've got some validations that it has to have upper lower number special character and be more than eight long so i was just making sure of that and the terms are already agreed to so now i can refresh the page and i don't have to fill this out every time and i still have access to the token so one thing say there's a there's an error on the server and you want to resubmit this if you just click submit again see how it's sort of like stuck in this submitting state so be every after every recaptcha sorry that was a mouthful um you have to reset the recaptcha so that it's reader ready for a subsequent check again and the way you do that is you say reref.current.reset so by calling reset it allows you to reach execute the recaptcha check a subsequent time if the data say was incorrect on the server and that's all there is to the client side aspect of this so now if we hop over to the server i'm in next.js so i'm inside of the api uh folder and auth endpoint and inside of my sort of request response handler here i'm given the request which i've already declared that the body will be receiving a token of value string so what i want to do now is define a function that basically takes this token sends it off to google google responds back back with whether it was a success or not so i am going to define this function here and we'll say it's an async function called validate human that will receive the token so token will be a string and it will respond with a boolean of whether that's a human or not did i do this right function validate human boolean is not oh right because it's async i need to wrap this inside of a promise and hopefully that will work a function okay so it's just missing a return statement now i think true there we go so the first thing i want to do is post this data to google but in order to do that you need that secret um recaptcha key that we've defined here so let's just put this inside of a variable called secret process dot n dot that and now we can make a fetch call to the google endpoint so we will await the response fetch and we've got the url it's a little bit of a mouthful to type out it's https slash slash google.com slash recaptcha slash api slash site verify and you need to pass up this secret plus the token so because i'm going to be embedding variables we'll switch to backticks now i can say that the secret is equal to secret and so the way you pass the token up it's not token even though that seems to make the most sense it's actually the response and what they mean by that it's the sort of human check response that was done on the client that results in this token here so that's the response that we're passing up so fetch on its own would want to do a get request we want to do an http post so we'll have to add in that the method is post and that should uh set us up good to go so we want to convert the response into some data so we'll say data is a weight response.json and why don't we just console.log what google is sending back to us and we'll pretend that it's a human um by returning true actually why don't we pretend it's a bot but will console.log the data data recaptcha data cool so we haven't called this function yet and i want to call it prior to trying to save the data and checking if the email already exists and all of that stuff because if it's not a human i don't even want to continue um because sometimes a bot would be submitting emails to check if it gets an error back of whether the email exists in your database or not and they may be trying to harvest and find out what users you have in order to use leaked passwords to try and gain access to your account hopefully this will block that because we won't allow bots to be submitting data to our form so we will say um if not actually why don't we put it into a variable if um human we will await validate human passing the token so if it's not a human we want to respond with a status of 400 which means an error and uh user input error and we want to respond with some json that includes an array of errors and the error that it will contain is uh please you are not fooling us bot perfect and we don't need to continue going after this so we're just going to do an early return from this function so that it doesn't keep checking here and responding with success etc so with this in place why don't we check to see if whether it's working or not so i'm going to refresh send this over and great please you're not fooling us bot and why don't we check to see what google responded on our back end check so because all of that code happened on the back end we need to go into the terminal here and we can see that the recaptcha data is actually success true so it thinks i'm a human which is good because i pretty sure i am so we just need to access this and return it rather than a hard-coded false value so we can do that by coming here and say return data dot success and we can get rid of our console.log and with this in place we hopefully have our backend validate human check working go back here let's refresh we'll submit this form and we get the success message so what that meant is basically client-side validation says good to go submit it to the back end with the token from recaptcha google says human good to go and then we had a subsequent um validation check where this is where you would check your database and perform some backend validation as well that one also said good to go there's no errors and because of that we responded with success so this is where you may redirect them back to the home page hopefully with like an authenticated token or cookie or something like that but that's beyond the scope of this video so what we've done is we've gone from um nothing at all we've registered a recaptcha key v2 invisible1 we've come over into react we've added in the recaptcha component setting the correct key which recaptcha method we're using the ref so that during the on submit event we could grab a token reset it for subsequent submissions send that token back to the uh the back end to the server the server receives this token passes it to the validate human function where we send the token along with our secret key to google they give us a response back which is either success or not and a success of true is basically that it's a human so if it were not a human we could respond with errors saying please you're not fooling us bot maybe you'd want something a little more professional but that's all we need to basically implement front-end back-end full-stack recaptcha check and to keep those bots away from our forms hope you have a nice day take care bye
Info
Channel: Leigh Halliday
Views: 21,072
Rating: undefined out of 5
Keywords: react tutorial, recaptcha tutorial, google recaptcha, recaptcha react, react recaptcha, node recaptcha, recaptcha form
Id: vrbyaOoZ-4Q
Channel Id: undefined
Length: 17min 33sec (1053 seconds)
Published: Mon Aug 03 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.