How to Add QR Codes to Your Sveltekit Project

  • I decided to use the 'qrcode' library, a popular npm, to add QR codes to my app.
  • To add it to my Sveltekit project, I installed 'qrcode' and its type definitions.
  • I particularly liked the SVG output feature of 'qrcode' as it allowed me to display the QR codes at different resolutions for screen and printing.
  • To allow flexibility for changing this library in the future, I wrapped this library inside a component.
  • I ensured that this component is capable of reporting errors and would display a generic error message in case of an issue.
  • I utilized Svelte's reactive nature to automatically update the QR code if it changes from its parent.
  • The new QR code component met all the app requirements.
How to Add QR Codes to Your Sveltekit Project

This morning, I needed to add QR Codes to my app. After some research, I have decided to use the popular qrcode - npm (npmjs.com), which currently has over 2 million weekly downloads.

Adding it to my Sveltekit project was very easy:

npm i qrcode
npm i --save-dev @types/qrcode

The SVG output feature is particularly useful because I need to display the QR code at different resolutions for both screen and print.

I always create a component to wrap libraries, such as qrcode, in case I need to change it for a different library later. Svelte makes this easy.

<script lang="ts">
    import { Spinner } from "flowbite-svelte";
    import { createEventDispatcher } from "svelte";
    import QRCode from "qrcode";
    export let code: string;
    
    let qrCode: string | undefined;
    let error: string | undefined;

    const dispatch = createEventDispatcher<{ error: string }>();

    $: {
        generateQRCode(code);
    }

    async function generateQRCode(code: string) {
        try {
            qrCode = await QRCode.toString(code, { type: "svg" });
        } catch (err) {
            const qrCodeError = (err as Error).message || "Unknown error: Unable to render QR Code.";
            if (error) {
                dispatch("error", qrCodeError);
            }
        }
    }
</script>

{#if !error}
    {#if qrCode}
        <div class="w-64">
            {@html qrCode}
        </div>
    {:else}
        <div class="w-64 h-64">
            <Spinner />
        </div>
    {/if}
{:else}
    <p>Unable to render QR Code.</p>
{/if}

The component must report any errors and display a generic error message if one occurs. It also uses the reactive nature of Svelte to update the QRCode if it changes in its parent.

This new component meets all my app requirements for adding QR codes.