How does middleware work in NextJS if you cannot export it

As I am trying to implement a system where users will not be able to access admin routes unless they are authenticated, to do this you need a middleware. But the problem is I am using nginx on my website, and you cannot use middleware on this, as it says:

error Middleware cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html

I am so confused on how this all works. How will you be able to use a middleware? Are there ways to not give users access to routes eg: [website]/admin/items/list unless they are authenticated?

Cookies and Sessions setting and getting issue

I hope that all is well…

I am facing an issue where I am setting cookies and session values at login on the backend, which is node js. However, when react calls the API that verifies the cookies or sessions values, the values returns undefined… I know my middleware is fine because I can log data automatically to the DB, which is MySQL. I have tried switching req.session.isAdmin, req.session.loggedIn, and req.session.username to req.cookies.isAdmin, req.cookies.loggedIn, and req.cookies.username but that did not work. The code is below, any advice will truly help. Please note I am trying to configure cookie the best way possible as I am new to setting cookies, any lessons are welcomed!

Index.js

require('dotenv').config();
const host = process.env.HOST;
const port = process.env.PORT;
const express = require('express');
const app = express();
const cors = require('cors');
const session = require('express-session');
const SqlDbStore = require('express-mysql-session')(session); // Import SqlDbStore
const cookieParser = require('cookie-parser');

app.use(cors());
app.use(express.json());

app.use(cookieParser());
app.use(
  session({
    key: 'BibleTriviaSessionCookies',
    secret: '3B4F7C4E6DA85A5176758B437A22A',
    store: new SqlDbStore({
      host: process.env.DB_Host,
      port: process.env.DB_Port,
      user: process.env.DB_User,
      password: process.env.DB_Pass,
      database: process.env.DB_Data,
    }),
    resave: false,
    saveUninitialized: false,
    cookie: {
      maxAge: 1000 * 60 * 60 * 24,
      secure: true,
    },
  })
);

app.get('/', (req, res) => {
  res.send("The server is running successfully. <br/>The server is running on port " + port + "... <br/>The server url is " + host + ":" + port + "...")
});

const userRoute = require('./routes/User');
app.use('/user', userRoute);

const adminRoute = require('./routes/Admin');
app.use('/admin', adminRoute);

const triviaRoute = require('./routes/Trivia');
app.use('/trivia', triviaRoute);

app.listen(port, (req, res) => (
  console.log("Server running on port " + port + "...")
));

Login and CheckLogin Routes from User.Js

