Simulate Click function with a Delay regardless of tab focus?

I’ve looked everywhere online, but can’t find a straight answer to this specific issue.

Normally, you’d do something like this if you wanted to delay a click:

setTimeout(() => {
    $('.review-more-btn').trigger('click');
}, 1000);

That’ll make the browser simulate a click on that button after the page loads, a second later. Great. Works fine.

However, on a browser like Edge or Chrome, if you navigate off of the page (maybe you opened it as a tab and then went off to do other stuff), setTimeout() goes all manner of whack and doesn’t always work as intended when you return back to it. A well-known JavaScript issue as old as time.

jQuery’s delay() function doesn’t work on non-visual functions, so I can’t do something like the following as it ignores the delay altogether.

$('.review-more-btn').delay(1000).trigger('click');

Is there any possible way to make sure it always fires off properly regardless of page focus? Thanks.

I got errors while connecting to firebase how do i fix it?

If I run my website it doesnt allow me to use my javascript functions.
I get these errors:

Uncaught SyntaxError: Unexpected token 'export' (at firebase-app.js:1577:1)Understand this errorAI
firebase-database.js:1 Uncaught SyntaxError: Cannot use import statement outside a module (at firebase-database.js:1:1)

I use these scripts to get the firebase data

<script src="https://www.gstatic.com/firebasejs/9.1.2/firebase-database.js"></script>

In this case, Can anyone help me?

I Don’t know what to do

Theatre.js + Three.js – Change animation rate

I tried to write a code, the meaning of which is as follows: when the animation is active (we hover the mouse over the object and hold it), we remove the mouse from the object and the animation should play forward a little, gradually slowing down, then smoothly change its direction in the opposite direction.

  1. raycaster.setFromCamera(mouse, camera) determines the intersection with the object
  2. if (intersects.length > 0) InteractiveOn();
  3. InteractiveOnn() { name.sequence.play ({direction: 'normal', rate: 1}) }
  4. Remove the mouse and raycaster.setFromCamera activates InteractiveOff()
  5. InteractiveOff(): smooth change of rate to ~0 > change of animation direction:
    name.sequence.play ({direction: ‘reverse’, rate: 1})

I wrote the following code:

function TM_Func_ChangeRate() {
    let start = performance.now();

    function timing(t) {
        return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
    }

    function TM_Func_GradualChange(time) {
        if (!TM_Fl_RateChange) return; 

        let timeFraction = (time - start) / 100;
        if (timeFraction > 1) timeFraction = 1;

        let progress = TM_Fl_Direction === 'forward'
            ? timing(timeFraction)
            : timing(1.01 - timeFraction);

        TM_SQ_Rate = Math.max(progress, 0.01);

        if (timeFraction < 1) {
            TM_changeRateId = requestAnimationFrame(TM_Func_GradualChange);
        } else {
            TM_Fl_RateChange = false;
            TM_changeRateId = null;
        }
    }

    TM_Fl_RateChange = true; 
    TM_changeRateId = requestAnimationFrame(TM_Func_GradualChange);
}


function TM_InteractiveOn() {
    if (!TM_Fl_isHovered) {
        TM_Fl_isHovered = true;
        
        if (TM_Sequence.position === 0) {
            TM_Fl_playForward = true;
            TM_SQ_Direction = 'normal';
            TM_SQ_Rate = 1;
            start_TM_Animation({
                direction: TM_SQ_Direction,
                rate: TM_SQ_Rate
            });
        } else {
        //    TM_SQ_Direction = 'reverse';
            TM_Fl_RateChange = false;
            cancelAnimationFrame(TM_changeRateId);
            TM_changeRateId = null;
            TM_Fl_Direction = 'back';
            TM_Func_ChangeRate();
            if (TM_stopTimeout) clearTimeout(TM_stopTimeout);
            TM_stopTimeout = setTimeout(() => {
                if (!TM_Fl_playForward) {
                    TM_Fl_playForward = true;
                    
                    TM_SQ_Direction = 'normal';
                    TM_Fl_Direction = 'forward';

                    TM_Fl_RateChange = false;
                    cancelAnimationFrame(TM_changeRateId);
                    TM_changeRateId = null;
                    TM_Func_ChangeRate();

                    start_TM_Animation({TM_SQ_Direction, TM_SQ_Rate});
                }
            }, 100); 
        }

    }
}


