How to convert SVG data into a PDF document with svg2pdf.js server-side with Deno?

We try to convert incoming SVG data into a PDF output that is stored on our server. The processing is restricted to JavaScript and is preferrably done on a Deno server (or node.js). Our approach is to send SVG data via POST request to our Deno server and use svg2pdf.js (extends jsPDF) to generate and store the resulting PDF document. In this post we describe our approach and share our experience for all of you working on a similar project. Moreover, we ask for the appraisal of yours that already have dealt with similar issues.

Running svg2pdf.js in the browser works remarkebly well and the conversion of SVG to PDF is accurate. Yet, running the library in the Deno environment differs slightly from the web browser and causes a few problems. The library is designed to run in the browser and relies on the DOM. Nevertheless, there are JavaScript implementations of the DOM Web API which may mitigate this problem. After importing svg2pdf.js on a Deno instance, it seems that the DOM is needed to (1) parse the SVG document and (2) calculate dimensions of objects.

In how far is running svg2pdf.js on a Deno server promising to successfully built a PDF?

Minimal example repository for reproducing the error: GitHub: proto-deno-svg2pdf

(1) Parsing the SVG document: Document Object Model for Deno

svg2pdf.js relies on a DOM to parse the SVG document tree. While Deno does not provide a native DOM API, though the module Deno DOM implements the DOM Web API. (Further DOM parsers are: jsdom, /zuisong/happy-dom-deno or LinkeDOM).

Deno DOM needs few added functions and attributes to parse a SVG document (e.g., Document:createElementNS(), Element:setAttributeNS()). So far, traversing elements and constructing the document tree seems to work fine. A few missing pieces seem to be easily extensible within the classes.

The rendering on the other hand seems more difficult to implement on a server…

(2) Calculating dimensions of SVG objects

svg2pdf.js additionally relies on the Canvas API to render objects. When executed in the browser the calculation and the subsequent rendering works very well.

Challenge: Dependencies to Canvas API and SVGGraphicsElement

In the Deno environment we have two blocking issues identified so far which raise the doubt in our current approach. Because svg2pdf.js relies on Canvas API as well as SVGGraphicsElement:

TextMeasure.prototype.canvasTextMeasure() relies on canvas.getContext('2d') which is not implemented in Deno DOM. Moreover, TextMeasure.prototype.svgTextMeasure() relies on SVGGraphicsElement.getBBox() which is not implemented in Deno DOM. That is why the conversion is stuck at the point of calculating the dimensions of SVG objects:

