How can I conditionally render a React component if a sessionStorage variable does not exist in Next.js?

I have an <Authenticated> component that is used to render all of my authenticated routes. I want to prevent rendering the page until I have checked a token stored in sessionStorage.

'use client';

export const Authenticated = ({ children }) => {
  const token = typeof window !== 'undefined' ? sessionStorage.getItem('token') : null;

  if (!token) {
    return <></>;
  }

  return (
    <main>{children}</main>
  );
}

This works but I get this hydration error:

Uncaught Error: Hydration failed because the initial UI does not match what was rendered on the server.

Is there a better way to do this?

Numbers not appearing when I click on their button

I’m trying to make a calculator and I have completed the html and css files so far however, whenever I click on a number button it is not displaying in the display. I am not sure where I went wrong, it most likely is a easy fix that I am just not seeing.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cute Calculator</title>
    <link rel="stylesheet" href="style.css"/>
 </head>
 <body>
    <div id="calculator">
        <input id="display" readonly>
        <div id="keys">
            <button onclick="appendToDisplay('+')" class="op-button">+</button>
            <button onclick="appendToDisplay('7')">7</button>
            <button onclick="appendToDisplay('8')">8</button>
            <button onclick="appendToDisplay('9')">9</button>
            <button onclick="appendToDisplay('-')" class="op-button">-</button>
            <button onclick="appendToDisplay('4')">4</button>
            <button onclick="appendToDisplay('5')">5</button>
            <button onclick="appendToDisplay('6')">6</button>
            <button onclick="appendToDisplay('*')" class="op-button">*</button>
            <button onclick="appendToDisplay('1')">1</button>
            <button onclick="appendToDisplay('2')">2</button>
            <button onclick="appendToDisplay('3')">3</button>
            <button onclick="appendToDisplay('/')" class="op-button">/</button>
            <button onclick="appendToDisplay('0')">0</button>
            <button onclick="appendToDisplay('.')">.</button>
            <button onclick="calculate()">=</button>
            <button onclick="clearDisplay()" class="op-button">C</button>
        </div>
    </div>
    <script src="index.js"></script>
 </body>

</html>

body{
    margin:0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: url("./calckitty.jpg");
    background-size: cover;




}

#calculator{
    font-family: Arial, Helvetica, sans-serif;
    background: url("./kitty2.jpg");
    border-radius: 15px;
    max-width:500px;
    overflow:hidden;

}

#display{
    width:100%;
    padding:20px;
    font-size: 5rem;
    text-align: left;
    border:none;
    background: url("./kittytop.jpg");
    opacity: 90%;
    color:white;

}

#keys{
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 5px;
    padding: 20px;
}

button{
    width:100px;
    height:100px;
    border-radius: 50px;
    border: 1.5px solid pink;
    background-color: hsl(26, 93%, 89%);
    color: rgb(128, 118, 118);
    font-size: 2rem;
    font-weight: bold;
    cursor: pointer;

}

button:hover{
    background-color: hsl(332, 60%, 77%);
}

button:active{
    background-color: hsl(332, 60%, 83%);
}

.op-button{
    background-color: hsl(327, 44%, 35%);
}

.op-button:hover{
    background-color: hsl(327, 59%, 45%);
}

.op-button:active{
    background-color: hsl(57, 54%, 58%);
}
const display = document.getElementById("display");

function appendToDisplay(input){
 display.value += input;
 console.log;
 
}

function clearDisplay(){

}

function calculate(){

}

I went through my html file, made sure the .js and .html file were linked, they were and then I went back to make sure my ids were correct and they are.

How do I get the Photopea API to work as described?

According to the documentation for the Photopea API, the “script” parameter of the JSON configuration object “should be executed after loading each file (can be long)”

However, when I test the following simple JSON object within the Playground page, it appears that the script is trying to run BEFORE the files have fully loaded:

{
    "files": [ 
        "https://www.photopea.com/api/img2/pug.png",
        "https://www.photopea.com/api/img2/pug.png"
    ],
    "environment": {
        
    },
    "script" : "app.documents[1].rotateCanvas(90);"
}

