<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Teddy-Livingstone on Medium]]></title>
        <description><![CDATA[Stories by Teddy-Livingstone on Medium]]></description>
        <link>https://medium.com/@tememandu?source=rss-cda0e2f2da14------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YWYd9ZUnUrXj14zl9mrHfg.jpeg</url>
            <title>Stories by Teddy-Livingstone on Medium</title>
            <link>https://medium.com/@tememandu?source=rss-cda0e2f2da14------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 04:08:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tememandu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to set up Google Captcha with Ruby on Rails API and React frontend]]></title>
            <link>https://medium.com/@tememandu/how-to-set-up-google-captcha-with-ruby-on-rails-api-and-react-frontend-56426f88836c?source=rss-cda0e2f2da14------2</link>
            <guid isPermaLink="false">https://medium.com/p/56426f88836c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[captcha]]></category>
            <category><![CDATA[ruby-on-rails-api]]></category>
            <category><![CDATA[google-captcha]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Teddy-Livingstone]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 17:41:13 GMT</pubDate>
            <atom:updated>2023-02-11T10:16:18.157Z</atom:updated>
            <content:encoded><![CDATA[<h4>Set up Google captcha site key and secret key</h4><p>Go to <a href="https://google.com/recaptcha/admin/create">Google reCaptcha admin console</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UOCMdtmh8qGaGkYezGVpqw.jpeg" /><figcaption>recaptcha admin console</figcaption></figure><p>Select your site label, reCaptcha type v2 (since we are going for the challenge type), domain (localhost because we in development and don’t have a site hosted domain)</p><p>Next you will be presented with your site and secret keys (I have erased part of mine)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sigj-evyqaDkExxhVtz7xA.jpeg" /><figcaption>site and secret keys</figcaption></figure><h4>Set up Rails API backend</h4><p>Set up your rails backend app. We’ll call it <strong>captcha-backend. </strong>Go to your local directory and run the following command to generate API-only Rails app:</p><pre>rails new captcha-backend --api</pre><p>Add the following gems to Gemfile.</p><pre>gem &#39;recaptcha&#39;<br><br>gem &#39;httparty&#39;<br><br>gem &#39;dotenv-rails&#39;</pre><p>The first gem allows us configure captcha, the second for making requests to the verification site, the last for accessing environment variables.</p><p>We’d likely have CORS policy issue when making requests from the React frontend so uncomment the gem “rack-cors” line in the Gemfile and run bundle install .</p><p>Create an .env file and add site and secret keys as environment variables.</p><pre>CAPTCHA_SITEKEY=your_site_key<br>CAPTCHA_SECRETKEY=your_secret_key</pre><p>Create config/initializers/recaptcha.rb file and configure captcha.</p><pre>Recaptcha.configure do |config|<br>  config.site_key = ENV[&#39;CAPTCHA_SITEKEY&#39;]<br>  config.secret_key = ENV[&#39;CAPTCHA_SECRETKEY&#39;]<br>end</pre><p>Next, in the config/initializers/cors.rb file uncomment this code and change origins to “*” to allow request from all sites. You can use your more specific frontend URL if you wish.</p><pre>Rails.application.config.middleware.insert_before 0, Rack::Cors do<br>  allow do<br>    origins &quot;*&quot;<br><br>    resource &quot;*&quot;,<br>      headers: :any,<br>      methods: [:get, :post, :put, :patch, :delete, :options, :head]<br>  end<br>end</pre><h4>Set up React frontend with Vite</h4><p>You can set up your app with create-react-app , but I would be using Vite here.</p><p>Run yarn create vite in the directory you wish you generate you app. Next enter your project name — mine is <strong>captcha-frontend</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*BYZVHrlSL6eOlPCsfrX5pQ.jpeg" /></figure><p>Select the framework you want using the arrow keys. Select <strong>React.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*kaTFFsseiJOIY4pCdO5Drw.jpeg" /></figure><p>Choose <strong>JavaScript</strong> as your variant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*hJxgXaoMy-_fMmdmBjwmSQ.jpeg" /></figure><p>Next, cd into the directory, run yarn and yarn dev to view your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*koe1wBYEvG12l9cfxWwYDA.jpeg" /></figure><p>We would be using site key from the Google console so let’s create a .env file and add it to the file.</p><pre>VITE_CAPTCHA_SITEKEY=your_site_key</pre><p>Let’s install the react-google-recaptcha for building the captcha challenge UI.</p><pre>yarn add react-google-recaptcha</pre><p>We need a component for rendering the challenge. Let’s create a src/components/captcha-form.jsx file. Next we’ll import <strong>ReCAPTCHA </strong>from the react-google-recaptcha package we installed earlier and wrap it in a &lt;form&gt;element whose submission we’ll handle shortly.</p><p>The ReCAPTCHA component takes in various props but for now we only need sitekey and ref.</p><p>The captcha-form component should look like so:</p><pre>import React from &#39;react&#39;<br>import ReCAPTCHA from &#39;react-google-recaptcha&#39;;<br><br>const CaptchaForm = () =&gt; {<br><br>  const recaptchaRef = React.createRef()<br><br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault()<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;Captcha Challenge&lt;/h3&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;ReCAPTCHA<br>          sitekey={import.meta.env.VITE_CAPTCHA_SITEKEY}<br>          ref={recaptchaRef}<br>        /&gt;<br>        &lt;button type=&#39;submit&#39;&gt;Submit&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>}<br> <br>export default CaptchaForm;</pre><p>Then import the component to the App component:</p><pre>import &#39;./App.css&#39;<br>import CaptchaForm from &#39;./components/captcha-form&#39;<br><br>function App() {<br><br>  return (<br>    &lt;CaptchaForm /&gt;<br>  )<br>}<br><br>export default App</pre><p>Check your app in the browser. You may have an issue like in the error message below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*qDmrSqVjM8jVIPPWnME-CQ.jpeg" /></figure><p>This is because Vite’s URL is likely something like so: <a href="http://127.0.0.1:5173/b">http://127.0.0.1:5173/</a>. Remember we specified localhost as the allowed domain so if we change to this localhost:5173 the issue should be resolved. But you can also add 127.0.0.1 as an allowed domain and it would also work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*_yTuFc3vXqfiVZseqcRsFw.jpeg" /></figure><p>Next, let’s modify the handleSubmit method to show the returned value after solving the captcha.</p><pre>const handleSubmit = (e) =&gt; {<br>  e.preventDefault()<br>  console.log(recaptchaRef.current.getValue())<br>}</pre><p>If we solve the challenge and click submit, the value in the browser console should look like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*xOWXC5-b5j69sAP5xSLH0w.jpeg" /></figure><p>This is the value we need to send to the Rails backend to verify.</p><h4>Integrate React and Rails API</h4><p>Create the route.</p><pre>namespace :api do<br>  post &#39;/verify_captcha&#39;, to: &#39;verify#verify_captcha&#39;<br>end</pre><p>Start up the rails server rails s, create a controller - I’ll call mine VerifyController — in the app/controllers/api/verify_controller.rb file, import httparty.</p><pre>class Api::VerifyController &lt; ApplicationController<br>  require &#39;httparty&#39;<br><br>  def verify_captcha<br>    response = HTTParty.post(&#39;https://www.google.com/recaptcha/api/siteverify&#39;,<br>                              body: {<br>                                secret: Recaptcha.configuration.secret_key,<br>                                response: params[:captcha_response]<br>                              })<br>  end<br><br>end</pre><p>In the React frontend, update the handleSubmit method to send the captcha response to our backend:</p><pre>const handleSubmit = async (e) =&gt; {<br>  e.preventDefault()<br><br>  const response = await fetch(&#39;http://localhost:3000/api/verify_captcha&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    },<br>    body: JSON.stringify({captcha_response: recaptchaRef.current.getValue()})<br>  })<br><br>  const data = await response.json()<br>  console.log(data)<br>}</pre><p>Solve the captcha on the browser and click submit. If you log the response variable in the controller you would see that it looks like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IS-1w9o8lAIlFU8MggEIMw.jpeg" /></figure><p>The value of the success key is what we need. If the captcha was incorrectly solved we get false, else it returns true.</p><p>Update the verify_captcha action in the controller to return a message based on the value of success:</p><pre>def verify_captcha<br>  response = HTTParty.post(&#39;https://www.google.com/recaptcha/api/siteverify&#39;,<br>                            body: {<br>                              secret: Recaptcha.configuration.secret_key,<br>                              response: params[:captcha_response]<br>                            })<br><br>  if response[&#39;success&#39;]<br>    render json: { success: &quot;Captcha challenge is correctly solved&quot; }<br>  else<br>    render json: { error: &quot;Incorrect solution!&quot; }<br>  end<br>end</pre><p>If we solve the captcha correctly we get the nice message in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*pAKbC0Spjp_n4PVQ8l7wsA.jpeg" /></figure><p>And that’s all for now…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56426f88836c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>