TypeError: textNode.getBBox is not a function
    at TextMeasure.svgTextMeasure (file:///home/christian/projects/svg2pdf.js_deno/dist/svg2pdf.es.js:594:25)

Other popular DOM parser like jsdom seem to omit the implementation of getBBox() as well. From this perspective it seems that there might be more problems down this path. Thats why we are in doubt about this approach.

My questions:

  1. For peer developers: Has anyone experiences with implementing svg2pdf.js on a Deno or Node.js server?

  2. For module maintainers: Svg2pdf.js depends on DOM and Canvas API. In how far are DOM parser such as Deno DOM or jsdom adequate tools for calculating dimensions of SVG elements printing them on a PDF?

For anyone interested in this challenge, please have a look at the minimum example repository linked above.
Thank you in advance for sharing your thoughts with me!

Uncaught ReferenceError: e is not defined at HTMLInputElement.onclick

I get this error where e is a MouseEvent.

My HTML that involve the problematic checkbox click event is like this:

<ItemTemplate>
    <tr style="border-top:1px solid  #adadad;border-bottom:1px solid  #adadad;">
        <td>
            <asp:HiddenField runat="server" id="hfOptionProductID" value='<%#Eval("Key.ProductID")%>' />
            <asp:HiddenField runat="server" id="hfOptionModelNumber" value='<%#Eval("Key.BTModel")%>' />
            <asp:HiddenField runat="server" ID="hfAssetId" value='<%#Eval("Value.AssetID")%>' />
            <p>
               <%#Eval("Key.Name")%><asp:CheckBox runat="server" id="chbxOption" class="chkOlcs" onclick="chkOlcs_onClick(e);"/>
            </p>
            <asp:Panel runat="server" ID="pnlOlcs" class="pnlOlcs" Visible="False">
                <asp:CheckBox runat="server" ID="chkDomain" class="chkDomain" onclick="chkDomain_onClick(e)" Text="I want to link my license to a specific domain and its subdomains." /><br/>
                <asp:TextBox runat="server" ID="txtDomain" class="txtDomain"  style="padding: 3px 5px; text-align: center; width: 200px;" placeholder="Enter a domain name"  ValidationGroup="OptionValidationGroup" disabled />
                <asp:Label runat="server" ID="lblDomainError" class="lblDomain" Visible="False" style="color: red;"/><br/>
                <asp:CheckBox runat="server" ID="chkAny" class="chkAny" onclick="chkAny_onClick(e)" Text="I do not want to link my license to a specific domain."/><br/>
            </asp:Panel>
            <br />
       </td>               
   </tr>     
</ItemTemplate>

In this above HTML, this is the problematic part:

<%#Eval(“Key.Name”)%><asp:CheckBox runat=”server” id=”chbxOption” class=”chkOlcs” onclick=”chkOlcs_onClick(e);”/>

For some unknown reason, when I run this in debug from Visual Studio in my Edge browser, I get the error.

Somehow e gets undefined and never reaches the Javascript function calls.

Here’s the Javascript function definition:

function chkOlcs_onClick(e) {
    var chkOlcs = $('#' + e.target.id);
    var pnlOlcs = chkOlcs.parent().parent().parent().find('.pnlOlcs');

    var isChecked = e.target.checked;
    if (isChecked) {
        pnlOlcs.show();
    } else {
        pnlOlcs.hide();
    }
}

Now to make this worst: When ran from the deployed web page, the error doesn’t occurs.

I have read pretty much all similar issues of this error but none seems to apply. I am open to any help.

unable to get local issuer certificate node.js app

Im given this error when i go to my node.js app. The subdomain didnt have an ssl cerificate before but now I have installed one so it is HTTPS. It still seems to be giving me the same error though and im not sure what to do.

“{“message”:”unable to get local issuer certificate”,”name”:”Error”,”stack”:”Error: unable to get local issuer certificaten at AxiosError.from (/home/taymiyya/nodevenv/new-node-app.info/20/lib/node_modules/axios/dist/node/axios.cjs:836:14)n at RedirectableRequest.handleRequestError (/home/taymiyya/nodevenv/new-node-app.info/20/lib/node_modules/axios/dist/node/axios.cjs:3010:25)n at RedirectableRequest.emit (node:events:511:28)n at eventHandlers. (/home/taymiyya/nodevenv/new-node-app.info/20/lib/node_modules/follow-redirects/index.js:14:24)n at ClientRequest.emit (node:events:511:28)n at TLSSocket.socketErrorListener (node:_http_client:495:9)n at TLSSocket.emit (node:events:511:28)n at emitErrorNT (node:internal/streams/destroy:151:8)n at emitErrorCloseNT (node:internal/streams/destroy:116:3)n at process.processTicksAndRejections (node:internal/process/task_queues:82:21)”,”config”:{“transitional”:{“silentJSONParsing”:true,”forcedJSONParsing”:true,”clarifyTimeoutError”:false},”adapter”:[“xhr”,”http”],”transformRequest”:[null],”transformResponse”:[null],”timeout”:0,”xsrfCookieName”:”XSRF-TOKEN”,”xsrfHeaderName”:”X-XSRF-TOKEN”,”maxContentLength”:-1,”maxBodyLength”:-1,”env”:{},”headers”:{“Accept”:”application/json, text/plain, /“,”User-Agent”:”axios/1.4.0″,”Accept-Encoding”:”gzip, compress, deflate, br”},”method”:”get”,”url”:”https://www.hadithapi.com/api/sahih-bukhari/chapters?apiKey=$2y$10$OJaOQ1PpJsXclWRHcoH3jE330eD1MP3ZYA1eTxXcjp1XxJY31u”},”code”:”UNABLE_TO_GET_ISSUER_CERT_LOCALLY”,”status”:null}”

This is what the error looks like when you go to the site

I have tried entering this: set NODE_TLS_REJECT_UNAUTHORIZED=0 into my terminal and nothing resulted from it

gram-js/gramjs add contact to contact list by phone number

there is add contact method but it ask parameter of user id how can i get the user id of telegram members by there phone

const { Api, TelegramClient } = require("telegram");
const { StringSession } = require("telegram/sessions");

const session = new StringSession(""); // You should put your string session here
const client = new TelegramClient(session, apiId, apiHash, {});

(async function run() {
  await client.connect(); // This assumes you have already authenticated with .start()

  const result = await client.invoke(
    new Api.contacts.AddContact({
      id: "username",
      firstName: "some string here",
      lastName: "some string here",
      phone: "some string here",
      addPhonePrivacyException: true,
    })
  );
  console.log(result); // prints the result
})();

and also getEntity(entity: EntityLike) Using phone numbers (from people in your contact list)

and also this

const { Api, TelegramClient } = require("telegram");
const { StringSession } = require("telegram/sessions");

const session = new StringSession(""); // You should put your string session here
const client = new TelegramClient(session, apiId, apiHash, {});

(async function run() {
  await client.connect(); // This assumes you have already authenticated with .start()

  const result = await client.invoke(
    new Api.contacts.ResolvePhone({
      phone: "some string here",
    })
  );
  console.log(result); // prints the result
})();

how can I get the users id by there phone number which is not my contact

Using data from one page’s textbox on another page on html/node.js

<form id="loginForm">
                <div class="mb-3">
                    <label for="txtUsername" class="form-label">Kullanıcı Adı</label>
                    <input type="text" class="form-control" id="txtUsername" name="txtUsername" required >
                </div>
                <div class="mb-3">
                    <label for="txtPassword" class="form-label">Şifre</label>
                    <input type="password" class="form-control" id="txtPassword" name="txtPassword" required>
                </div>
                <button type="submit" class="btn btn-primary">Giriş Yap</button>
            </form>

I want to assign the “txtUsername” data to the “value” part of the “txtUsername” section in the code below. How can I do that?

        <input class="form-control" type="text" id="txtUsername" name="txtUsername" value="" placeholder="kullanıcı ismi" disabled=" disabled">

Note: the codes are in different .ejs files.

Nodemailer not sending email when using it in my web hosting service

Recently I purchased a oviPanel(web hosting service) when I am using my code for nodemailer I am getting this error However if I am using the same code in localhost everything works fine. You can find the code in end. The password and username are correct here

ERROR is this

Invalid login: 435 4.7.8 Error: authentication failed:
at SMTPConnection._formatError (/home/rentomart/server/node_modules/nodemailer/lib/smtp-connection/index.js:790:19)
at SMTPConnection._actionAUTHComplete (/home/rentomart/server/node_modules/nodemailer/lib/smtp-connection/index.js:1548:34)
at SMTPConnection. (/home/rentomart/server/node_modules/nodemailer/lib/smtp-connection/index.js:546:26)
at SMTPConnection._processResponse (/home/rentomart/server/node_modules/nodemailer/lib/smtp-connection/index.js:953:20)
at SMTPConnection._onData (/home/rentomart/server/node_modules/nodemailer/lib/smtp-connection/index.js:755:14)
at TLSSocket.SMTPConnection._onSocketData (/home/rentomart/server/node_modules/nodemailer/lib/smtp-connection/index.js:193:44)
at TLSSocket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at TLSSocket.Readable.push (node:internal/streams/readable:228:10)
at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23) {
code: ‘EAUTH’,
response: ‘435 4.7.8 Error: authentication failed: ‘,
responseCode: 435,
command: ‘AUTH PLAIN’
}

CODE:::

import nodemailer from 'nodemailer'

export const sendEmail = async(email, subject, text) => {
    try{
        const transporter = nodemailer.createTransport(
            {
            host:process.env.HOST,
            port:Number(process.env.EMAIL_PORT),
            secure:Boolean(process.env.SECURE),
            auth:{
                user:process.env.USER,
                pass:process.env.PASS
            },
            tls: {
                rejectUnauthorized: false,
            },
            }
        )
        await transporter.sendMail({
            from:process.env.USER,
            to:email,
            subject:subject,
            text:text
        })
        console.log("Email sent successfully",email)
    }
    catch(error){
        console.log("Email not sent",error)
    }
}

Tried using chatgpt and the same code works fine in php here is the php code



            <?php 
            
include('smtp/PHPMailerAutoload.php');
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    
    $name= $_POST['name'];
    $email= $_POST['email'];
    $msg = "Job Application -".$_POST['message'];
    
    
    
    $mail = new PHPMailer(); 
    //$mail->SMTPDebug=3;
    $mail->IsSMTP(); 
    $mail->SMTPAuth = true; 
    $mail->SMTPSecure = 'ssl'; 
    $mail->Host = "the_host";
    $mail->Port = "465"; 
    $mail->IsHTML(true);
    $mail->CharSet = 'UTF-8';
    $mail->Encoding = "base64";
    $mail->Username = "the_username";
    $mail->Password = 'the_password';
    $mail->SetFrom("the_username");
    $mail->Subject = $subject;
    $mail->Body =$msg;
    $mail->AddAddress($email);
    $mail->SMTPOptions=array('ssl'=>array(
      'verify_peer'=>false,
      'verify_peer_name'=>false,
      'allow_self_signed'=>false
    ));
    if(!$mail->Send()){
      echo("<h2>Sorry could not be sent your response.</h2>");
    } else {
      echo("<h2> Thank you for your response!<h2>");
        echo("<p>Our team will get back to you soon</p>" );
        $folder_path = "./media";
        $files = glob($folder_path.'/*'); 
        
          // Deleting all the files in the list
          foreach($files as $file) {
              if(is_file($file)) unlink($file); 
          }
    }
    
}
else{
    echo("<center><i class='bi bi-envelope-fill' style='font-size:100px'></i><br>Fails to send the email");
      echo("<p> Form Not Submited</p><a href='/'> <b>Back</b></a></center>");
}

    



?>
          <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Contact form</title>
</head>
<body>
<h1>Contact us</h1>
<?php if (!empty($msg)) {
    echo "<h2>$msg</h2>";
} ?>
<form method="POST" action="#">
    <label for="name">Name: <input type="text" name="name" id="name"></label><br>
    <label for="email">Email address: <input type="email" name="email" id="email"></label><br>
    <label for="message">Message: <textarea name="message" id="message" rows="8" cols="20"></textarea></label><br>
    <input type="submit" value="Send">
</form>
</body>
</html>

How do i get data from Webuntis api?

i have a problem. I want to use Webuntis api and put the dates from the exam in the google calender. For now i want to learn how to use the Webuntis api but i get just an Error:
Error: Failed to login. {“jsonrpc”:”2.0″,”id”:”Awesome”,”error”:{“message”:”bad credentials”,”code”:-8504}}

i tried in javascript and in python. and in both of them is the same error

Javascript:

const { WebUntis } = require('webuntis');

// Erstelle eine asynchrone Funktion, um 'await' verwenden zu können.
async function main() {
  const untis = new WebUntis('BK-Beckum', 'name', 'Password', 'tritone.webuntis.com');
  await untis.login();

  const timetable = await untis.getStudents();
  console.log(timetable);

  // Weitere asynchrone Aufrufe oder Operationen können hier stattfinden.
  await untis.logout()
}

// Rufe die asynchrone Funktion auf.
main();

Python:

import webuntis

s = webuntis.Session(
    username="EngelhCar",
    password="PolizeiAuto006",
    server = "tritone.webuntis.com",
    school = "BK-Beckum",
    useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0"
    )

s.login()
for klass in s.klassen():
    print(klass.name)
s.logout()

I tried different URL’s and different schoolname’s. I uninstalled the webuntis and installed it again. i tried other funktions or parameter but then i got other error’s.

Node-modules Missing Directory

While I was coding I wanted to push to the github repo so I deleted the node modules before pushing to the repo named abamade but now that I have pulled the same repo when I use npm i it shows this:

found 0 vulnerabilities

npm WARN config global --global, --local are deprecated. Use --location=global instead.

up to date, audited 3 packages in 4s

found 0 vulnerabilities

But after this I still don’t have a node_modules directory in my folder

I was expecting to see the node modules directory to show

Javascript to control scroll of the webpage is not working

Im trying to create a submenu that pops from the side of the webpage. What I’m trying to achieve is that when the submenu is open, the scroll has to be disabled. I am written the below javascript for the same. For some reason, it is not working. Can anyone point out why.

Ps. the same code is working on another webpage of mine.

const USERINFO = document.getElementById("USERINFO");
const subMenu = document.getElementById("login-subMenu");
const closeButton = document.getElementById("closeButton");
const html = document.documentElement;


  html.addEventListener("click", function(event) {
    if (event.target !== USERINFO) {
      subMenu.style.right = "-445px";
      html.classList.remove("dimmed");
      document.body.style.overflow = 'auto'; // added this line
    } else {
      document.body.style.overflow = 'hidden'; // added this line
    }
  });


subMenu.addEventListener("click", function(event) {
  event.stopPropagation();
});
<div id="right_nav">
  <a id="USERINFO"> Help ></a>
</div>


<div id="login-subMenu">
  <button id="closeButton">Close X</button>
</div>

Do file-level Javascript functions / variables ever get garbage collected?

My single page app is getting rather big and I’m becoming a bit worried about the memory usage of just having functions and variables declared in file level scope.

For example, let’s say I have a bunch of exported helper functions declared in a file, and I import those and execute them in another part of my app.

If I only ever use those functions in one part of the application, wouldn’t they stick around in memory even after the user leaves that part of the application?

Normally I wouldn’t be worried about this, but my application is becoming rather large (50,000 lines of code at the moment), and I guess it just seems wasteful to have all this lying around?

As another example, I may have constants declared in a file that are only referenced in that file by some functions or classes, but wouldn’t that memory also stick around?

Is all of the above true? And if so, is there a better way of handling things? Is there any way to deallocate these things? It seems a bit “bad” to just constantly have thousands of functions loaded into memory if we are only ever using a few at a time.

My Redux persisted store is not persisting the state properly

I am creating a web app using Django as backend and React on frontend. Am pretty far ahead and almost ready to deploy on my staging server, currently just clearing some issues before I do that and I found out that my redux store which am using your persisting the state doesnt function properly. Everything works fine in terms of authentication, and navigating between pages, but when I hit refresh once the state is still there and when I hit the refresh again the user gets logged out.

I am new to Redux so I am not sure what could be the problem, I followed couple of tutorials and I tried to keep the configuration as simple as I can in order to avoid the unescessery complications.

I am using axiosInstance as interceptor to re authenticate user on every api call so I figured maybe thats where the issue lies but am not sure since its working good with the rest of the functions when it comes to login, logout, register, permissions etc..

Here is my redux store configuration:

import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { apiSlice } from "./api/apiSlice";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import authReducer from "../features/auth/authSlice";
import thunk from "redux-thunk";
import formReducer from "../features/modal/formReducer";
import modalReducer from "../features/modal/modalReducer";
import elementReducer from "../features/elements/elementReducer";
import editPageReducer from "../features/elements/editPageReducer";

const persistConfig = {
  key: "root",
  storage,
};

const rootReducer = combineReducers({
  auth: persistReducer(persistConfig, authReducer),
  formState: formReducer,
  modalState: modalReducer,
  elementState: elementReducer,
  editPageState: editPageReducer,
});

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: [thunk, apiSlice.middleware],
  devTools: true,
});

