npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mac-barrett/svelte-recaptcha

v1.2.1

Published

A SvelteKit/Svelte Component that handles all of your ReCaptcha needs!

Downloads

111

Readme

Svelte Kit ReCaptcha Component:

  • This component uses Google's v2 Captcha widget, which sends the user an 'I am not a robot' challenge.

Things to note

  • This has only really been tested inside of SvelteKit, I'm not sure if this works outside of that Framework
  • Please follow the tutorial steps for client & server validation below, it will explain how to use this component in pretty good detail.

Initial setup:

  1. Install the npm package:
npm i @mac-barrett/svelte-recaptcha
  1. Go to Google's captcha service and grab a SITE_KEY & a SECRET_KEY for use in the ReCaptcha widget. You can do so here: http://www.google.com/recaptcha/admin
    • Note that these keys are associated with your domain name, so if you want to use this on multiple sites you must acquire more keys.
  2. Set these keys up as .env variables so you're not hosting them anywhere malicous users can see them. The site key is for your browser pages while the secret key is for your server or endpoint to validate the captcha token.
  3. Import the ReCaptcha component & insert it into your HTML body:
<script lang="ts">
    import { ReCaptcha } from '@mac-barrett/svelte-recaptcha';

    let SITE_KEY = // your environment variable goes here
    let Captcha: ReCaptcha;
</script>

<ReCaptcha bind:this={Captcha} { SITE_KEY } captchaStyle={{theme: 'dark', size: 'compact'}}/>

Verifying Captcha Responses Client-Side:

  1. Bind the Captcha Element to a variable in your script tag & pass the SITE_KEY variable into the component as well as shown above.
  2. After completing the Captcha, you can get the token from the captcha widget by using the exported function getRecaptchaResponse().
formData.token = Captcha.getRecaptchaResponse();
if (formData.token.length === 0) {
    return;
}

Verifying Captcha Responses Server-Side

  1. Make sure to send the token from Captcha.getRecaptchaResponse() along with any other formData you're sending to your server.
  2. In your server endpoint, make an API call to google's recaptcha service to verify that the token the server recieved from the client is the same one that google sent to the client's browser. Your endpoint ought to end up looking something like this:
const SECRET_KEY = // your environment variable goes here

export const POST: RequestHandler = async ({ request }) => {
    const { formData } = await request.json();

    // First arg is token from the captcha, second arg is your site's URL
    // Yes you may use localhost
    const CaptchaResponse = await verifyCaptcha(formData.token, 'localhost:8080');
    if (!CaptchaResponse) {
        return {
            status: 400,
            body: 'ReCaptcha Failed to authorize on server, please try again'
        }
    }
    /* Captcha is verified, now you may handle the request as you normally would
        Do stuff
        Do other stuff...
    */
    return {
        status: 200,
        body: 'Captcha Verified, success or what have you'
    }
}

/**
* Calls the captcha API endpoint, returns true if captcha is succesful
* 
* @param token ReCaptcha Token from the client
* @param host URL of the site making the request
* @returns Promise containing captcha's success status
*/
async function verifyCaptcha(token: string, host: string): Promise<boolean> {
    const res = await fetch(`https://www.google.com/recaptcha/api/siteverify?secret=${SECRET_KEY}&response=${token}&remoteip=${host}`, { method: 'POST' });

    const data: { success: boolean; } = await res.json();
    return data.success;
}

Component Properties & Events:

<ReCaptcha SITE_KEY captchaStyle/>

Properties:

// The SITE_KEY associated with your domain
export var SITE_KEY: string;

// Used to style the widget
export var captchaStyle: {theme?: 'light'|'dark', size?:'normal'|'compact'} = {
    theme: 'light',
    size: 'normal'
}

Functions:

  • Bind the component to a variable in your script tag to use exported methods.
/** Returns the captcha's token if it has one. If no response it returns an empty string */
export function getRecaptchaResponse(): string {
    return grecaptcha.getResponse();
}

That's all there is to know! If there are issues please let me know.