Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
How can I "encapsulate" this code into a module so it could become reusable?

I have got this Node.JS snippet and would like to write it as a module, so I can use recaptcha in different parts of my system.

This is how it currently looks like:

app.post('/register_user', (req, res) => {
  const secret_key = process.env.RECAPTCHA_SECRET;
  const token = req.body.recaptcha;
  const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`;
  fetch(url, { method: "post",})
    .then((response) => response.json())
    .then((google_response) => {
      if (google_response.success == true) {      
        res.format({'text/html': () => res.redirect(303, '/register'),})
      } else {
        return res.send({ response: "Failed" });
      }
    })
    .catch((error) => {
      return res.json({ error });
    });
})

I have tried to write the following module which works absolutely great, but I have absolute no idea about how to call it from the app.post, since I always get undefined as return:

import fetch from 'node-fetch';

export function fetch_out(url, timeout = 7000) {
    return Promise.race([
        fetch(url),
        new Promise((_, reject) =>
            setTimeout(() => reject(new Error('timeout')), timeout)
        )
    ]);
}
export async function checkRecaptcha(token, secret_key){
    const url = "https://www.google.com/recaptcha/api/siteverify?secret=" + secret_key + "&response=" + token;
    try{
    const response = await fetch_out(url, 1000);
    const google_response = await response.json();
    }catch(error){
        return error;
    }
    return google_response;
}

Any help would be appreciated! Thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could make this method reusable by removing the framework actions that need to happen and only return if the validation was successful or not. This way, it will be reusable in another project that doesn't use a specific framework.

Example module;

export async function checkRecaptcha(token, secret_key) {
    const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`;
    
    const response = await fetch(url, { method: "post",});
    if (!response.ok) return false;

    const json = await response.json();
    if (!json.success) return false;      
    
    return true;
}

Usage:

import { checkRecaptcha } from "./some-file-name";

app.post('/register_user', async (req, res) => {
    const isHuman = await checkRecaptcha(req.body.recaptcha, process.env.RECAPTCHA_SECRET);
    
    if (!isHuman) {
        return res.send({ response: "Failed" });
    }
    
    return res.format({'text/html': () => res.redirect(303, '/register'),});
});

If you specifically want to call an action after the validation, you can also use successful and error callbacks.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!