export const persistor = persistStore(store);


And here is my axios Interceptor:

import axios from "axios";
import jwt_decode from "jwt-decode";
import dayjs from "dayjs";
import { useSelector, useDispatch } from "react-redux";
import {
  selectCurrentToken,
  setCredentials,
  logOut,
} from "../features/auth/authSlice";
import { useRef, useEffect } from "react";
import store from "../app/store";

const useAxiosInstance = () => {
  const dispatch = useDispatch();
  const token = useSelector(selectCurrentToken);
  const user = useSelector((state) => state.auth.user);

  const createAxiosInstance = (token) => {
    const instance = axios.create({
      baseURL: "http://127.0.0.1:8000/api/",
    });

    // Set the authorization header
    if (token) {
      instance.defaults.headers.common["Authorization"] = `Bearer ${token}`;
    }

    return instance;
  };

  const axiosInstanceRef = useRef(createAxiosInstance(token));

  axiosInstanceRef.current.defaults.headers.common[
    "Authorization"
  ] = `Bearer ${token}`;
  
  axiosInstanceRef.current.interceptors.request.use(async (req) => {
    if (!token) {
      dispatch(logOut(user, token));
      console.log("IS IT LOGGGED OUT!!!!!")
      localStorage.removeItem("tokens");
      // Handle the case where the token is not available
      // e.g., redirect the user to the login page
      // or perform other necessary actions
    }

    const isExpired = dayjs.unix(jwt_decode(token).exp).diff(dayjs()) < 1;
    const getRefreshToken = localStorage.getItem("tokens");

    if (!isExpired) return req;

    try {
      const response = await axios.post(
        `http://127.0.0.1:8000/api/token/refresh/`,
        {
          refresh: getRefreshToken,
        }
      );
      localStorage.setItem("tokens", response.data.refresh);

      const newToken = response.data.access;

      // Update the axios instance with the new token
      axiosInstanceRef.current = createAxiosInstance(newToken);
      axiosInstanceRef.current.defaults.headers.common[
        "Authorization"
      ] = `Bearer ${newToken}`;

      req.headers.Authorization = `Bearer ${newToken}`;
      dispatch(setCredentials({ ...response.data, user }));

      return req;
    } catch (error) {
      // Handle refresh token request error
      localStorage.removeItem("tokens");
      dispatch(logOut()); // Replace with your logout logic
      throw error;
    }
  });

  return axiosInstanceRef.current;
};