The script attempts to rotate the canvas of the 2nd document, which presumably fails because the script executes before the 2nd file has loaded.

How, using the API, can I get the script to run only AFTER all the documents have loaded?

Why does my Node.js server occasionally hang when using async/await with event listeners?

I’m developing a Node.js server that listens to a stream of events from a message queue (like RabbitMQ or Kafka). I’m using async/await to handle asynchronous operations within my event listeners. However, I’ve noticed that occasionally the server seems to hang—no new events are processed, and no errors are thrown.

Here’s a simplified version of my code:

const { EventEmitter } = require('events');
const eventEmitter = new EventEmitter();

eventEmitter.on('data', async (message) => {
  try {
    await handleMessage(message);
  } catch (error) {
    console.error('Error handling message:', error);
  }
});

function startListening() {
  // Simulate receiving messages
  setInterval(() => {
    eventEmitter.emit('data', { content: 'New message' });
  }, 1000);
}

startListening();

handleMessage Function:

async function handleMessage(message) {
  // Simulate asynchronous processing
  await new Promise((resolve) => setTimeout(resolve, 2000));
  console.log('Processed message:', message.content);
}

After running for a while, the server stops processing new messages.
No error messages are logged.
CPU and memory usage remain normal.

Debugging: Added console logs before and after the await in handleMessage to see where it might be getting stuck.

Error Handling: Ensured that all promises have .catch handlers or are within try/catch blocks.

Concurrency Limits: Thought it might be due to overwhelming the event loop, so I considered implementing a concurrency limit but am unsure how to proceed.

  1. Is using async functions directly in event listeners a bad practice in Node.js?
  2. What could cause the event listener to hang without throwing errors?
  3. How can I modify my code to handle asynchronous event processing more reliably?

How to implement RSA encryption on the frontend

So, as the title says, I’m trying to implement a service on the client with SvelteKit that encrypts the user data sent to the server made with Express.

I’m trying to do achieve this with the RSA encryption that I found in several forums.

The thing is, on the backend, it works perfectly fine:

Encryption:

import { constants, publicEncrypt } from 'node:crypto';
import { readFileSync } from 'node:fs';

export const encryptData = (data: string) => {
  const publicKey = readFileSync('public.pem');
  const encryptedData = publicEncrypt(
    {
      key: publicKey,
      padding: constants.RSA_PKCS1_OAEP_PADDING,
      oaepHash: 'sha256',
    },
    Buffer.from(data),
  );
  return encryptedData.toString('base64');
};

Decryption:

import { constants, privateDecrypt } from 'node:crypto';
import { readFileSync } from 'node:fs';

export const decryptData = (data: string) => {
  const privateKey = readFileSync('private.pem');
  const decryptedData = privateDecrypt(
    {
      key: privateKey,
      padding: constants.RSA_PKCS1_OAEP_PADDING,
      oaepHash: 'sha256',
    },
    Buffer.from(data, 'base64'),
  );
  return decryptedData.toString();
};

But in the frontend I can’t find a way to get the server receiving the data and parsing it to a JSON. This is the last code I tried to implement:

Encryption:

import axios from 'axios';

async function retrieveRsaKey() {
  const BACKEND = import.meta.env.VITE_SERVER_URL;
  const PUBLIC_RSA_KEY = await axios.get(BACKEND + '/public_rsa').then((res) => res.data);
  return PUBLIC_RSA_KEY;
}

export async function encryptData (data: {[key:string]: unknown}) {
  const parsedData = JSON.stringify(data)
  const crypto = new Crypto;
  crypto.subtle.encrypt({name: "RSA-OAEP"}, await retrieveRsaKey(), parsedData)
}

Do you know can I achieve this? I’ve been searching for this topic for about two days and couldn’t find anything working with JS or TS only. Some even rely on PHP or Python to make the encryption.

What I have tried?

  • Use the “web crypto api”
  • Search for packages that imitate the functions in “node:crypto”

What am I expeting?

  • A service that receives a JSON with the information of an user that creates an encrypted message for the server with the PUBLIC RSA KEY.

Javascript flask tutorial

I am going through a tutorial, but it is not working and I can’t figure out why.

