SameSite=None is not set

The firefox tells me that I need to put the value “None” in the somesite attribute, but when I set it, the browser still thinks that Lax is used there, instead of None

enter image description here

Code:

app.use(
  cors({
    origin: "https://59e5-185-9-186-241.ngrok-free.app",
    methods: ["GET", "POST"],
    allowedHeaders: ["Content-Type", "Authorization"],
    credentials: true,
  }),
);


app.post("/api/auth/telegram", (req, res) => {
  const userData = req.body;

  // Проверяем подпись
  if (!validateTelegramAuth(userData)) {
    console.log("Неверная подпись Telegram");
    return res.status(403).json({ message: "Неверная подпись Telegram" });
  }

  // Генерируем JWT токен
  const token = generateAuthToken(userData);

  res.cookie('authToken', token, {
    httpOnly: true,
    secure: true,
    sameSite: 'None',
    partitioned: true,
    maxAge: 7 * 24 * 60 * 60 * 1000,
});

res.cookie('user', userData, {
    httpOnly: true,
    secure: true,
    sameSite: 'None',
    partitioned: true,
    maxAge: 7 * 24 * 60 * 60 * 1000,
});

  
  

  console.log("Токен сгенерирован и отправлен:", token);
  return res.json({ token });
});

I rebooted the server, accessed chatGPT, looked for solutions and similar cases on the Internet

try catch in then still gives uncaught error [closed]

I’m fetching data from an API. I would like to handle both cases, when the response is valid JSON and when it is not.

return fetch( ... )
    .then(response => {
        let res
        try {
            res = response.json()
        } catch (e) {
            res = response.blob()
        }
        return res
    })

I thought this should work, but it doesn’t. It throws

Uncaught (in promise) SyntaxError: Unexpected token 'N', " ... "... is not valid JSON

What am I doing wrong?

How to run external javascript op page resize

My site contains a page with an external script to generate a form.
When the page is resized the form disappears and the page has to be reloaded to rerun the external script. How can the external script be executed on a page resize?

I tried several options.

Debugging ‘Objects are not valid as a React child’

I work in a very large monorepo, lots of changes, lots of developers. A couple days ago it totally broke, only in prod, with the error:

Error: Objects are not valid as a React child (found: object with keys {$$typeof, type, key, props, _owner, _store}). If you meant to render a collection of children, use an array instead.

Oddly reverting to previous versions is not addressing the issue at all. This comes up frequently enough on StackOverflow, and I think I know the basic cause. What I’m looking for is a way to get a more descriptive error message to help pinpoint where the failure is. As it stands the full message doesn’t get out of node_modules:

