📎 Webclip
Let’s Make a QR Code Generator With a Serverless Function!
The article explains that QR code generation can be moved to a cloud function instead of shipping the full qrcode package with a site’s scripts. It uses DigitalOcean Functions and a small Node.js function that returns either a base64 image string or an <img> tag.
Reading notes#
- QR code generators already exist, but the
qrcodepackage is about 180 KB, so the author does not want to load it with the rest of the site scripts. - Cloud functions are presented as a place for code that runs only when needed, like a small API.
- DigitalOcean Functions is used for this example, and the article says functions are easy to deploy.
- A local project is created with
doctl serverless init --language js qr-generator. - The generated project includes a
/packagesfolder, and the example adds aqrfolder beside the sample function. - Inside
packages/sample/qr, theqrcodepackage is installed withnpm install --save qrcode. - The
qr.jsfunction requiresqrcodeand exportsmain, which callsqrcode.toDataURL(args.text). - The function returns a response with
content-type: text/html; charset=UTF-8and either the raw data URL or an<img>tag using that data URL. - The function can be tested in the terminal with
doctl serverless functions invoke sample/qr -p "text:css-tricks.com". - The
project.ymlfile must match the folder and function names, sohellois changed toqr. - Deployment uses
doctl sandbox connectand thendoctl sandbox deploy qr-generator. - After deployment,
doctl sbx fn get sample/qr --urlreturns the live function URL. - The article closes by saying the API can then be fetched to generate the QR code.
