0

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!

2
  • 1
    But how do you import the second file into the first one? That part of your code is missing (you say you're getting undefined, but what does?) Did you try import { fetch_out } from "./fileWithExports" ? Nov 8, 2021 at 14:43
  • 1
    return error; is not a good idea.
    – Bergi
    Nov 8, 2021 at 15:24

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.