function TM_InteractiveOff() {
    if (TM_Fl_isHovered) {
        TM_Fl_isHovered = false;
        
        if (TM_Sequence.position === 1.5) {
            TM_Fl_playForward = false;
            TM_SQ_Direction = 'reverse';
            TM_SQ_Rate = 1;
            start_TM_Animation({
                direction: TM_SQ_Direction,
                rate: TM_SQ_Rate
            });
        } else {
        //    TM_SQ_Direction = 'normal';
            TM_Fl_RateChange = false;
            cancelAnimationFrame(TM_changeRateId);
            TM_changeRateId = null;
            TM_Fl_Direction = 'back';
            TM_Func_ChangeRate();
            if (TM_stopTimeout) clearTimeout(TM_stopTimeout);
            TM_stopTimeout = setTimeout(() => {
                if (!TM_Fl_playForward) {
                    TM_Fl_playForward = false;
                    
                    TM_SQ_Direction = 'reverse';
                    TM_Fl_Direction = 'forward';

                    TM_Fl_RateChange = false;
                    cancelAnimationFrame(TM_changeRateId);
                    TM_changeRateId = null;
                    TM_Func_ChangeRate();

                    start_TM_Animation({TM_SQ_Direction, TM_SQ_Rate});
                }
            }, 100); 
        }

    }
}


function start_TM_Animation({ TM_SQ_Direction, TM_SQ_Rate }) {
    TM_Sequence.play({
        range: [0, 1.5],
        iterationCount: 1,
        direction: TM_SQ_Direction,
        rate: TM_SQ_Rate,
    });
} 

But for some reason the code doesn’t work properly at all: the animation plays forward and freezes. Even if we remove the mouse during the animation, the animation will still continue to its end and freeze 🙁

How to keep the line breaks inside a string in js/html?

For a project of mine, I pass a string to another page for product description.
The thing is that is can’t keep the line breaks when i pass the string with Javascript. Nothing seems to work (
, etc)

Can anyone help me with that ?

I tried every technique on the internet but nothing works.

I just want to pass in JS a string with line breaks to another page via the a anchor.

For example, I pass “hello (line break) everybody”; I finally have “hello everybody” with no break

Displaying filtered web-socket data on html page

Apologies, I’m pretty new to Jquery and websockets but I feel like I’m grasping enough of it where I should be close to getting my simple script to work.

All I’m trying to do is display filtered data on a webpage from a websocket. The filter should only display any data that starts with an “S,”.

I can see that the websocket is connected in Dev tools and that unfiltered data is flowing but nothing is being displayed on the page.


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script>
$(document).ready(function() {
    const socket = new WebSocket('wss://proxy.livemadisonalerts.com/');

    socket.onmessage = function(event) {
        const data = event.data;
        if (data.startsWith('S,')) {
            $('#output').append('<p>' + data + '</p>');
        }
    };
});
</script>

<div id="output">TEST OUTPUT</div>

My example page is: https://livemadisonalerts.com/?page_id=50

React Chrome EXtension : Popup Shows Previous Tab Data Before Updating to Current Tab Data

I am facing an issue while rendering data in a popup based on the currently active tab. Here’s what’s happening:

I have multiple tabs, and each tab contains links.
I am grabbing the data (links) from the active tab and rendering it in a popup.
The data is structured as an array of objects.
The problem occurs when I switch tabs:

If I am on Tab 1 and load the data, the popup works fine and renders the correct data.
However, when I navigate to Tab 2, the popup briefly shows Tab 2’s data, but then Tab 1’s data appears for a moment before correcting itself.
It feels like the data from the previous tab gets rendered for a split second before the new tab’s data is fully updated.

What I’ve Tried:

I ensured the data is updated when the tab changes.
I checked the rendering logic for the popup, but the previous data still appears momentarily.
I am fetching the data dynamically and storing it in an array of objects.