export default useAxiosInstance;

I believe issue lies somewhere here but I am not sure where exactly.

Any help or feedback is very appreciated!

JavaScript app HTML page not invoking function

I am following a YouTube Javascript course chapter 34 “Make start button work” Javascript tutorial

and my HTML, CSS and Javascript are all in the same folder I am using VS Code and the Live Server extension.

This is the HTML

<html>
<head>
    <script src="index.js"></script>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <a href="index.js">Index.js</a>
    <h1>Blackjack</h1>
    <p id="message-el">Want to play a round?</p>
    <p>Cards:</p>
    <p>Sum:</p>
    <button onclick="startGame()">START GAME</button>
    
</body>

I added the link in the head so to check that the file was linked ok.

This is the CSS

    body {
    font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
    background-color: darkgreen;
    color:aliceblue;
    text-align: center;
}

h1 {
    color: goldenrod;
    text-align: center;
}

#message-el {
    
    text-align: center;
}

button {
    color:#016f32;
    width: 150px;
    background-color: goldenrod;
    padding-top: 5px;
    padding-bottom: 5px;
    font-weight: bold;
    border: none;
    border-radius: 2px;
}

And now the JavaScript

let firstCard = 10
let secondCard = 1
let sum = firstCard + secondCard
let hasBlackJack = false
let isAlive = true
let message = ""

