"You need to specify a canvas element" error when using Cloudflare Workers with `qrcode`

Author: bkyervCreated Sep 15, 2023Updated May 23, 2025

I am encountering an error when attempting to generate a QR code using the qrcode library within a Cloudflare Worker. The error message is "You need to specify a canvas element".

Error stack:

Error: You need to specify a canvas element
    at getCanvasElement (index.js:2058:15)
    at Object.render (index.js:2069:20)
    at renderToDataURL (index.js:2088:32)
    at renderCanvas (index.js:2214:18)
    at qr (index.js:2307:31)
    at new Promise (<anonymous>)
    at Object.fetch (index.js:2306:24)
    at async jsonError (index.js:2337:12) {
  stack: Error: You need to specify a canvas element
    at…306:24)
    at async jsonError (index.js:2337:12),
  message: You need to specify a canvas element
}

Environment:

Using Cloudflare Workers.
Implementing the server API of the qrcode library.

Steps to Reproduce:

Set up a Cloudflare Worker.
Integrate the qrcode library to generate a QR code.
Execute the worker function to generate the QR code.

Expected Result: The QR code should be generated successfully.

Actual Result: Encountering the above error, which seems to suggest a canvas element is required.

I would appreciate any guidance or suggestions on how to resolve this issue, especially considering the context of using Cloudflare Workers where a DOM-based canvas isn't available.

Thank you!

Below is the source code for the worker

bash
export default {
	async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
		
		if (request.method !== 'POST') {
			return new Response('Method not allowed', { status: 405 });
		}

		try {
			const payload = await request.json();
			
			const qr = await QRCode.toDataURL(payload.uniqueTitle, { type: 'image/webp' });
			
                        return new Response(qr);

		} catch (e) {
			console.error(e);
			return new Response(null, { status: 500});
		}
	},
};