Expected Behavior:

The popup should always render the correct data for the currently active tab without flickering or showing previous tab data.

How to find Package.json version, and use as variable in Github Action

I have a Github action shown below. My build artifact increments with my version in package.json for an Angular application. How do I reference the new version in the willo google drive upload action below?

strategy:
      matrix:
        os: [macos-latest]

    steps:
    - uses: actions/checkout@v4
    - uses: oven-sh/setup-bun@v1
      with:
        bun-version: "latest"

    - name: Install dependencies
      run: bun install

    - name: Install NX
      run: bun i nx -g

    - name: Build MacOS
      if: startsWith(matrix.os, 'macos')
      run: nx run app:build-distro-mac-ci

    - uses: actions/upload-artifact@v4
      if: startsWith(matrix.os, 'macos')
      with:
        name: app-mac
        path: dist/*.dmg
        retention-days: 7

    - uses: willo32/google-drive-upload-action@v1
      if: startsWith(matrix.os, 'macos')
      with:
        target: dist/app-2.0.1.dmg
        credentials: ${{ secret }}
        parent_folder_id: some_id

Problem with the responsiveness of a “heatmap” using bootstrap

the objective with this was to create something like githubs heatmap feature but for our use, but I cant figure out a way to make this work on smaller screens because it looks like it looses parts of the code.

<div class="col-12 col-sm-8 my-auto flex-column" style="overflow-x: auto">
                <div>
                    <div class="d-flex ms-4 me-5 justify-content-around months-label">
                        <small>Jan</small>
                        <small>Feb</small>
                        <small>Mar</small>
                        <small>Apr</small>
                        <small>May</small>
                        <small>Jun</small>
                        <small>Jul</small>
                        <small>Aug</small>
                        <small>Sep</small>
                        <small>Oct</small>
                        <small>Nov</small>
                        <small>Dec</small>
                    </div>
                    <div class="justify-content-end">
                        <div class="heatmap shadow rounded">
                            <script>
                                document.addEventListener("DOMContentLoaded", function() {
                                    const totalDays = 365;  // Number of days in the year
                                    const startPadding = 2;  // Monday = 0, Tuesday = 1, etc.
                                    const weeks = 52; // Number of weeks in the year
                                    const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
                                    
                                    // Select the grid
                                    const heatmap = document.querySelector('.heatmap');
                                    
                                    // Add labels for days of the week
                                    for (let i = 0; i < 7; i++) {  // 7 days of the week
                                        const dayLabel = document.createElement('div');
                                        dayLabel.classList.add('day-label');  
                                        dayLabel.textContent = days[i];
                                        heatmap.appendChild(dayLabel);
                                    }
                                    
                                    // Adicionar células vazias no início (startPadding)
                                    for (let i = 0; i < startPadding; i++) {
                                        const emptyDay = document.createElement('div');
                                        emptyDay.classList.add('day', 'level-0');
                                        heatmap.appendChild(emptyDay);
                                    }
                                    
                                    // Calculate the number of empty cells at the end
                                    const endPadding = (7 - (startPadding + totalDays) % 7) % 7;
                                    
                                    // Generate 365 days with random contributions (levels 1 to 3)
                                    const contributions = [];
                                    for (let i = 0; i < totalDays; i++) {
                                        contributions.push(Math.floor(Math.random() * 3) + 1);
                                    }
                                    
                                    // Fill the grid by weeks (52 weeks)
                                    let dayIndex = 0;
                                    for (let i = 0; i < weeks; i++) {
                                        // For each week, add 7 cells (one for each day of the week)
                                        for (let j = 0; j < 7; j++) {
                                            if (dayIndex < totalDays) {
                                                const level = contributions[dayIndex];
                                                const day = document.createElement('div');
                                                day.classList.add('day', `level-${level}`);
                                                heatmap.appendChild(day);
                                                dayIndex++;
                                            } else {
                                                // If no more contributions, fill with empty cells
                                                const emptyDay = document.createElement('div');
                                                emptyDay.classList.add('day', 'level-0');
                                                heatmap.appendChild(emptyDay);
                                            }
                                        }
                                    }
                                    
                                    // Add empty cells at the end (endPadding)
                                    for (let i = 0; i < endPadding; i++) {
                                        const emptyDay = document.createElement('div');
                                        emptyDay.classList.add('day', 'level-0');
                                        heatmap.appendChild(emptyDay);
                                    }
                                });
                                
                                </script>
                            <!--Add labels for days of the week
                            for (let i = 0; i < 7; i++) {  // 7 days of the week
                            const dayLabel = document.createElement('div');
                            dayLabel.classList.add('day-label');  // Ensure this class is styled appropriately in your CSS
                            dayLabel.textContent = days[i];
                            heatmap.appendChild(dayLabel);
                            }-->
                        </div>
                    </div>
                    <div class=" d-flex justify-content-end">
                        <caption class="labels-legend">Color guide: </caption>
                    </div>
                </div>
#             <div>

So I have this code that generates a small block for each day of the year,

I tried using the overflow-x styling in the above and below divs but it didn´t work

This is what is happening

this is the same code but in a bigger screen

what I wanted to happen is when I go on my phone it should be the same grid but with a scroll feature, it might be a dumb problem with an easy fix but I think i’ve tried everything

Cannot get update of React state variable from callback function to actually change the state to trigger re-rendering

The main problem is that setting a state variable from a callback function does not seem to successfully actually change the state, so re-rendering is not triggered, and when re-rendering happens anyway, the state has not changed as expected.

It works for me as far as that the various callbacks seem to be called when (and only when) the buttons are clicked. Logging indicates that all is ok in that regard.

But when clicking the Cancel button (or the Confirm button) and calling setShowConfirmDialog(prev => false) the dialog is expected to vanish, but it remains.

Adding a useEffect simply in order to log the expected value change indicates that it is never changed. I believe that there is some issue related to closure, or a fundamental misunderstanding of some aspect of the React rendering mechanism, or how I must be accessing a view of the state that is “stale”.

I have tried to specify the involved callback functions in a variety of ways in order to try to understand why it seems like my code refers to a “stale” state variable. To no avail. The code below is my current minimal exexample that illustrates the issue.

I’ve tried with useCallback, I’ve tried setShowConfirmDialog(false), I’ve tried passing the state variable as a prop. It is clear that I have not fully understood what goes on here.

The “parent” is here in page.js

"use client"
import { useEffect, useState } from "react";
import { DeletableRow, EditableCell, ReadOnlyCell, SelectableCell } from "./Components/EditableCell";

export default function Home() {

  const [usersData, setUsersData] = useState([]);

  useEffect(() => {
    const dbrows =
      [
        { id: 11, name: "Dotty", email: "[email protected]" },
        { id: 22, name: "Adam", email: "[email protected]" }
      ];
    setUsersData(dbrows);
  }, []);

  function handleDeleteUserCB(id) { console.log("Placeholder for parent CB: handleDeleteCB: id=", id) };

  let rows = usersData.map((d, i) => {
    let row =
      <DeletableRow id={d.id}
        printName={`${d.id} ${d.name} ${d.email}`}
        type="User"
        key={"users__" + i}
        parentHandleDeleteCB={handleDeleteUserCB}>
        <ReadOnlyCell value={i} />
        <ReadOnlyCell value={d.id} />
        <EditableCell value={d.name} prefix="user__name__" />
        <EditableCell value={d.email} prefix="user__email__" />
        <ReadOnlyCell value={"Read-only text"} prefix="user__email__" />
      </DeletableRow >
    return row;
  });

  console.debug("rowsToShow=", rows);
  return (
    <>
      <h1>User list</h1>
      <table >
        <tbody>
          {rows}
        </tbody>
      </table>
    </>

  );
}

The display:

EditableCell.js

"use client"
import React, { useCallback, useEffect, useRef, useState } from "react";

export function DeletableRow({ printName, id, children, prefix, parentHandleDeleteCB, parentHandleUpdateCB }) {
    const [deleteInitiated, setDeleteInitiated] = useState(false);

    console.log("(Re)Rendering <tr>", { printName, id, children, prefix, parentHandleDeleteCB, parentHandleUpdateCB });
    return (
        <tr key={prefix + id} >
            {/* For convenience, pass some props to all children*/
                React.Children.map(children, (child) => (
                    React.cloneElement(child, { id, parentHandleUpdateCB })
                ))}

            <DeleteButtonCell id={id} printName={printName}
                parentHandleDeleteCB={parentHandleDeleteCB}
            />
        </tr>
    );
}


