QR Code Generator Service with Node.js and Express.js (original) (raw)

Last Updated : 23 Jul, 2025

Nowadays, Quick Response (QR) codes have become an integral tool for transferring information quickly and conveniently. This project aims to develop a QR code generation API service using Node.js and Express.js. In addition, it goes further and extends the former by providing more customization options to follow RESTful API design principles and handle errors.

**Output Preview: Let us have a look at how the final output will look like.

fgdh

Prerequisites

How QR Codes Work?

Quick response codes (QR codes) are two-dimensional barcodes that can store much more information than traditional one-dimensional barcodes. The following are the basics of how it works.

  1. **Data encoding: The given data (text, URL, contact information, etc.) will be converted into a sequence of bits (binary digits i.e. 0s and 1s).
  2. To create “qrcode” and other QR codes in our API, the library uses an error-correcting method that adds extra bits to ensure that even if some parts were damaged during transmission or scanning, it can be rebuilt from scratch.
  3. **Reading and decoding: A smartphone camera or a reader specifically designed for QR codes is able to recognize unique barcodes. The decoder looks for patterns to find timestamps and grid size. It then ejects the data module together with the error correction bit. The error correction algorithm repairs any possible errors that may occur based on the image.
  4. Finally, this decoded data is then reversed to its original form i.e. text, URL etc.

Approach to create QR Code Generator Service:

We will follow some industry standards to organize our code and write the application server. The separation of controller, routes, and services layer helps to make the code more readable, modify friendly and such modules can be easily debugged for server issues.

Steps to create QR Code Generator Service

**Step 1: Create the folder for the project by using the following command.

mkdir qr-code-generator
cd qr-code-generator

Step 2: Create the server folder inside it and initialize the Node application:

mkdir server
cd server
npm init -y

**Step 3: Install the required dependencies:

npm install express qrcode body-parser cors

**Project Structure:

feretgf

Folder structure

The updated dependencies in package.json file will look like:

"dependencies": {
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.18.2",
"qrcode": "^1.5.3"
}

**Example Code for Backend: Now create the required files as suggestedand add the following code.

JavaScript ``

//app.js

const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const router = require('./routes');

const app = express(); const port = process.env.PORT || 3000;

app.use(bodyParser.json()); app.use(cors()); app.use(router);

app.listen(port, () => { console.log(Server listening on port ${port}); });

`` JavaScript `

//controller.js

const service = require('./service');

exports.generateQR = async (req, res) => { try { const { data } = req.body;

    const qrCodeText = service.formatData(data);

    const qrCodeBuffer = await service.generateQRCode(qrCodeText);

    res.setHeader('Content-Disposition', 'attachment; filename=qrcode.png');
    res.type('image/png').send(qrCodeBuffer);
} catch (err) {
    console.error('Error generating QR code:', err);
    res.status(500).send({ error: 'Internal Server Error' });
}

};

JavaScript

//routes.js

const express = require('express'); const controller = require('./controller');

const router = express.Router();

router.post('/generate-qr', controller.generateQR);

module.exports = router;

` JavaScript ``

//service.js

const QRCode = require('qrcode');

exports.formatData = (data) => { const qrCodeText = Product ID: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>d</mi><mi>a</mi><mi>t</mi><mi>a</mi><mi mathvariant="normal">.</mi><mi>i</mi><mi>d</mi></mrow><mo separator="true">,</mo><mi>P</mi><mi>r</mi><mi>i</mi><mi>c</mi><mi>e</mi><mo>:</mo></mrow><annotation encoding="application/x-tex">{data.id}, Price: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal">d</span><span class="mord mathnormal">a</span><span class="mord mathnormal">t</span><span class="mord mathnormal">a</span><span class="mord">.</span><span class="mord mathnormal">i</span><span class="mord mathnormal">d</span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">i</span><span class="mord mathnormal">ce</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>${data.price}; return qrCodeText; };

exports.generateQRCode = async (qrCodeText) => { const options = { errorCorrectionLevel: 'M', type: 'image/png', margin: 1 };

const qrCodeBuffer = await QRCode.toBuffer(qrCodeText, options);
return qrCodeBuffer;

};

``

**Step 4: To start the application run the following command.

node app.js

**Step 5: Now go to the root folder and create folder for the frontend.

mkdir client

**Example Code for Frontend: Create the required files and add the following codes.

HTML `

QR Code Generator

QR Code Generator

ID:
Price:
Generate QR Code

CSS

/* style.css */

body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }

.content { margin-bottom: 15px; }

.margin { margin-right: 18px; }

.qr-input { padding: 10px; width: 200px; }

#qr-result img { margin-top: 20px; border: 1px solid #000; }

button { padding: 10px 12px; text-transform: uppercase; border-radius: 5px; background-color: bisque; }

JavaScript

// script.js

document.getElementById('qr-form').addEventListener('submit', function (e) { e.preventDefault();

const id = document.getElementById('qr-id').value;
const price = document.getElementById('qr-price').value;
const data = { id, price }

fetch('http://localhost:3000/generate-qr', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ data })
})
    .then(response => response.blob())
    .then(blob => {
        const qrImage = document.createElement('img');
        const qrImageUrl = URL.createObjectURL(blob);
        qrImage.src = qrImageUrl;
        const qrResultDiv = document.getElementById('qr-result');
        qrResultDiv.innerHTML = '';
        qrResultDiv.appendChild(qrImage);
    })
    .catch(error => console.error('Error generating QR code:', error));

});

`

Output: