SoFunction
Updated on 2025-04-13

JS sample code for generating image verification code using svg-captcha

nodejs(nestjs)During the back-end development process, there will be a function that needs to generate image verification codes, which can reduce robot attack operations. This is also a relatively common function during the development process. Here we passsvg-captchato implement a verification code function and to optimize its logic slightly

First import the corresponding librarysvg-captcha

yarn add svg-captcha

This is how basic use is, it's very simple

var svgCaptcha = require('svg-captcha');

const svg = ()
 text
 Image data
text保存用于校验,Image data返回给客户端,Let the client compare

This verification code can only generate text and pictures. When generating code normally, we need to give it a random verification code. In this way, we need to save text information for convenience for verification, and even pass a id generated by ourselves as a comparison of unique values, but there is still a problem. This verification code has no identity information. Anyone visits it, a new one will be generated. If there are too many people in a short period of time, a lot of verification codes will be generated (of course, we only save the id generated by ourselves, and text will be used normally. It will be fine. It can be cleaned out if it expires)

What to do if there are a lot of people? Let’s save a few verification code texts and pictures directly. Assume that the number is limited to 10, recycle, valid for 1 minute, expiration is eliminated and replaced with new ones, and clean them regularly after use. Advantages are small in number and fast access. The disadvantage is that there will be duplications over a period of time (in fact, if you add a few more, you won’t see it, because the next time is random, and the expiration will be replaced with new ones. The maximum memory peak is like that, just like fake or real)

ps: Who can tell the truth about the world of development?

//You can also add id as needed, and add id here. As long as one is right, it is right, and you can be more rigorous.type ImageCodeType = {
    text: string
    image: string
    timeStamp: number
}

private imgCodes: any[] = []
private imgClearTimeout?: 

getVerificationCode() {
    const currentTime = new Date().getTime()
    const newCode: ImageCodeType[] = []
    ((item) => {
        if (currentTime -  < 60000) {
            (item)
        }
    })
    let imgInfo: ImageCodeType
    if ( < 10) {
        const captchaCode = ()
        imgInfo = {
            text: (),
            image: ,
            timeStamp: new Date().getTime(),
        }
        (imgInfo)
    } else {
        const index = (new Date().getTime() % 10)
        imgInfo = newCode[index]
    }
     = newCode

    //Avoid long-term memory occupancy, no one can use it to clean it up after 2 minutes    if () {
        clearTimeout()
    }
     = setTimeout(() => {
         = 0
         = void 0
    }, 120000)

    return 
}

Check it, set the id and get the corresponding verification. Here you can directly satisfy one of them.

//Let's compareconst code = params.verification_code.toLocaleLowerCase()
if (!this.img_code.find((e) =>  === code)) {
    return throw 'Please enter the correct verification code'
}

This is the article about JS's sample code for using svg-captcha to generate image verification code. For more related JS's svg-captcha image verification code content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!