//Login Page
router.post('/login', async (req, res) => {
  const username = req.body.username;
  const password = req.body.password;

  try {
    const userVerification = await db.query('SELECT * FROM userverification WHERE accountUsername = ?', [username]);
    const userLogin = await db.query('SELECT * FROM users WHERE accountUsername = ?', [username]);
    const adminVerification = await db.query('SELECT * FROM adminusersverification WHERE accountUsername = ?', [username]);
    const adminLogin = await db.query('SELECT * FROM adminusers WHERE accountUsername = ?', [username]);

    // Check User Verification
    if (typeof userVerification[0][0] !== 'undefined') {
      sg.sendVerification(userVerification[0][0].accountEmail, userVerification[0][0].accountFirstName, userVerification[0][0].accountLastName, username);
      res.json({ message: 'User needs to check email to verify account' });
    }
    // Check User Table
    else if (typeof userLogin[0][0] !== 'undefined') {
      const result = await new Promise((resolve, reject) => {
        bcrypt.compare(password, userLogin[0][0].accountPassword, (err, result) => {
          if (err){
            reject(err);
          }
          else {
            resolve(result);
          }
        });
      });

      if (result === true) {
        req.session.username = username;
        req.session.loggedIn = true;
        req.session.isAdmin = false;
        res.cookie('username', username);
        res.cookie('loggedIn', true);
        res.cookie('isAdmin', false);
        res.setHeader('Set-Cookie-Instructions', 'loggedIn=true; username=username; isAdmin=false');
        return res.json({ loggedIn: true, username: username });
      }
      else {
        return res.json({ loggedIn: false, message: 'Account Does Not Exist or Password Is Incorrect!' });
      }
    }
    // Check Admin Verification
    else if (typeof adminVerification[0][0] !== 'undefined') {
      sg.sendAdminVerification(adminVerification[0][0].accountEmail, adminVerification[0][0].accountFirstName, adminVerification[0][0].accountLastName, username);
      res.json({ message: 'User needs to check email to verify account' });
    }
    // Check Admin Table
    else if (typeof adminLogin[0][0] !== 'undefined') {
      const result = await new Promise((resolve, reject) => {
        bcrypt.compare(password, adminLogin[0][0].accountPassword, (err, result) => {
          if (err){
            reject(err);
          }
          else {
            resolve(result);
          }
        });
      });

      if (result === true) {
        req.session.username = username;
        req.session.loggedIn = true;
        req.session.isAdmin = true;
        res.cookie('username', username);
        res.cookie('loggedIn', true);
        res.cookie('isAdmin', true);
        res.setHeader('Set-Cookie-Instructions', 'loggedIn=true; username=username; isAdmin=true');
        return res.json({ loggedIn: true, username: username, isAdmin: true });
      }
      else {
        return res.json({ loggedIn: false, message: 'Account Does Not Exist or Password Is Incorrect!' });
      }
    } else {
      return res.json({ loggedIn: false, message: 'Account Does Not Exist or Password Is Incorrect!' });
    }
  } catch (err) {
    console.log(err);
    return res.json({ message: 'An Error Occured!' });
  }
});
router.post('/checkLogin', (req, res) => {
  const expectedIsAdmin = req.session.isAdmin; // Get isAdmin from the server's session
  const expectedLoggedIn = req.session.loggedIn; // Get loggedIn from the server's session
  const expectedUsername = req.session.username; // Get username from the server's session

  const receivedIsAdmin = req.body.isAdmin;
  const receivedLoggedIn = req.body.loggedIn;
  const receivedUsername = req.body.username;

  console.log(receivedIsAdmin + ' <-> ' + expectedIsAdmin)
  console.log(receivedLoggedIn + ' <-> ' + expectedLoggedIn)
  console.log(receivedUsername + ' <-> ' + expectedUsername)

  if (receivedIsAdmin === null || receivedLoggedIn === null || receivedUsername === null) {
    //User not logged in...
    console.log("User not logged in...")
    return res.json({forceLogout: false, verified: false})
  }
  else if (receivedIsAdmin === expectedIsAdmin && receivedLoggedIn === expectedLoggedIn && receivedUsername === expectedUsername) {
    // Cookies match the server's session values
    //User verification passed...
    console.log("User verification passed...")
    return res.json({ forceLogout: false, verified: true });
  } else {
    // Cookies do not match the server's session values
    //User verificaton failed...
    console.log("User verificaton failed...")
    return res.json({ forceLogout: true, verified: false });
  }
});

Puppetteer autoscroll works on windows, but not on linux

i am using puppetteer and i have a autoscroll like this