function startGame() {
    if (sum <= 20) {
    message = "Do you want to draw a new card?"
    //console.log(message)
    } else if (sum === 21) {
        message = "Wohoo! You've got Blackjack!"
        hasBlackJack = true
    } else  {
        message = "You're out of the game!"
        isAlive = false
    }
}
//startGame()
console.log(message)
console.log(isAlive)

I have Node.js installed on the machine and I can see the output of the JavaScript file in the terminal section below the code. If I uncomment //startGame() and run the code it works outside of the HTML page. When I run the HTML file in live server it renders and if I follow the link it loads my JavaScript in another tab of my browser. However if I click the button on the web page there is no output in the console of VS Code.

Summary JS file works HTML doesn’t call startGame()

So where is the bug in this?

Many thanks for reading! 🙂

NextJS Component work in dev mode but not production mode

I’m experiencing an issue with the ‘Highlight’ component from ‘react-highlight’ when using NextJS in both development and production modes.

In development mode, the component renders properly with formatted styles. However, in production mode, it only displays plain text without the expected formatting.

I’m relatively new to NextJS, so I’m not sure what could be causing this difference. Do you have any idea why this might be happening? Any help would be greatly appreciated.

Header.tsx

'use client'
import "./Header.scss";
import { CodeBlock } from '../CodeBlock/CodeBlock';
import { codeSnipetsHeader, codeSnipetsHeader2 } from "./data";
import { useEffect, useRef } from "react";
import { motion } from "framer-motion";
import { usePathname } from 'next/navigation';

