Create Web beacon in Nuxt3

Nuxt

2023-11-03 23:31 (KST)

Language :

Hi, I’m Lovefield.

Web beacon is a common technology used to check whether a user has read an email. A method to plant an image that is 1x1px size and determine if it is loaded. It's not as difficult as I thought, so I'll write it briefly.

You must first use the Server Routes feature. Create an ~/server/routes/beacon.ts file.

export default defineEventHandler(async (event) => {
	
});

Once the file has been created, it can be accessed via the path "http://localhost:3000/beacon". If the information configuration is URL, params data can be obtained through getRouterPrams(event) within the file, and if the information configuration is queried, query data can be obtained through getQuery(event).

export default defineEventHandler(async (event) => {
    const data = getQuery(event); // or getRouterPrams(event)
});

You can then process data, communicate API, or create and archive files. Because each of us has a contextual approach. Let's move on to explaining that logic and describe how to create 1x1px-sized image information that should be displayed when the beacon URL is called.

First, if the information in the data is incorrect, you must display 404.

export default defineEventHandler(async (event) => {
    const data = getQuery(event); // or getRouterPrams(event)

    if(data.email === undefined){
        setResponseStatus(event,404);
    }else{
    }
});

Use the setResponseStatus function to convert the http status code to 404.

Next, you must generate image information.

export default defineEventHandler(async (event) => {
    const data = getQuery(event); // or getRouterPrams(event)

    if(data.email === undefined){
        setResponseStatus(event,404);
    }else{
        const imageData = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 1, 115, 82, 71, 66, 0, 174, 206, 28, 233, 0, 0, 0, 13, 73, 68, 65, 84, 24, 87, 99, 248, 255, 255, 255, 127, 0, 9, 251, 3, 253, 5, 67, 69, 202, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]);
        const imageBlob = new Blob([imageData], { type: "image/png" });

        setResponseHeader(event, "content-type", "image/png");
        setResponseHeader(event, "content-length", imageBlob.size);

        return imageBlob;
    }
});

I generated a piece of data using new Uint8Array(). The data is white, 1x1px size image information. Create a Blob object using the image information. Then, use setResponseHeader to specify the type of content and the size of the content. If you return Blob data via return, you can now see that the page displays an image of 1x1px.

Lovefield

Web Front-End developer

하고싶은게 많고, 나만의 서비스를 만들고 싶은 변태스러운 개발자입니다.