export const autoScroll = async (page, durationInSeconds) => {
  const totalHeight = await page.evaluate(() => {
    return document.body.scrollHeight - window.innerHeight
  })

  let totalScrolled = 0
  const scrollStep = totalHeight / (durationInSeconds * 60)
  const timeInterval = (durationInSeconds * 1000) / (totalHeight / scrollStep) // Time in milliseconds

  return new Promise((resolve, reject) => {
    const scrollInterval = setInterval(async () => {
      // Scroll by the step.
      await page.mouse.wheel({ deltaY: scrollStep })
      totalScrolled += scrollStep

      if (totalScrolled >= totalHeight) {
        clearInterval(scrollInterval)
        resolve()
      }
    }, timeInterval)
  })

The problem is that this gives the expected output on windows so the scrolling takes the amount that is provided in the parameters but on linux it does the autoscroll 4-5 seconds too fast so it just stays at the bottom the rest 4-5 seconds, what could be the reason?

How to get rid of double-logging in Vite?

I’m using Vite with pnpm to build a React 18 app. For some reason the logs I’m seeing in the browser console are doubled. First it’s coming from the filename that is correct, the second is coming from localhost:port. I want to get rid of the localhost logs.

log list

redirect vue page us

im still learning js,vue,node and i stumble into this problem
i wanted to redirect vue page after i login using nodejs
this is my vue and the script

<form>
     <div class="mb-3">
          <label for="usernameEmailMobile">Username/Email/Mobile</label>
          <input type="text" class="form-control" id="usernameEmailMobile" 
          placeholder="Enter username, email, or mobile number" required
          v-model="stateLogin.newInput" >
     </div>
     <div class="mb-3">
          <label for="password">Password</label>
          <input type="password" class="form-control" id="password" 
          placeholder="Enter password" required
          v-model="stateLogin.passwordInput">
     </div>
     <button @click="login()" type="submit" class="btn btn-success ">Login</button>
</form>

<script>

import loginCRUD from '../modules/loginCRUD.js'

export default {
    name:"loginView",
    setup(){
        const {stateLogin, login} = loginCRUD()
        return {stateLogin, login}
    }
}
</script>

this is my module

import {reactive} from 'vue'

const doLogin =() =>{

    const stateLogin = reactive({
        newInput: '',
        passwordInput: ''
    })


    const login = () =>{
        const request = {
            method : "POST",
            headers: {
                "Content-Type" : "application/json"
                //authtoken bisa disini
            },
            body: JSON.stringify({
                input: stateLogin.newInput ,
                password: stateLogin.passwordInput ,
            })
        }
        fetch("http://localhost:3000/user/login",
        request
        )
    }

    return {
        stateLogin,
        login
    }
}

export default doLogin

and this is my backend node

router.post('/login', async (req,res) =>{
    const tempUser = req.body.input;
    const password = req.body.password;
    
    // const user = await User.findOne({
    //     $or:
    //         [
    //             {username : tempUser},
    //             {mobilePhone : tempUser},
    //             {email : tempUser}
    //         ]
    // })
    const user = await User.findOne({username : tempUser })
    const worker = await Worker.findOne({username : tempUser })
    if(user != null){
        if(password == user.password){
           return res.redirect(301,`/home`)
        }else{
            
        }
    }else{

    }
    //const match = await bcrypt.cmopare(req.body.password, user.password)
})

i was able to get the data to my backend in node. it got to the point

if(password == user.password){
     return res.redirect(301,`/home`)
}

so if i put the correct password and match it to the password at the database it got to the inside if but it doesnt return and redirect to my home page view at vue

am i missing something?
thank you

Using Intersection Observer for animations

im a rookie so maybe this is a dumb question, sorry in advance.

I want to create a website in angular and i want the content to be animated as it scrolls into the viewport. The ‘solution’ i found was intersection observer but unfortunately i cant get it to work. it seems like it just doesnt trigger as the elements scroll into the viewport.

I had some in depth discussions with chatGPT which werent helpful and i tried to google it but i only found solutions that work in plain js not in angular.

this is my typescript code:

import { Component, ElementRef, OnInit, QueryList, ViewChildren } from '@angular/core';

@Component({
  selector: 'app-project-component',
  templateUrl: './project-component.component.html',
  styleUrls: ['./project-component.component.scss']
})
export class ProjectComponentComponent implements OnInit {
  projects = [project1, project2, project3, project4];
  @ViewChildren('hidden') myElements!: QueryList<ElementRef>;

  ngOnInit () {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        console.log(entry);
      });
    });

    this.myElements.forEach((el) => observer.observe(el.nativeElement));
  }
}

the projects array of course contains 4 json objects but i didnt want to bother you with more unnessecary details.
i put the console log for debug reason, at this position i would write something like entry.target.classList.add('show'); to animate the content.

and here follows my html code:

<div class="project" *ngFor="let item of projects; let i = index" [ngClass]="{ 'odd': i % 2 == 1 }">
    <div class="img hidden">
        <img src="{{projects[i].img}}">
    </div>
    <div class="info hidden">
        <h1>{{projects[i].name}}</h1>
        <h3>{{projects[i].language}}</h3>
        <p>{{projects[i].description}}</p>
        <div class="links">
            <a href="{{projects[i].github}}" target="_blank">
                <button> Github </button>
            </a>
            <a href="{{projects[i].ftp}}" target="_blank">
                <button> Live test </button>
            </a>
        </div>
    </div>
</div>

If you have different suggestions for more effective ‘on-scroll-animations’ please let me know

Thanks for your time and help.

HTMLDialogElement gets focus on initial click on Chromium