export function EditableCell({ id, prefix, value, parentHandleUpdateCB }) {
    return (
        <td id={prefix + id} contentEditable={true} style={{ border: "1px solid yellow", padding: "10px" }}
            title={`Click to change ${value} to another value."`}
            suppressContentEditableWarning={true} >
            {value}
        </td>
    )
}

export function ReadOnlyCell({ value }) {
    return (
        <td contentEditable={false} style={{ border: "1px solid grey", padding: "10px" }}
            title="Read only value">
            {value}
        </td>
    )
}


export function DeleteButtonCell({ printName, id, parentHandleDeleteCB }) {
    const [showConfirmDialog, setShowConfirmDialog] = useState(undefined);
    const [itemIdToDelete, setItemIdToDelete] = useState(null);

    const showConfirmDialogRef = useRef(undefined);

    console.log("inline showConfirmDialog=", showConfirmDialog);
    console.log("inline itemIdToDelete=", itemIdToDelete);

    useEffect(() => {
        console.log("useEffect showConfirmDialog=", showConfirmDialog);
        console.log("useEffect itemIdToDelete=", itemIdToDelete);

    }, [showConfirmDialog, itemIdToDelete]);

    const handleDeleteClick = useCallback((itemId) => {
        setItemIdToDelete(itemId);
        setShowConfirmDialog(prev => true);
    }, []);


    const confirmDeleteCB = useCallback((id, parentHandleDeleteCB) => {
        // Call the deletion callback in the parent component
        parentHandleDeleteCB(id);
        console.log("After parent call, which would have deleted id=", id, " Removing dialog.")
        // Deletion complete, remove the dialog.
        setShowConfirmDialog(prev => false)
        console.log("delete complete - dialog should close");

    }, [parentHandleDeleteCB]);

    const cancelDeleteCB = useCallback(() => {
        console.log("setShowConfirmDialog(false)");
        setShowConfirmDialog(prev => false),
            console.log("delete cancelled - dialog should close");
    }, []);

    console.log("Rendering DeleteButtonCell", { showConfirmDialog, printName, id });

    return (
        <td onClick={() => handleDeleteClick(id)}
            title={`Delete ${printName}?`}><button>&nbsp;❌&nbsp;</button>
            {showConfirmDialog && <DeleteConfirmationDialog
                // setShowConfirmDialog={setShowConfirmDialog}
                printName={printName} id={id}
                cancelCB={cancelDeleteCB}
                confirmCB={() => confirmDeleteCB(itemIdToDelete, parentHandleDeleteCB)} />
            }
        </td>)
}