It is “Python + JavaScript – Full Stack App Tutorial”

https://www.youtube.com/watch?v=PppslXOR7TA

I downloaded the files whole sale, but when I use ‘npm run dev’ command it says

usage: vite [options]

A simple and minimal static site generator.

positional arguments:
{init,new,build,serve}
Options to help create, build and serve your project.

options:
-h, –help show this help message and exit
-v, –version show program’s version number and exit
PS C:Usersjudewdesktopusing python to interact with pdf and excel project!!! kevings program websiteold one for 1.5 hours can’t make workzzdowloadedfrontend>

When I try to go through the whole thing myself, it has a problem with line 70 is ContactList.jsx

{contacts.map((contact) => (

error is
Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)

It looks like contact doesn’t exist, and it is empty because I am just starting the program, but I have no idea what the problem could be.

Getting rasterized text in html canvas

I have main canvas on which I draw another canvas which had a text written on it. When I saw the results, it appears that the text is rasterized and not smooth.

Here is the code I tried :-

Code :-

const mainCanvas = document.querySelector('.main');
const mainCanvasContext = mainCanvas.getContext('2d');

const backgroundCanvas = document.createElement('canvas');
const backgroundCanvasContext = backgroundCanvas.getContext('2d');

const run = async () => {
  backgroundCanvasContext.font = '500 300px MatterSQ';
  ctx.fillStyle = 'white';
  ctx.fillText(text, 1920 / 2, 30);

  mainCanvasContext.drawImage(backgroundCanvas, 0, 0, mainCanvas.width, mainCanvas.height);
};

run();

Here is the HTML and CSS setup:

<canvas class="main"></canvas>
.main {
  width: 800px;
  aspect-ratio: 16 / 9;
  background: blue;
}

Problem: The final text canvas draw on the main canvas has blurry / rasterized text

Here is the Final Result :-
enter image description here

How to add js/css style to svelte-kit project

I have a js effect called color changin in codepen and i dont how implement it into my svelte-kit project like I tried to implementing this directly into app.css and app.html but it didn’t work I dont how to implement it into svelte-kit project and there is my project structure.
enter image description here

implementing that effect into my project properly

Handling delayed API responses with multiple button clicks [closed]

I’m working on an e-commerce product page where users can add items to their cart by clicking an “Add to Cart” button. Here’s the issue I’m facing:

When a user clicks the “Add to Cart” button, an API call is made to update the cart on the server. However, sometimes the server response is delayed due to high traffic. During this delay, if the user clicks the button multiple times, multiple requests are sent, causing the product to be added multiple times.

This leads to two main problems:

  • The same product gets added multiple times.
  • The user doesn’t get immediate feedback, so they keep clicking.

I haven’t yet added any handling to prevent multiple requests or feedback for the user. I’m wondering what the best way is to:

  • Disable the button until the request is completed,
  • Handle the situation in case the user clicks too fast or the server responds slowly.
  • Any suggestions or best practices on how to handle this?

I did same in my previous project but that time worked.

Please advice me remix template [closed]

I am new to remix (not to js and web dev though) and gonna write my first project on it.
My stack is:

  • taiwind (which is see pretty everywhere. GOOD)
  • vite (good)
  • typescript
  • mysql (bad because I haven’t found any template supporting it. BAD)
  • no specific CI/Deploy pipeline (and not gonna to invest dev time now)
  • session-cookie based user auth
  • zero knowledge in client side testing (please advice some test framework for beginner)
  • own hosting with nodejs and pm2 behind nginx.
    I see that there is no template with this stack and either one requires adjustements.
    What would you advice to take for customization to fit my needs

JavaScript Pass Object Parameters to Reusable Function

I have a function that I use frequently to lookup parameter values in objects…

let paramDesc = objName.find((e) => e.param1.includes(searchVal));
return paramDesc.param2;

that I would like to turn into reusable code. Here’s a working example where I hard-code the object and parameters, followed by my crude attempt to make it resusable:

const noteLocations = [
  { note: ["D3", "C##3"], locations: ["s6f10", "s5f5", "s4f0"]} ,
  { note: ["D#3", "Eb3"], locations: ["s6f11", "s5f6", "s4f1"]} ,
  { note: ["E3", "Fb3"], locations: ["s6f12", "s5f7", "s4f2"]} ,
  { note: ["F3", "E#3"], locations: ["s6f13", "s5f8", "s4f3"]} ,
  { note: ["F#3", "Gb3"], locations: ["s6f14", "s5f9", "s4f4"]} ,
  { note: ["G3", "F##3"], locations: ["s6f15", "s5f10", "s4f5", "s3f0"]} ,
];

function getNoteById(location) {
  let foundLocations = noteLocations.find((e) => e.locations.includes(location));
  if (typeof foundLocations !== "undefined") {
    return foundLocations.note[0];
  } else {
    return "&#216;";
  }
}
console.log("Note: " + getNoteById('s4f4'));


function reusableLookup(search4, objName, param1, param2) {
  let parameterDesc = objName.find((e) => e.param1.includes(search4));
  if (typeof parameterDesc !== "undefined") {
    return parameterDesc.param2[0];
  } else {
    return "&#216;";
  }
}
console.log("Note: " + reusableLookup('s4f4',noteLocations, locations, note));
console.log("Note: " + reusableLookup('s4f4',noteLocations, noteLocations.locations, noteLocations.note));

Obviously, I’m not very clear on the concept, so that’s what I’m trying to learn. There are plenty of similar questions on here, but I didn’t see one that addressed it in a way that I could relate directly to provide the answer.

Issue with Playwright Browser in Electron-Vue3 Build Using Electron-Builder

I’m working on an Electron-Vue3 application that uses Playwright for web scraping. Everything works fine during development, but after I build the installer with electron-builder, the browser stops functioning.

The only solution I’ve found is to explicitly define the browser’s executablePath pointing to a local directory. However, when I try to make the path relative to the app (by including the browser within the app itself), it fails to work after installation.

What I’m looking for:

Is there a way to include the Chrome browser inside the installer/compiled app (like within the /resources directory) and configure Playwright to use that browser from within the installed app?

Addiocional Context:

package.json

{
  "name": "playpix-brayo",
  "version": "1.0.0",
  "description": "playpix",
  "main": "main/main.js",
  "scripts": {
    "dev": "node scripts/dev-server.js",
    "build": "node scripts/build.js && electron-builder --config.extraMetadata.main=main/main.js --config.extraMetadata.buildDependencies.node-abi=108",
    "build:win": "node scripts/build.js && electron-builder --win --config.extraMetadata.main=main/main.js --config.extraMetadata.buildDependencies.node-abi=108",
    "build:mac": "node scripts/build.js && electron-builder --mac",
    "build:linux": "node scripts/build.js && electron-builder --linux"
  },
  "repository": "https://github.com/deluze/electron-vue-template",
  "author": {
    "name": "Brayozin",
    "url": "https://github.com/Brayozin"
  },
  "devDependencies": {
    "@playwright/test": "1.47.1",
    "@types/node": "22.5.0",
    "@vitejs/plugin-vue": "^4.4.1",
    "autoprefixer": "^10.4.20",
    "chalk": "^4.1.2",
    "chokidar": "^3.5.3",
    "daisyui": "^4.12.10",
    "electron": "^27.1.0",
    "electron-builder": "^24.2.1",
    "postcss": "^8.4.45",
    "postcss-loader": "^8.1.1",
    "tailwindcss": "^3.4.11",
    "typescript": "^5.2.2",
    "vite": "^4.5.0"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^6.6.0",
    "@fortawesome/free-brands-svg-icons": "^6.6.0",
    "@fortawesome/free-regular-svg-icons": "^6.6.0",
    "@fortawesome/free-solid-svg-icons": "^6.6.0",
    "@fortawesome/vue-fontawesome": "^3.0.8",
    "axios": "^1.7.7",
    "daisyui": "^4.12.10",
    "playwright": "^1.47.1",
    "playwright-chromium": "^1.47.1",
    "sqlite3": "5.1.6",
    "vite": "^2.9.18",
    "vue": "3.3.8",
    "vue-router": "^4.0.13",
    "vuex": "^4.1.0"
  }
}

build.js

const Path = require('path');
const Chalk = require('chalk');
const FileSystem = require('fs');
const Vite = require('vite');
const compileTs = require('./private/tsc');

function buildRenderer() {
    return Vite.build({
        configFile: Path.join(__dirname, '..', 'vite.config.js'),
        base: './',
        mode: 'production'
    });
}


console.log(Chalk.blueBright('Transpiling renderer & main...'));
console.log(Chalk.blueBright('PATH: ', Path.join(__dirname, '..', 'build')));
function buildMain() {
    const mainPath = Path.join(__dirname, '..', 'src', 'main');
    return compileTs(mainPath);
}


function copyScrapperBrowser() {
  const srcPath = Path.join(
    __dirname,
    "..",
    "src",
    "main",
    "scrapper",
    "browser"
  );
  const destPath = Path.join(
    __dirname,
    "..",
    "dist",
    "scrapper",
    "browser"
  );
  FileSystem.mkdirSync(destPath, { recursive: true });
  FileSystem.cpSync(srcPath, destPath, { recursive: true });
}

function copyMainJs() {
  const srcPath = Path.join(__dirname, "..", "src", "main", "main.js");
  const destPath = Path.join(__dirname, "..", "dist", "main", "main.js");
  FileSystem.mkdirSync(Path.dirname(destPath), { recursive: true });
  FileSystem.copyFileSync(srcPath, destPath);
}


FileSystem.rmSync(Path.join(__dirname, "..", "build"), {
  recursive: true,
  force: true,
});

console.log(Chalk.blueBright("Transpiling renderer & main..."));
console.log(Chalk.blueBright("PATH: ", Path.join(__dirname, "..", "build")));

FileSystem.rmSync(Path.join(__dirname, '..', 'build'), {
    recursive: true,
    force: true,
})

console.log(Chalk.blueBright('Transpiling renderer & main...'));

Promise.allSettled([
    buildRenderer(),
    buildMain(),
]).then(() => {
    copyScrapperBrowser();
        // copyMainJs();

    console.log(Chalk.greenBright('Renderer & main successfully transpiled! (ready to be built with electron-builder)'));
});

ConfigBrowser src/main/scrapper/configBrowser.js

import { chromium } from "playwright";
import { login } from "./login.js";
import fs from "fs";
import path from "path";
const { app } = require("electron");

export async function configBrowser() {
  const contextFilePath = "browserContext.json";
  let context;
  let page;

      const executablePath = path.join(
        appPath,
        "scrapper",
        "browser",
        "chrome",
        "chrome"
      );

  let actualDir = __dirname;
  console.log("executablePath====================================");
  console.log(executablePath);
  console.log("====================================executablePath");
  const browser = await chromium.launch({
    headless: false,
    devtools: true,
    args: [
      "--no-sandbox",
      "--no-devtools",
      "--disable-setuid-sandbox",
      "--mute-audio",
    ],
    executablePath: executablePath,
    // executablePath: "./browser/chrome/chrome", // src/main/scrapper/browser/chrome/chrome
    timeout: 60000, // Increase timeout to 60 seconds
  });

  if (fs.existsSync(contextFilePath)) {
    console.log("oi1");
    const contextData = fs.readFileSync(contextFilePath, "utf8");
    context = await browser.newContext({
      storageState: JSON.parse(contextData),
    });
...

javascript [object HTMLParagraphElement] problem with Pusher

New To Javascript programming i want to real-time chat with Pusher but i got problem in html [object HTMLParagraphElement] and it will display normally after reloading the page.

`
// Configure Pusher
Pusher.logToConsole = true;
var pusher = new Pusher(‘fd21ca0961576845a7dd’, {
cluster: ‘ap1’,
encrypted: true
});

// Replace with actual sender and receiver IDs
var senderId = 1;
var receiverId = 2;

// Subscribe to the private channel for the receiver
var channel = pusher.subscribe(`private-chat-${receiverId}`);
channel.bind('new_message', function (data) {
    var messageHistory = document.getElementById('message-history');
    var message = document.createElement('div');
    message.className = `message ${data.senderId === senderId ? 'sent' : 'received'}`;

    // Create and set message content
    var messageContent = document.createElement('p');
    // Ensure data.message is a string before assigning to textContent
    messageContent.textContent = `${String(data.message)} (Sent at ${data.sentAt})`;

    message.appendChild(messageContent);
    messageHistory.appendChild(message);
    messageHistory.scrollTop = messageHistory.scrollHeight; // Scroll to the bottom
});

// Load message history on page load
document.addEventListener('DOMContentLoaded', function () {
    fetch(`/history/${senderId}/${receiverId}`)
        .then(response => response.json())
        .then(messages => {
            var messageHistory = document.getElementById('message-history');
            messages.forEach(message => {
                var msgDiv = document.createElement('div');
                msgDiv.className = `message ${message.senderId === senderId ? 'sent' : 'received'}`;

                // Create and set message content
                var msgContent = document.createElement('p');
                // Ensure message.messageContent is a string before assigning to textContent
                msgContent.textContent = `${String(message.messageContent)} (Sent at ${new Date(message.sentAt).toLocaleString()})`;

                msgDiv.appendChild(msgContent);
                messageHistory.appendChild(msgDiv);
            });
            messageHistory.scrollTop = messageHistory.scrollHeight; // Scroll to the bottom
        })
        .catch(error => console.error('Error loading message history:', error));
});

// Handle sending messages
document.getElementById('send-button').addEventListener('click', function () {
    var messageContent = document.getElementById('message-input').value;

    fetch('/send', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            senderId: senderId,
            receiverId: receiverId,
            messageContent: messageContent
        })
    })
        .then(response => response.json())
        .then(data => {
            console.log(data);

            // Display the sent message in the chat history immediately
            var messageHistory = document.getElementById('message-history');
            var message = document.createElement('div');
            message.className = 'message sent';

            // Create and set message content
            var messageContent = document.createElement('p');
            // Ensure messageContent is a string before assigning to textContent
            messageContent.textContent = `${String(messageContent)} (Sent at ${new Date().toLocaleString()})`;

            message.appendChild(messageContent);
            messageHistory.appendChild(message);
            messageHistory.scrollTop = messageHistory.scrollHeight; // Scroll to the bottom

            // Clear the input field
            document.getElementById('message-input').value = '';
        })
        .catch(error => console.error('Error:', error));
});

`

I tried using innerHTML but it still doesn’t work

Expo not loading app icon “No icon is defined in the Expo config.”

my app.json

{
  "expo": {
    "name": "myapp-native",
    "slug": "myapp-native",
    "version": "1.0.0",
    "orientation": "portrait",
    "icon": "./assets/icon.png",
    

I ran npx expo prebuild
It outputs a warning like this
» ios: icon: No icon is defined in the Expo config.

I searched the expo discord. Not a single other soul has encountered this warning, apparently. Searching it on quotes on google returns nothing either. I’m at a complete loss. The icon just will not appear in a dev build, ad hoc, or anything.

Am desperate for some help.

React+NextJS server side rendering a page that fetches data and displays it

Currently, I am using client side rendering for a page that fetches data using api and then displays this raw data.

'use client'

import React, { useState, useEffect } from 'react'
import axios from 'axios';

const SolarPanels = () => {
    const [titles, setTitles] = useState([]);

    useEffect(() => {
        axios.get(`/api/panelUpdate?cb=${Date.now()}`, {
            headers: {
                'Cache-Control': 'no-cache',   // Prevents axios from caching
                'Pragma': 'no-cache',
                'Expires': '0'
            }
        })
            .then((response) => { setTitles(response.data.documents[0].productDetails) })
            .catch((error) => { console.error(error.message) });
    }, []);

    return (
        <div>
            <h1>Panels data</h1>
            <p>{titles.map((element) => {
                return <div>{JSON.stringify(element)}</div>
            })}</p>
        </div>
    );
}

export default SolarPanels

I’ve read that its better to perform Client side rendering instead of Server side, so I newant to change this code in order to do that. I’m not planning to make use of hooks other than the one just used.

Also, please tell whether its worth it to convert this to client side rendering?