<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>nextjs Archives - Michael Soriano</title>
	<atom:link href="https://michaelsoriano.com/tag/nextjs/feed/" rel="self" type="application/rss+xml" />
	<link>https://michaelsoriano.com/tag/nextjs/</link>
	<description>I turn code into captivating user experiences for the web</description>
	<lastBuildDate>Wed, 02 Sep 2020 05:57:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>
	<item>
		<title>Adding Google reCaptcha to our Next.js Comments Form</title>
		<link>https://michaelsoriano.com/adding-google-recaptcha-to-our-next-js-comments-form/</link>
					<comments>https://michaelsoriano.com/adding-google-recaptcha-to-our-next-js-comments-form/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Wed, 02 Sep 2020 05:57:26 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[nextjs]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=7243</guid>

					<description><![CDATA[<p>In my last post, we&#8217;ve added the comments area to our single post page. This included the comments list, along with the comments form. Remember we&#8217;re still working with the framework Next.js and WordPress REST API. But what good is a form if all we get is junk? What is stopping bots from spamming our [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/adding-google-recaptcha-to-our-next-js-comments-form/">Adding Google reCaptcha to our Next.js Comments Form</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In my <a href="https://michaelsoriano.com/easy-comments-area-for-the-single-page-using-next-js/">last post</a>, we&#8217;ve added the comments area to our single post page.  This included the comments list, along with the comments form. Remember we&#8217;re still working with the framework Next.js and WordPress REST API. </p>


<p>But what good is a form if all we get is junk? What is stopping bots from spamming our comments? This is where reCaptcha comes in. Let&#8217;s go ahead and add that to our form.</p>


<p><img fetchpriority="high" decoding="async" width="1354" height="772" src="https://michaelsoriano.com/wp-content/uploads/2020/09/undraw_wordpress_utxt.png" alt="" class="wp-image-7249" srcset="https://michaelsoriano.com/wp-content/uploads/2020/09/undraw_wordpress_utxt.png 1354w, https://michaelsoriano.com/wp-content/uploads/2020/09/undraw_wordpress_utxt-300x171.png 300w, https://michaelsoriano.com/wp-content/uploads/2020/09/undraw_wordpress_utxt-1024x584.png 1024w, https://michaelsoriano.com/wp-content/uploads/2020/09/undraw_wordpress_utxt-768x438.png 768w" sizes="(max-width: 1354px) 100vw, 1354px" /></p>


<p>We&#8217;re going to use reCaptcha v2 &#8211; the traditional &#8220;<em>I&#8217;m not a Robot</em>&#8221; checkbox. I&#8217;ve used version 3, and the invisible one, but for some reason I like the older style better.</p>


<p>Go and add the script tag in your head section of your template. </p>


<pre class="wp-block-code"><code lang="markup" class="language-markup">&lt;script src="https://www.google.com/recaptcha/api.js" async defer>&lt;/script></code></pre>


<p>Let&#8217;s add the field into our form. So open up CommentForm.js and add as part of the fields:</p>


<pre class="wp-block-code"><code lang="markup" class="language-markup">&lt;div className="g-recaptcha" data-sitekey="YOURSITEKEY">&lt;/div></code></pre>


<p>The site key can be hard coded in the form if you like. It is client side and is visible in the source code. Don&#8217;t worry about hiding this value. </p>


<p>If the site key and the script tag is good, it should render like below:</p>


<p><img decoding="async" width="528" height="524" src="https://michaelsoriano.com/wp-content/uploads/2020/09/captcha.png" alt="captcha" class="wp-image-7244" srcset="https://michaelsoriano.com/wp-content/uploads/2020/09/captcha.png 528w, https://michaelsoriano.com/wp-content/uploads/2020/09/captcha-300x298.png 300w, https://michaelsoriano.com/wp-content/uploads/2020/09/captcha-150x150.png 150w" sizes="(max-width: 528px) 100vw, 528px" /></p>


<p>Once this is done, we&#8217;re ready to continue to the steps below.</p>


<h3 class="wp-block-heading">Create an API Route</h3>


<p>So this part is necessary to serve as a proxy for our post request. See, we can&#8217;t go directly to the WordPress Comments API any longer like we did in the <a href="https://michaelsoriano.com/easy-comments-area-for-the-single-page-using-next-js/">previous tutorial</a>. We need a way to call Google&#8217;s api first, then go to WordPress. And we need this using Server side code. </p>


<p>Enter API Routes with Next.js. They&#8217;re still basically pages, but built mainly for JSON responses as an output. You can learn more about it <a href="https://nextjs.org/docs/api-routes/introduction">here</a>.  </p>


<p>Let&#8217;s create an <strong>api</strong> folder under pages, then create a new file called &#8220;<strong>comments.js</strong>&#8220;. This serves as the endpoint we call when we submit our form. </p>


<p>In <strong>comments.js</strong>, let&#8217;s add the code below:</p>


<pre title="comments.js" class="wp-block-code"><code lang="javascript" class="language-javascript">import Axios from 'axios';
export  default async (req, res) => {
    let googleUrl = 'https://www.google.com/recaptcha/api/siteverify?secret='+process.env.CAPTCHA_SECRET+'&amp;response='+req.body.captcha;
    let captchaResponse = await Axios({
        url : googleUrl
    });
    if(captchaResponse.data.success === false){
      res.statusCode = 500;
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify({ success : false, message : 'captcha failed' }));
    }else{
      //captcha passes, continue to wp api...
      let response = await Axios({
              method : 'post',
              url : process.env.BACKEND + `comments`,
              data : req.body
          }
      );
      if(response.status === 201){
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json')
        res.end(JSON.stringify({ success: true, message : 'record created, awaiting approval' }))
      }
    }
}</code></pre>


<p>If you look at the above code, we&#8217;re simply taking the values of the post (from our form), including the captcha response (we stuffed it inside req.body.captcha). Note that we&#8217;re using environment variables (process.env) to store secret keys and other stuff. See <a href="https://nextjs.org/docs/basic-features/environment-variables">.env files in Next.js</a> to learn more. </p>


<p>We call Google, and depending if it thinks you&#8217;re not a spammer, we go to WordPress API. Otherwise, we throw a 500 error.</p>


<h3 class="wp-block-heading">Submit Form Handler</h3>


<p>Back in <strong>CommentForm.js</strong> let&#8217;s modify our handleSubmit method to look like below:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript">const handleSubmit = useCallback( async (e) => {
        e.preventDefault();
        fields.captcha = grecaptcha.getResponse();
        let commentLocalApi = await Axios({
            method : 'post',
            url : '/api/comment',
            data : fields
        });
        if(commentLocalApi.status === 200){
            showSuccess = true;
            message = 'Your comment is waiting approval.';
        }
    }, [])</code></pre>


<p>Notice that we&#8217;re adding a new property called &#8220;captcha&#8221; to our <strong>fields</strong> object, right before we do the call. </p>


<p>And instead of submitting to WordPress directly, we do it to our newly created <strong>/api/comment</strong> endpoint. Depending on the response, we show some kind of messaging etc. </p>


<p>Give this a try and let me know what you think in the comments below. </p>


<p>Happy coding. </p>


<p> </p>
<p>The post <a href="https://michaelsoriano.com/adding-google-recaptcha-to-our-next-js-comments-form/">Adding Google reCaptcha to our Next.js Comments Form</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/adding-google-recaptcha-to-our-next-js-comments-form/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