export function Header(): JSX.Element {

    const pathname: string = usePathname();

    /*Using useRef and ++ to regenerate <Header/> and play the animation each time the pathname changes. **/
    const ref = useRef<number>(0);
    useEffect(() => {
        ref.current++;
    }, [pathname]);

    let codeSnipetstoShow = codeSnipetsHeader2;
    if (pathname.length < 2) { codeSnipetstoShow = codeSnipetsHeader; }

    return (
        <header>
            <motion.div key={ref.current} className="group" exit={{ opacity: 0 }} transition={{ duration: 1 }}>
                {codeSnipetstoShow.map((value, index): JSX.Element => (
                    <motion.div key={index}
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 - (index * 0.2) }}
                        transition={{ duration: index + 1 }}
                    >
                        <CodeBlock language="typescript" text={value.text} fontSize={value.fontSize} margin={value.margin} />
                    </motion.div>
                ))}
            </motion.div>
        </header>
    );
}

CodeBlock.tsx

import { CSSProperties } from "react";
import Highlight from 'react-highlight';
import { motion } from 'framer-motion';
import './CodeBlock.scss';

interface CodeBlockProps {
    text: string;
    margin?: string;
    fontSize: number;
    language: "typescript" | "javascript" | "java" | "php";
}

/**
* @param text The text to be displayed as a code block
* @param margin Margin as top | right | bottom | left (in pixels)
* @param fontSize Display the text with the requested font size (in pixels)
* @param language The format (language to be used) for formatting
* @returns A code block that displays lines of code with color and formatting
**/

export function CodeBlock(props: CodeBlockProps): JSX.Element {

    const marginStyle: CSSProperties = props.margin ? { margin: props.margin } : {};
    const finalStyle: CSSProperties = { ...marginStyle, fontSize: props.fontSize };

    return (
        <motion.div className='codeblock' style={finalStyle}>
            <Highlight language={props.language}>
                {props.text}
            </Highlight>
        </motion.div>
    );
}

See pictures:
Dev Mode
Prod Mode

I tryed to use dynamic import without success.
I tryed to modify my css and split but without success.

I guess it’s something related to Static Rendering maybe ? Not sure

Timeout doesn’t delay each loop

I want to animate my logo and change its color quickly on hover. But it goes through the loop really quickly, as if setTimeout didn’t work. What have I mixed up?

let changeLogoColor = function(color) {
    document.documentElement.style.cssText = `
        --logo-color: ${"var(" + color + ")"};
    `;
    return null;
}

logo.addEventListener("mouseover", () => {
    elements.forEach((element) => {
        colors.forEach((color) => {
            setTimeout(changeLogoColor(color), 1000);
        });
    });
});