export function DeleteConfirmationDialog({ printName, id, cancelCB, confirmCB, parentHandleDeleteCB }) {
    const onCancel = () => { console.log("onCancel"); cancelCB() };
    const onUserX = () => { console.log("onX"); cancelCB() };
    const onConfirm = () => { console.log("onConfirm"); confirmCB() };

    console.log("Rendering DeleteConfirmationDialog", { printName, id, cancelCB, confirmCB });
    console.log("printName=[", printName, "]");
    return (
        <div >
            <div style={{ border: "4px solid red" }} >
                <div title="Cancel - X" onClick={() => {
                    onUserX();
                }}>X</div>
                <h3 >Confirm Deletion of {printName} </h3>
                <p>Are you sure you want to delete <br /><strong>{printName}</strong>?</p>
                <button title="Confirm" onClick={onConfirm}>Confirm</button>
                <button title="Cancel" onClick={onCancel}>Cancel</button>
            </div>
        </div>

    )
}

access lit-element variable from cypress

Is there a way to access Lit-Element / web-component variables in Cypress? For instance, if I have a lit-element component that has a non-public property like so:

constructor() {
  super();
  this.field = {};
}

and after doing some stuff with Cypress, access the value of this.field.

Right now, I’m making the variable a public property like this:

static get properties() {
  return {
    field: {
      type: Object,
      reflect: true,

    }
  };
}

