📲 Astro QR Code Generator #
In this video, we see how you can make your own, free Astro QR Code Generator. QR Codes are a convenient way to share links. Adding a QR code to your business card or merch can let potential customers get to your site just by scanning with their smartphone.
Some services offer free QR code generation but create a QR code which links to a URL shortening service. That service then forwards the visitor to your site. Unfortunately, some bad actors here stop forwarding after an initial period or demand a subscription fee. You might end up with your already distributed QR codes leading nowhere in this case. Luckily, if you know a bit about web development, we see it is pretty easy to generate your own QR codes which take visitors right to your own site.
As well as seeing how to generate QR codes, we see why you might consider using Svelte actions over an onMount function. If that doesn’t yet make sense, fear not! All shall become clear in the video. You can drop a comment below or reach out for a chat on Element as well as Twitter @mention if you have suggestions for improvements or questions.
📹 Video #
Please enable JavaScript to watch the video 📼
🗳 Poll #
🖥 Astro QR Code Generator: Code #
src/pages/index.astro
— click to expand code.
1 ---2 import QRCode from '~components/QRCode.svelte';3 import '~styles/fonts.css';4 import '~styles/global.css';56 const { request } = Astro;7 const { url: pageUrl } = request;8 const { searchParams } = new URL(pageUrl);9 const url = searchParams.get('url') ?? 'https://example.com';1011 const title = 'Astro QR Code Generator with Svelte Actions';12 const description = 'Astro QR Code Generator with Svelte Actions';13 ---1415 <!DOCTYPE html>16 <html lang="en-GB">17 <head>18 <meta charset="UTF-8" />19 <meta name="viewport" content="width=device-width" />20 <link rel="icon" href="/favicon.ico" sizes="any" />21 <link rel="icon" href="/icon.svg" type="image/svg+xml" />22 <link rel="apple-touch-icon" href="/apple-touch-icon.png" />23 <link rel="manifest" href="/manifest.webmanifest" />24 <title>{title}</title>25 {description ? <meta name="description" content={description} /> : null}</head26 >27 <main>28 <h1>Astro JS QR Code Generator</h1>29 <form action="">30 <h2>Enter a new URL:</h2>31 <div class="inputs">32 <label for="url" class="screen-reader-text">URL</label>33 <input id="url" name="url" type="text" placeholder="https://example.com" value={url} />34 <button type="submit">Generate</button>35 </div>36 </form>37 <p class="current-url">{url}:</p>38 <QRCode client:load url={url} />39 </main>4041 <style>42 h2 {43 margin-bottom: var(--spacing-8);44 }45 .inputs {46 flex-direction: row;47 }48 input {49 flex: 1 0 0;50 width: 100%;51 }5253 @media screen and (min-width: 48rem) {54 input {55 width: 30rem;56 }57 }58 .current-url {59 font-family: var(--font-family-monospace);60 max-width: var(--max-width-full);61 word-break: break-all;62 }63 </style>6465 </html>
tsconfig.json
— click to expand code.
1 {2 "compilerOptions": {3 "baseUrl": ".",4 "paths": {5 "~*": ["src/*"]6 }7 },8 "extends": "astro/tsconfigs/base"9 }
src/styles/fonts.css
— click to expand code.
1 /* cousine-regular - latin */2 @font-face {3 font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */4 font-family: 'Cousine';5 font-style: normal;6 font-weight: 400;7 src: url('/fonts/cousine-v25-latin-regular.woff2') format('woff2'),8 /* Chrome 36+, Opera 23+, Firefox 39+ */ url('/fonts/cousine-v25-latin-regular.woff')9 format('woff'); /* Chrome 5+, Firefox 3.6+, IE 9+, Safari 5.1+ */10 }1112 /* dm-sans-regular - latin */13 @font-face {14 font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */15 font-family: 'DM Sans';16 font-style: normal;17 font-weight: 400;18 src: url('/fonts/dm-sans-v11-latin-regular.woff2') format('woff2'),19 /* Chrome 36+, Opera 23+, Firefox 39+ */ url('/fonts/dm-sans-v11-latin-regular.woff')20 format('woff'); /* Chrome 5+, Firefox 3.6+, IE 9+, Safari 5.1+ */21 }2223 /* dm-sans-700 - latin */24 @font-face {25 font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */26 font-family: 'DM Sans';27 font-style: normal;28 font-weight: 700;29 src: url('/fonts/dm-sans-v11-latin-700.woff2') format('woff2'),30 /* Chrome 36+, Opera 23+, Firefox 39+ */ url('/fonts/dm-sans-v11-latin-700.woff') format('woff'); /* Chrome 5+, Firefox 3.6+, IE 9+, Safari 5.1+ */31 }
src/styles/fonts.css
— click to expand code.
1 :root {2 --spacing-px: 1px;3 --spacing-px-2: 2px;4 --spacing-0: 0;5 --spacing-1: 0.25rem;6 --spacing-2: 0.5rem;7 --spacing-4: 1rem;8 --spacing-6: 1.5rem;9 --spacing-8: 2rem;10 --spacing-12: 3rem;11 --spacing-24: 6rem;1213 --max-width-wrapper: 48rem;14 --max-width-full: 100%;1516 --font-size-root: 16px;17 --font-size-1: 1rem;18 --font-size-2: 1.25rem;19 --font-size-3: 1.563rem;20 --font-size-4: 1.953rem;21 --font-size-5: 2.441rem;22 --font-size-6: 3.052rem;2324 --font-weight-normal: 400;25 --font-weight-bold: 700;2627 --colour-dark: hsl(214 9% 15%); /* shark */28 --colour-brand: hsl(204 99% 36%); /* lochmara */29 --colour-theme: hsl(42 100% 70%); /* golden tainoi */30 --colour-light: hsl(248 100% 98%); /* sandwisp */31 --colour-alt: hsl(198 63% 38%); /* jelly bean */3233 --colour-theme-alpha-90: hsl(42 100% 70% / 90%);3435 --font-family-body: DM Sans;36 --font-family-monospace: Cousine;37 }3839 html {40 font: var(--font-weight-normal) var(--font-size-1) var(--font-family-body);41 }4243 body {44 display: grid;45 place-items: center;46 background-color: var(--colour-brand);47 padding: var(--spacing-12);48 color: var(--colour-light);49 accent-color: var(--colour-theme);50 caret-color: var(--colour-brand);51 }5253 main {54 display: flex;55 flex-direction: column;56 min-height: 100vh;57 width: min(var(--max-width-full) - var(--spacing-24), var(--max-width-wrapper));58 margin: var(--spacing-0) auto;59 }6061 h1 {62 font-size: var(--font-size-6);63 font-weight: var(--font-weight-bold);64 }6566 h2 {67 font-weight: var(--font-weight-normal);68 }6970 p {71 font-size: var(--font-size-1);72 margin-top: var(--spacing-2);73 }7475 @media screen and (min-width: 48rem) {76 p {77 font-size: var(--font-size-4);78 }79 }8081 form {82 display: flex;83 flex-direction: column;84 width: var(--max-width-full);85 max-width: var(--max-width-full);86 align-items: center;87 margin-bottom: var(--spacing-12);88 }8990 form h2 {91 width: 100%;92 }9394 input {95 line-height: 1.75;96 text-indent: var(--spacing-2);97 border: var(--spacing-px) auto var(--colour-dark);98 }99100 button {101 all: unset;102 cursor: pointer;103 background-color: var(--colour-theme);104 color: var(--colour-dark);105 padding: var(--spacing-px) var(--spacing-2);106 line-height: 1.75;107 }108109 button:focus {110 outline: var(--spacing-px-2) solid var(--colour-light);111 }112113 button:focus,114 button:hover {115 background-color: hsl(42 100% 70% / 90%);116 }117118 input,119 button {120 border-radius: var(--spacing-1);121 font-size: var(--font-size-2);122 }123124 .screen-reader-text {125 border: 0;126 clip: rect(1px, 1px, 1px, 1px);127 clip-path: inset(50%);128 height: 1px;129 margin: -1px;130 width: 1px;131 overflow: hidden;132 position: absolute !important;133 word-wrap: normal !important;134 }
src/components/QRCode.svelte
— click to expand code.
1 <script lang="ts">2 import QRCode from 'qrcode';34 let { url }: { url: string } = $props();56 function generateQRCode(canvasElement: HTMLCanvasElement, url: string) {7 QRCode.toCanvas(canvasElement, url, function (error: unknown) {8 if (error) {9 console.error(`Error creating QRCode: ${error as string}`);10 }11 });12 }1314 function useQRCodeCanvas(node: HTMLCanvasElement, { url }: { url: string }) {15 generateQRCode(node, url);1617 return {18 update({ url: newUrl }) {19 generateQRCode(node, newUrl);20 },21 };22 }23 </script>2425 <canvas use:useQRCodeCanvas={{ url }}></canvas>2627 <style>28 canvas {29 margin: 0 auto;30 padding: auto;31 }32 </style>
⌨️ Astro QR Code Generator: Font Links #
🔗 Links #
- complete code in Rodney Lab GitHub repo
- create Astro app post
- using self-hosted fonts with Astro
- NPM qrcode package
- Svelte actions docs
- Element chat: #rodney matrix chat
- Twitter handle: @askRodney
🏁 Astro QR Code Generator: Summary #
How easy is it to generate your own QR codes for free? #
- Quite easy so long as you are comfortable using the Terminal or know a little about web development. We saw the latter approach in action, creating an Astro app to generate QR codes for us. We used the qrcode package, available on npm. If you know what you are doing, as an alternative, you can set this up to generate the QR code from the command line. There is also an alternative CLI tool called qrencode (available on macOS via Homebrew and also Linux). Search for it on your system package manager.
How can you avoid adding an extra API route for form submission using Astro SSR? #
- Astro lets you define API routes to handle server functions in SSR mode. Typically, you listen for form submissions on one of these API routes. To save on boilerplate code, if you only need the form data for your client code (for example, if you do not have to store it to your database) you can set the form method to GET. You need to remember to name all the inputs and set the form action to an empty string. Now when you submit the form, the browser goes to the same URL as the form page, but now you will have the form inputs appended to the URL as URL search parameters. They will be URI encoded. Now you can update the interface with the submitted data, using `Astro.request.url` to access the URL and then parse the search parameters.
Why use Svelte Actions instead of onMount? #
- Svelte actions and onMount can each be used if you want to manipulate or mutate a DOM node. We saw an example where we painted a QR code to an HTML canvas node, but you also might want to add event listeners or update the node’s styles. Svelte actions use a little less boilerplate code than an onMount method. Besides this, they are easier to share between components. Finally, they have a mechanism for updating in-built. This saves you have to add an extra beforeUpdate or similar.
🙏🏽 Feedback #
Have you found the post useful? Would you prefer to see posts on another topic instead? Get in touch with ideas for new posts. Also, if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee.
Just dropped a new video on how you create QR codes using 🚀 Astro SSR and ❤️ Svelte actions.
— Rodney (@askRodney) February 6, 2023
Hope you find it useful!
#learnastro #useThePlatform #JAMStack pic.twitter.com/fydivqJUDq
Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter, @[email protected] on Mastodon and also the #rodney Element Matrix room. Also, see further ways to get in touch with Rodney Lab. I post regularly on Astro as well as SEO. Also, subscribe to the newsletter to keep up-to-date with our latest projects.