2:50:14 PM [vike][request(1)] Following error was thrown by the onRenderHtml() hook defined at /src/renderer/+onRenderHtml.tsx
server-1  | Error: Objects are not valid as a React child (found: object with keys {$$typeof, type, key, props, _owner, _store}). If you meant to render a collection of children, use an array instead.
server-1  |     at renderNodeDestructiveImpl (/usr/src//apps/marketing/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:6194:11)
server-1  |     at renderNodeDestructive (/usr/src//apps/marketing/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:6091:14)
server-1  |     at renderIndeterminateComponent (/usr/src//apps/marketing/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:5790:7)
server-1  |     at renderElement (/usr/src//apps/marketing/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:5961:7)
server-1  |     at renderNodeDestructiveImpl (/usr/src//apps/marketing/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:6119:11)
server-1  |     at renderNodeDestructive (/usr/src//apps/marketing/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:6091:14)
server-1  |     at renderContextProvider (/usr/src//apps/marketing/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:5935:3)
server-1  |     at renderElement (/usr/src//apps/marketing/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:6032:11)
server-1  |     at renderNodeDestructiveImpl (/usr/src//apps/marketing/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:6119:11)
server-1  |     at renderNodeDestructive (/usr/src//apps/marketing/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:6091:14)

Set Results Per Page For Google Node.js Youtube API v3 playlists.list() Method

I’m using the Google YouTube Api (v3) to fetch the video IDs for a YouTube Playlist. My code is working well enough, but I’d really like to set the “resultsPerPage” variable to a higher number. It is set to 5 by default. I’m using it for album tracks so most of the playlists that I’m working with are between 8 and 15 videos. It would be nice to get all of their info in one call.

When I execute the same request from the Google API Explorer there is no such limitation; it returns all of the videos in one response.

I tried setting the “resultsPerPage” option Node.js code that fetches the data, but that had no effect:

  const youtube_v3 = require('@googleapis/youtube').youtube_v3;
  const youtube = new youtube_v3.Youtube();

  const requestOptions = {
    key: process.env.YOUTUBE_API_KEY,
    part: 'snippet,contentDetails',
    fields: 'items(snippet/title,contentDetails/videoId),pageInfo,nextPageToken',
    playlistId: playlistId,
    maxResult: maxResults,
    resultsPerPage: 10 // this does nothing!
  };

  if ( pageToken ) {
    requestOptions.pageToken = pageToken;
  }

  const results = await youtube.playlistItems.list( requestOptions );
  const data = results.data;

I found some info in the Docs about a PageInfo class. It has a method named set_results_per_page() which seems promising. However, I have no idea how to access that class.

Has anyone managed to change the number of results per page using the API?

shadcn chart has no space between label and value

The issue I’m facing can be seen on the image, essentially some bigger values don’t have any padding in between value and label, I’d like to know how I can make it at least 2px

Image:

enter image description here

Part of code:

    <ChartTooltip
      cursor={false}
      content={
        <ChartTooltipContent
          labelFormatter={(value) => {
            return new Date(value).toLocaleDateString("en-US", {
              month: "short",
              day: "numeric",
            });
          }}
          indicator="line"
        />
      }
    />

Select group Elements with Sortable.js

I would like to know if there’s the possibility to select all elements with same class only with one click in one of them, or double click. Trying not to check all of them one in one.

Thx for all

I found the class assigned when you select one, and i’ve tried to assign to other elements on loops, but making this, you only drag the item you pressed on. I think there’s an event that makes something more when you click on the element, but i don’t find what it

Apexcharts plot point does not coincide with the xaxis label ticks. Tick is places slightly behind

enter image description here

As you can see in the image the tooltip and plot graph are ahead of the x-axis label. How do we align them together?

here is my base config

export const baseChartConfig = (): ApexOptions => {
  return {
    xaxis: {
      tickPlacement: 'between',
      tickAmount: 12,
      labels: {
        offsetX: 10,
        trim: true,
        hideOverlappingLabels: true,
        style: {
          fontSize: '11px'
        }
      }
    },
    yaxis: {
      labels: {
        offsetY: -5,
        style: {
          fontSize: '11px'
        },
        formatter: (value: number) => value.toFixed(0)
      },
      forceNiceScale: true,
      min: 0,
      max: (largestValue: number) => largestValue + 1
    },
    grid: {
      show: true,
      borderColor: 'var(--va-light-tertiary)',
      position: 'back',
      strokeDashArray: 3,
      padding: {
        top: 0,
        bottom: 0,
        right: 10,
        left: 10
      },
      xaxis: {
        lines: {
          show: true
        }
      },
      yaxis: {
        lines: {
          show: true
        }
      }
    },
    plotOptions: {
      bar: {
        columnWidth: '25%',
        borderRadius: 1
      }
    },
  }
}

I have tried removing the padding, offset, etc., but nothing seems to make a difference. This problem persists even if I zoom in or zoom out of the chart.

JS Cryptographic safe vs performacne

So… I’ve been working on a npm (and browser compatible too) JS library for a while, which contains a lot of randomization functions.

It uses Math.random() behind everything, and some days ago, I’ve decided to replace it with a more secure one, since people asked me about security issues

The basic choice was require("crypto").randomBytes , but it doesn’t exist in browsers so I’ve taken a look at crypto.getRandomValues, and it was looking ideal

But with that function, I need to create a new Uint32Array everytime I’d like to get a random number, and it’s then giving very bad performances
( around 2seconds for 1million numbers betweeen 0 and 1 excluded, versus 8ms for Math.random, I knew there’d be a difference, but not that much).

So I’ve decided to create a pool of pre-existing values (around 10’000) inside a function, and I’ll need to recall crypto.getRandomValues with a new Array each 10000 times instead of everytime previously, and I got astonishing results (12ms vs 2seconds)

Here’s the code I used (with somekind of benchmarks), do you think I’ve found a way to reduce those performance issues?

Thanks ^^



let __cryptoPool;
let __cryptoPoolIndex = 0;

function __cleanPool(){
    __cryptoPool = crypto.getRandomValues(new Uint32Array(10000));
    __cryptoPoolIndex = 0;
}

function newRandomPool(){
    if (!__cryptoPool || __cryptoPoolIndex >= 9999){
        __cleanPool();
    }
    return __cryptoPool[__cryptoPoolIndex++];

}

function newRandom(){
    return crypto.getRandomValues(new Uint32Array(1))[0] / 0xffffffff;
}


function tests(n = 1000){

    console.time("using my Pool trick");

    for (var i = n - 1; i >= 0; i--) {
        newRandomPool();
    }
    console.timeEnd("using my Pool trick");


    console.time("not using my Pool trick");

    for (var i = n - 1; i >= 0; i--) {
        newRandom();
    }
    console.timeEnd("not using my Pool trick");


    console.time("using default Math.random");

    for (var i = n - 1; i >= 0; i--) {
        Math.random();
    }
    console.timeEnd("using default Math.random");


}



tests(1000000);

        
*Output : 
using my Pool trick: 12.323ms
not using my Pool trick: 2.082s
using default Math.random: 8.611ms*

React – Set form submit button to disabled until form is empty using useActionState hook

I have a form in a React app. I am using the useActionState hook to manage form status. How can I set the submit button to disabled until the user enters something in the text input?

By using the useState hook to store the input and calling the setter method on input change I can track if there is an input in the form field. But by using useActionState I can only know the form values after submitting the form.

import { useActionState, useState } from "react";

export function MyForm() {

  // form state managed with useActionState
  const [state, formAction] = useActionState(
    updateState,
    { name: ""}
  )
  function updateState(_prevState, formData) {
    // do something
    return {name: formData.get("name") as string}
  }

  // form state managed with useState
  const [state2, setState2] = useState({name: ""})
  function handleChange(e) {
    setState2({name: e.target.value})
  }
  function handleSubmit(e) {
    e.preventDefault()
    // do something
    setState2({name: ""})
  }

  return (
    <>
      {/* form state managed with useActionState */}
      <form  action={formAction}>
        <input type="text" name="name" />
        <button type="submit">Submit</button> {/* <- I want this to be disabled until user enters a value */}
        <div>{state.name}</div>
      </form>

      {/* form state managed with useState */}
      <form onSubmit={handleSubmit}>
        <input type="text" name="name" onChange={handleChange} value={state2.name}/>
        <button disabled={state2.name ? false : true} type="submit">Submit</button> 
        <div>{state2.name}</div>
      </form>
    </>
  )
}

I know there is a hook useFormStatus which might be used for this but I don’t like the idea of having the content of my form in a separate child component.

How can I detect in javascript if a file to be opened is write protected or not?

I need to know if a file is write protected or not (in javascript). So far I know only how to get the below four information pieces:

  • file name, e.g. using document.getElementById(‘file’).files[0].name
  • file size, analoguously
  • file type
  • file modified date

What I need is the information if the file is write protected or not. Something like getProperties or so. Anyone around who understands what I am looking for? Thank you very much in advance.

The context is: I want to save some data in .json format do disc using this tiny function:

function save2JSON (jsonData, fName) { window.showSaveFilePicker({
suggestedName : fName+".json",
types : [{
  description: "JSON file",
  accept: { "application/json": [".json"] },
  lastModified:new Date().getTime()
}],}) .then(async handler => {

let data = jsonData;

let writable = await handler.createWritable();
await writable.write(JSON.stringify(data,null,4));
await writable.close();}).catch(err => console.error(err));}

My web-site tells me so far if a:

  • file exists
  • file is protected

But thats to late and to little. I would like to know before I try to save the file (i.e. when I open it) if the file is protected or not. Ideally, once I try to save the file the function suggests me another name so save the file anyway. Any ideas around?? Once again thank you very much.

User Authentication Across Multiple Tabs in React

I have a React application with a login mechanism that stores the user’s authentication token in localStorage. Here’s the issue I am facing:

  1. User “A” logs in (tab 1).
  2. User “A” opens a new tab (tab 2); they remain logged in as user “A”.
  3. In tab 2, the user logs out and logs back in as user “B”. The token in localStorage updates to the one for user “B”.
  4. When the user returns to tab 1, they see user “B”‘s data loaded in the UI, but the token in localStorage was originally for user “A”.

The problem seems to arise because localStorage is shared between tabs, so the token gets overwritten across all tabs. At the same time, I cannot use sessionStorage because I want the user to maintain authentication if they open a new tab.

My Questions:

  1. What is the best practice to handle this kind of issue?

  2. Should I implement a polling mechanism to sync tabs?

  3. Are there any alternatives to localStorage that allow syncing across tabs but avoid this conflict?

I’d appreciate any insights or suggestions on this. Thanks!

Only one of two processes work in my express server?

So I’m creating an express server using MongoDB as my database. In my server I’ve defined a route for transferring money from one account to another. But the problem is that while the money is being deducted from the sender’s account, it isn’t being credited to the receiver’s account.

This is the route I’ve defined for transfer.

router.post("/transfer", authMiddleware, async (req, res) => {
    try{
        const session = await mongoose.startSession();

        session.startTransaction();
        const {amount, to} = req.body;
        const userId = req.userId.userId;
        const from = await Account.findOne({userId: userId}).session(session);
        
        if (!from || from.balance < amount) {
            await session.abortTransaction();
            return res.status(400).json({
                message: "Insufficient balance"
            });
        }

        const toAccount = Account.findOne({
            userId: to
        }).session(session);

        if (!toAccount) {
            session.abortTransaction();
            return res.status(400).json({
                message: "Invalid account"
            });
        }

        await Account.updateOne({userId}, {
            $inc: {
                balance: -amount
            }
        }).session(session);
        await Account.updateOne({to}, {
            $inc: {
                balance: amount
            }
        }).session(session);

        await session.commitTransaction();
        return res.status(200).json({
            message: "Transfer successfully"
        });
    } catch {
        return res.status(400).json({
            message: "Some error occurred"
        })
    }
})

Cookies are not transmitted to the server

I made sure that I have cookies saved on the client, and the authorization itself works. I can get a token through the frontend, but when I try to check for the token on the server, the server just gets nothing, what should I do? 🙁

Client:

      const checkToken = async () => {
        const token = Cookies.get("authToken");
        console.log("The token is on the client:", token);
      
        if (!token) {
          console.log("There is no token");
          return;
        }
      
        try {
          const response = await fetch("http://localhost:5000/api/auth/check", {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
            },
            credentials: "include", 
          });
      
          console.log("Server responce:", await response.text());
          if (response.status === 200) {
            const data = await response.json();
            console.log("done:", data);
            setUser(data.user); 
          } else {
            console.log("Auth error:", await response.json());
          }
        } catch (error) {
          console.error("Error checking the token:", error);
        }
      };
      

Server:

app.use(
  cors({
    origin: "https://59e5-185-9-186-241.ngrok-free.app",
    methods: ["GET", "POST"],
    allowedHeaders: ["Content-Type", "Authorization"],
    credentials: true, 
  })
);

app.post("/api/auth/telegram", (req, res) => {
  const userData = req.body;


  if (!validateTelegramAuth(userData)) {
    console.log("Неверная подпись Telegram");
    return res.status(403).json({ message: "Incorrect Telegram signature" });
  }


  const token = generateAuthToken(userData);


  res.cookie("authToken", token, {
    httpOnly: true, 
    signed: true, 
    secure: process.env.NODE_ENV === "production",
    sameSite: "None", 
    maxAge: 7 * 24 * 60 * 60 * 1000,
  });

  console.log("The token has been generated and sent:", token);
  return res.json({ token });
});


app.use((req, res, next) => {
  console.log(`Request received: ${req.method} ${req.url}`);
  console.log("Cookies on the server:", req.cookies);
  next();
});

I turned to chatGPT, searched for solutions on the Internet, disabled http only, signed, secure, samesite, received a token through the client and output it (and it was output)