question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Importing QRCodeStyling into NextJS immediately fails

See original GitHub issue

Using version 1.3.4

Simply adding import QRCodeStyling from "qr-code-styling";

causes the package to immediately fail with server error: ReferenceError: self is not defined

The library does not check to verify it’s running client side.

Workaround for now is to replace the import statement with if (typeof window !== "undefined") { console.log("i am client"); const QRCodeStyling = require("qr-code-styling"); }

Issue Analytics

  • State:open
  • Created 3 years ago
  • Comments:7

github_iconTop GitHub Comments

2reactions
Ali762commented, Apr 1, 2021

I got it working like this. I’m not sure why I used qrCode update - you might be able to use your data directly in the options.

export function QR( mydata) {
  let qrCode;
  if (typeof window !== "undefined") {           //Only do this on the client
    const QRCodeStyling = require("qr-code-styling");
    qrCode = new QRCodeStyling({
      width: 600,
      height: 600,
      data: "yourdata",
     ...etc

then

 qrCode.update({
    data: mydata,
  });
1reaction
rtorcatocommented, Apr 1, 2022

I created a react hook to use QRCodeStyling in NextJS. The following code should help it also uses typescript.

import React, { useEffect, useRef, useState } from 'react'

import DashboardLayout from '@app/layouts/DashboardLayout'
import { IPage } from '@app/ts/nextJS.types'
import PageContainer from '@app/components/containers/PageContainer'
import QRCodeStyling, { Options as QRCodeStylingOptions, FileExtension } from 'qr-code-styling'
import CardContainer from '@app/components/containers/CardContainer'
import Button from '@app/components/buttons/Button'

const styles = {
  inputWrapper: {
    margin: '20px 0',
    display: 'flex',
    justifyContent: 'space-between',
    width: '100%',
  },
  inputBox: {
    flexGrow: 1,
    marginRight: 20,
  },
}

const qrOptions: QRCodeStylingOptions = {
  width: 300,
  height: 300,
  image: 'https://upload.wikimedia.org/wikipedia/commons/5/51/Facebook_f_logo_%282019%29.svg',
  dotsOptions: {
    color: '#4267b2',
    type: 'rounded',
  },
  imageOptions: {
    crossOrigin: 'anonymous',
    margin: 20,
  },
}

const useQRCodeStyling = (options: QRCodeStylingOptions): QRCodeStyling | null => {
  //Only do this on the client
  if (typeof window !== 'undefined') {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const QRCodeStylingLib = require('qr-code-styling')
    const qrCodeStyling: QRCodeStyling = new QRCodeStylingLib(options)
    return qrCodeStyling
  }
  return null
}

const QrCodePage: IPage = () => {
  const [url, setUrl] = useState('https://cardstore.matrixdigital.com')
  const [fileExt, setFileExt] = useState<FileExtension | undefined>('png')
  const qrCode = useQRCodeStyling(qrOptions)
  const ref = useRef<any>(null)

  useEffect(() => {
    qrCode?.append(ref.current)
  }, [ref, qrCode])

  useEffect(() => {
    qrCode?.update({ data: url })
  }, [url, qrCode])

  const onUrlChange: React.ChangeEventHandler<HTMLInputElement> | undefined = (event) => {
    event.preventDefault()
    setUrl(event.target.value)
  }

  const onExtensionChange: React.ChangeEventHandler<HTMLSelectElement> | undefined = (event) => {
    setFileExt(event.target.value as FileExtension)
  }

  const onDownloadClick = () => {
    qrCode?.download({ extension: fileExt })
  }
  return (
    <PageContainer>
      <CardContainer>
        <div className="m-3">
          <h1 className="text-lg text-medium">QR Codes</h1>
          <div className="my-5">
            <div style={styles.inputWrapper}>
              <input value={url} onChange={onUrlChange} style={styles.inputBox} />
              <select onChange={onExtensionChange} value={fileExt}>
                <option value="png">PNG</option>
                <option value="jpeg">JPEG</option>
                <option value="webp">WEBP</option>
              </select>
              <Button theme="primary" onClick={onDownloadClick}>
                Download
              </Button>
            </div>
            <div ref={ref} />
          </div>
        </div>
      </CardContainer>
    </PageContainer>
  )
}
QrCodePage.getLayout = (page) => <DashboardLayout>{page}</DashboardLayout>

export default QrCodePage
Read more comments on GitHub >

github_iconTop Results From Across the Web

self is not defined nextjs | The AI Search Engine You Control
Primarily, the issue came up when I started to run an import QRCodeStyling from "qr-code-styling"; in my NextJS setup. "next": "latest",; "qr-code-styling": "^ ......
Read more >
Can't solve this error in next.js Deploying on Netlify. Imported ...
Next.js provides "public" folder for Static File Serving. You can find the details here. Put your image in public folder and change index.js ......
Read more >
How to Generate QR Code Using Node.js - Section.io
This tutorial will provide the readers a detailed guide on how to generate QR code from URL and Text using Node JS.
Read more >
easyqrcodejs - npm Package Health Analysis - Snyk
js 9.1)/ public ( >= Next.js 9.1) in the root directory. Script import Layout from '../components/Layout' ...
Read more >
How to solve "window is not defined" errors in React and Next.js
Which only runs at the rendering phase, so it won't run on the server. Let's update our scroll.js component: // components/Scroll.js import ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found