After opening the HTMLDialogElement the first click inside of it also focuses the dialog element on Chromium. Basically each first click within the dialog fires the focus event.
Thant is not the case on Firefox.

In my current use case, the focus trap causes problems for me but everything is fine on FF.

Is this an intentional behavior of Chromium?
Why is there a difference?

CHROMIUM BEHAVIOR:

  • step 1: press show()
  • step 2: click within dialog -> focus event fired
  • step 3: click outside dialog and click within dialog again -> focus event fired
  • setp 4: close()
  • step 5: showModal()
  • step 6: click anywhere -> focus event fired

FIREFOX BEHAVIOR:

    • no focus events fired ever

Stackblitz:

https://stackblitz.com/edit/typescript-s7ajm9?file=index.html,index.ts

I will create a workaround for my current use case and post it here as a solution but the question is if there is a reason to have a different behavior?

How to customize button styles for PayPal

I want to customize a PayPal payment style. I modify the style by obtaining the elements in the button. After successful modification, the button will automatically refresh the style and the style is gone

I would like to modify its width, height, size, and button background color to remove the PayPal icon for payment

javascript error: cannot read properties of null (reading ‘window’)

I am using javascript in my aspx page. code below:-

    function Refresh()
    {
       var url=opener.window.location.href;
       opener.window.RefreshTabContent();
    }

I am opening a new tab from a link, this code I have written in a new tab, that is opened opener.window.RefreshTabContent();
refreshes the previous tab, while

var url=opener.window.location.href; assigns the URL to the previous tab.

In the above code I am getting error: cannot read properties of null (reading ‘window’)
Please help where I am making error.
Thanks

Unable to display items from Local Storage

I’m creating a shopping cart ,in which I am having a problem that I am unable to get the items from local storage and display it on my page ,I’m new to web development so it’s so confusing can you guy’s take a look at my code and tell me what am I doing wrong here.

Here’s my JavaScript

let shopItemsData = [
  {
    id: "jfhgbvnscs",
    name: "Casual Shirt",
    price: 45,
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing.",
    img: "images/img-1.jpg",
  },
  {
    id: "ioytrhndcv",
    name: "Office Shirt",
    price: 100,
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing.",
    img: "images/img-2.jpg",
  },
  {
    id: "wuefbncxbsn",
    name: "T Shirt",
    price: 25,
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing.",
    img: "images/img-3.jpg",
  },
  {
    id: "thyfhcbcv",
    name: "Mens Suit",
    price: 300,
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing.",
    img: "images/img-4.jpg",
  },
];

// everytime u slecetd cart its gona store the data in the basket

let basket = JSON.parse(localStorage.getItem("data")) || [];

const productsContainer = document.querySelector(".products");

function displayProducts(data) {
  productsContainer.innerHTML = data
    .map((item) => {
      let { id, name, price, desc, img } = item;
      let search = basket.find((x) => x.id === id || []);

      return `
    <div id=product-id-${id} class="product">
            <img src=${img} alt="">
            <div class="details">

                <h3>${name}</h3>
                <span>${desc}</span>
                <div class="price">
                    <h3>${"$ " + price}</h3>
                    <div class="buttons">
                        <i onclick="decrement(${id})" class="ri-subtract-fill"></i>
                        <span id=${id} class="quantity" >${
        search.item === undefined ? 0 : search.item
      }</span>
                        <i onclick="increment(${id})"  class="ri-add-line"></i>
                    </div>
                </div>
            </div>
        </div>
    
    `;
    })
    .join("");
}

displayProducts(shopItemsData);

/**
 * first search in basket that if the item exist or not if not push the item in basket and if yes increase the basket's item quantity
 **/

let increment = (id) => {
  let selectedItem = id;

  let search = basket.find((x) => x.id === selectedItem.id);

  if (search === undefined) {
    basket.push({
      id: selectedItem.id,
      item: 1,
    });
  } else {
    search.item += 1;
  }

  //   console.log(basket);
  localStorage.setItem("data", JSON.stringify(basket));

  upgrade(selectedItem.id);
};