and then accessing the value via cypress invoke:

    cy.get('layout-container').invoke('attr', 'field')
      .then((fieldtxt) => {
        let fieldobj = JSON.parse(fieldtxt);

This works fine, but if I made every variable I wanted to test into a public property, it starts to get messy. If possible, it would be cleaner if there was a way to access the variable as a private member.

@state() protected field:Field;

In general I’m finding that cypress works really well when doing interactions, but am needing to access the component internals (access variables, or run a function directly) to get better testing coverage.

What is the solution? Payment error: Failed to communicate with MPGS server with wordpress

i Use WordPress and the MasterCard Payment Gateway Services (MPGS) plugin and This problem appears on the payment page, and I modified the link from the plugin settings and removed the slash mark

https://banquemisr.gateway.mastercard.com/

but the problem was not solved. Are there other solutions?

Payment error: Failed to communicate with MPGS server. Make sure MPGS URL looks like `https://example.mastercard.com/` by removing `checkout/version/*/checkout.js` and end the URL with a slash "/".

Why am I receiving a 401 Unauthorized error in Axios even though the JWT token is set as an HttpOnly cookie and included in the request? [closed]

Creating a Real-Time Chat Application through MERN.
Aditionally with
“bcryptjs”: “^2.4.3”,
“cloudinary”: “^2.5.1”,
“cookie-parser”: “^1.4.7”,
“cors”: “^2.8.5”,
“dotenv”: “^16.4.5”,
“express”: “^4.21.1”,
“jsonwebtoken”: “^9.0.2”,
“mongoose”: “^8.8.2”,
“socket.io”: “^4.8.1”

I am developing a real-time chat application named Wave Chat using the MERN stack. The backend sends a JWT token as an HttpOnly cookie after a successful login, and I use this token for authentication in subsequent requests. However, when I try to make an authenticated request using Axios, I receive a 401 Unauthorized error.

[Project Setup:]
Backend (Node.js, Express, and JWT):

Upon successful login, the server generates a JWT token and sends it as an HttpOnly cookie.
A middleware function validates the token from the cookies for protected routes.
Sample Backend Code (JWT Middleware):

javascript

const jwt = require('jsonwebtoken');

const authenticateToken = (req, res, next) => {
  const token = req.cookies.jwt; // Read the token from cookies
  if (!token) {
    return res.status(401).json({ message: 'Token not found' });
  }

  try {
    const decoded = jwt.verify(token, 'your_secret_key');
    req.user = decoded; // Attach user info to the request
    next();
  } catch (err) {
    return res.status(401).json({ message: 'Unauthorized - Invalid token' });
  }
};

app.get('/api/checkAuth', authenticateToken, (req, res) => {
  res.json({ message: 'User authorized', user: req.user });
});

CORS Configuration:

javascript

const cors = require('cors');

app.use(cors({
  origin: 'http://localhost:5173', // React frontend
  credentials: true // Allow cookies in cross-origin requests
}));
Frontend (React with Axios):
I am using Axios with withCredentials: true to ensure the cookie is sent with the request:

javascript
Copy code
import axios from 'axios';

const checkAuth = async () => {
  try {
    const response = await axios.get('http://localhost:5000/api/checkAuth', {
      withCredentials: true // Sends cookies along with the request
    });
    console.log('User authorized:', response.data);
  } catch (error) {
    console.error('Error in checkAuth:', error.response?.data || error.message);
  }
};

checkAuth();

Browser Debugging:

I confirmed that the JWT cookie (jwt) is correctly set in the browser under Application > Cookies.
The cookie is marked as HttpOnly and is visible in the network request headers.
I have verified that the Axios request includes the cookie by inspecting the Network tab in DevTools.
[What I Tried:
I verified that:
withCredentials: true is enabled in the Axios request.
The backend CORS configuration includes credentials: true and specifies the correct origin (http://localhost:5173).
I checked the browser’s Cookies to confirm the JWT is being sent with the request.
I ensured the JWT secret used in jwt.verify matches the one used during token creation.
I inspected the Network tab to confirm that cookies are attached to the request headers.]

For more reference i am posting git for this project:
(https://github.com/HimanshuJangid2147/Wave-Chat-2_err.git)

I expected the backend to validate the JWT token sent in the cookies, authenticate the user successfully, and return a 200 OK response with a success message.

This error i got in console
Its confirm that my browser is not getting cookie from backend

SolidJS Router doesn’t render page – Navigation doesn’t work

On navigation, even though the path of a Route is added to the url in the search bar, the component of the Route is not rendered. It only renders on refreshing the page.

My Header has buttons which are used for navigating to the different URLs (using useNavigate hook). When I click on each button, the path is added to the URL in the search bar but the previous component remains on the page and the new component is not shown.

Example, when I’m on ‘/,’ ‘Hi’ is displayed but when I navigate to ‘/mybooks,’ Books is not displayed and ‘Hi’ is still on the screen. I have to reload the page to get Books to display.

App.jsx :

function App() {
  return (
    <div class={styles.App}>
      <Header styles={styles} />
      <main>
        <Router>
          <Route path="/" component={() => <p>Hi!</p>} />
          <Route path="/mybooks" component={Books} />
          <Route path="/add" component={Add} />
        </Router>
      </main>
    </div>
  );
}

I have also wrapped App with a Router in index.jsx :

render(() => (
  <Router root={App} />
), root);

I have tried removing the inner Router thinking that was causing the problem, but when I do that, nothing is rendered (none of the three components supposed to be rendered are displayed) and I also get a warning (Unrecognized value. Skipped inserting.)

I want to know why the component is not being rendered without refreshing the page. How do I solve this and get each page to render as soon as I navigate to the path defined in the Route tag for each component?

Next.js App on AWS EC2 (Ubuntu) – Images, GIFs, and CSS Not Loading After Deployment

I’m currently facing an issue while deploying a Next.js application on an AWS EC2 instance running Ubuntu. The application runs fine, and the main logic is working as expected. However, images (JPG, PNG, GIF) and styles (CSS) are not loading properly. Instead, I see broken images and unstyled content on the deployed site.

enter image description here

Deployment Steps:

Launched an EC2 instance (Ubuntu 22.04).
Installed Node.js, NPM, and PM2 to run the Next.js server.
Cloned the project repository from GitHub.
Ran npm install to install dependencies.

Built the app using npm run build.

Started the server using npx next start or pm2 start npm --name "next-app" -- run start.

Checked File Permissions:

Verified that the image and CSS files exist in the .next/static folder.
Used chmod -R 755 .next/ to ensure files have read permissions.
Checked NGINX (if applicable):

Configured an NGINX reverse proxy.
Ensured location /_next/static/ is pointing to the correct path.

Environment Variables:

Double-checked the environment variables used in the next.config.js, especially assetPrefix and basePath.

Current Behavior:

Images and GIFs are broken (not loaded) in the browser.
CSS styles are not being applied, and the site appears unstyled.

What I’ve Tried to Debug:

Network Requests:
Checked network requests in the browser dev tools. The request URLs for images and styles are returning 404 errors.

Next.js Config:
Verified that next.config.js does not have any misconfigurations related to basePath or assetPrefix.

Build Verification:
Verified that the .next/static folder contains the expected images, styles, and JavaScript files.

Logs:
No errors are appearing in the server logs.

Questions:
Are there any specific settings for AWS EC2 (like file permissions) that could be blocking access to .next/static files?

Should I explicitly configure assetPrefix in next.config.js when using an EC2 instance?

How do I ensure that the files in .next/static/ are served correctly?

Environment Details:

Node.js version: v18.x
Next.js version: 13.x
OS: Ubuntu 22.04
Server: AWS EC2 (Ubuntu) with NGINX (if relevant)

Any help would be greatly appreciated!