let decrement = (id) => {
  let selectedItem = id;

  let search = basket.find((x) => x.id === selectedItem.id);

  if (search === undefined) return;
  else if (search.item === 0) return;
  else {
    search.item -= 1;
  }

  //   console.log(basket);
  localStorage.setItem("data", JSON.stringify(basket));
  upgrade(selectedItem.id);
};

let upgrade = (id) => {
  let search = basket.find((x) => x.id === id);
  //   console.log(search.item);
  document.getElementById(id).innerHTML = search.item;
  calculation();
};

let calculation = () => {
  let cartIcon = document.getElementById("cartAmount");
  cartIcon.innerHTML = basket.map((x) => x.item).reduce((x, y) => x + y, 0);
};

// Saving data in local storage

I tried other resources and videos to get help but I am unable to solve this problem.
Thanks in advance

Jest Manual Mock Not Working with Manual Implementation

I am testing some of my code using Jest. When I try to mock a function (autogenerated by pgtyped), the test fails, saying the function returns undefined. My original function is in: src/db/models/calls.ts, and my mocked function is in src/db/models/__mocks__/calls.ts.

To try to better understand the issue I am facing, I am trying to get the mocked function to simply console.log the parameters it receives. Below is the mocked function:

export const getCallBySid = {
    run: jest.fn().mockImplementation((params: { sid: string }) => {
        console.log("getCallBySid params", params);
    }),
};

What makes this even more confusing is, when I replace jest.fn().mockImplementation with a direct implementation in the mock file, the console.log works. Below is the code that is able to console.log

export const getCallBySid = {
    run: (params: { sid: string }) => {
        console.log("getCallBySid", params);
    },
};

I can’t tell why this would work, whereas the jest mock would not. I want to be able to get information on calls to the function, so it would be very helpful to be able to have it be a jest.fn in the mock.

How to create a typescript enum from an array?

I have a list of currencies supported

export const CURRENCIES = ['EUR', 'CHF', 'GBP', 'USD', 'DKK'];

This is defined in a npm library.

I have a TS project where I am using currency code for a currency related component. This is the current implementation.

export Interface InputProps extends React.InputHTMLAttributes<HTMLInputElement>{
currency?: 'USD' | 'EUR' | 'GBP'; // current implementation
}

const CurrencyInput = ({ currency = 'EUR'}:InputProps) => {
....
}

However, with the current implementation, the currency prop is restricted only to ‘USD’, ‘EUR’, and ‘GBP’. I want to make the currency prop dynamic, so it can accept any currency code from the CURRENCIES array. I prefer to keep the supported currencies in the npm library, so that if I have to update the supported currency in future, i only need to update in one place because this currency constant is being used in multiple places.

Intellisense not working in Visual Studio code

Intellisense not providing suggestions in Visual Studio code

I am facing an issue with Visual Studio code where the intellisense feature is not working.The suggestions that I need while coding are not displayed,which is causing unnecessary time wastage.
I have checked language extension for programming language I am using is installed and up to date.
I have restarted Visual Studio code multiple times to see if the issues resolve itself,but it persist.

I am expecting intellisense to provide relevant suggestions and autocompletion as I type, help me to write code more efficiently.
Could anybody help me to find out the solution for it?

srcSet in Image component is not working and it is not displaying right image in next js

here is my code of next js

import React from "react";
import style from "@/styles/Home.module.css";
import Image from "next/image";

function index() {
  return (
    <>
      <div className="container">
        <div style={{ textAlign: "center" }}>
          <Image
            src="/image/banner900x400.jpg"
            alt="Govind Hand Print Banner"
            fill={true}
            className={style.img}
            srcSet="/image/banner900x400.jpg 900w, /image/bedsheet.png 522w"
          />
        </div>
      </div>
    </>
  );
}

export default index;

css

.img {
  object-fit: contain;
  width: 80% !important;
  position: relative !important;
  height: unset !important;
  border-radius: 10px;
}

@media screen and (max-width: 1170px) {
  .img {
    margin-top: 40px;
    width: 90% !important;
  }
}

in output i only get banner900x400.jpg on all screen sizes. in vs code this is giving error like this ” Property ‘srcSet’ does not exist on type ‘IntrinsicAttributes & Omit<DetailedHTMLProps<ImgHTMLAttributes ”
i try srcset and srcSet none of these working. try to find answer on web but cant find anything