Cookies Not Being Set in Production in Next.js App

I’m working on a Next.js application where I’m setting a cookie after a successful login. The cookie is supposed to store an authentication token. This works as expected in my local development environment, but when deployed to production, the cookie is not being set.

Here’s the function I use to set the cookie:

import Cookies from 'js-cookie';

async function saveCookie(token) {
    Cookies.set('auth_token', token, {
        httpOnly: process.env.NODE_ENV !== 'development',
        expires: 60,
        secure: process.env.NODE_ENV !== 'development',
        sameSite: 'lax',
        path: '/',
    });
}

In production, the login functionality works, and the API returns a token as expected. However, the auth_token cookie does not appear in the browser’s cookie storage.

Attached is a screenshot showing that the user is logged in (indicating the token is received), but the cookie is not visible in the browser’s cookies.

enter image description here

I have deployed the frontend on Netlify with an environment variable NODE_ENV=production.

Why is the cookie not being set in the production environment, despite other parts of the application running as expected?

How can I make sure my iframe takes the whole width and height of the screen, regardless of any width restrictions

So i have an widget I built using an iframe and I give it to users like this

<div style="height: 100px; width: 100px">
    <iframe src="https://jade-biscuit-7026ef.netlify.app/?productId=LprOsWjrho5B&type=popup" style="border: 0;"
      height="100vh" width="100vw"></iframe>
  </div>

so users can set the height and width in the container div as shown above. My problem now is, in the iframe, I have a modal that opens up on click of a button, so i want this modal to take up the full width and height of the user’s screen but instead, it is restricted by the dimensions of the containing div

below is the code in my iframe:

/** @format */

import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalBody,
  useDisclosure,
  Box,
} from "@chakra-ui/react";
import CheckoutInfo from "./CheckoutCard";
import { Button } from "mainstack-design-system";
import { useEffect, useState } from "react";
import { TPaymentOptions, TProductDataRes } from "types";
import StripeCardCheckout from "./StripeCardCheckout";

interface IProps {
  width: string | null;
  productId: string;
  btnText?: string;
}
const PopupCheckout = ({ width, productId, btnText }: IProps) => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const [openModal,setOpenModal] = useState(false)
  const [paymentOption, setPaymentOption] = useState<TPaymentOptions>("");
  const [productData, setProductData] = useState<TProductDataRes>(
    {} as TProductDataRes
  );

  const ipAddress = JSON.parse(window.localStorage.getItem("userIp"));
  const isNigerian = ipAddress?.currency === "NGN";

  useEffect(()=>{
    setOpenModal(true)
  },[])
  return (
    <>
      <Button
        variant="primary"
        onClick={onOpen}
        label={btnText ?? "Proceed to checkout"}
        size="medium"
      />
      
      <Modal isOpen={openModal} onClose={onClose}>
        <ModalOverlay />
        <ModalContent
          className="modal"
          borderRadius={'0.75rem'}
          maxWidth={width}
          // w={"95%"}
          // maxH={"90vh"}
          overflow={"scroll"}
        >
          <ModalBody padding={0}>
            <CheckoutInfo
              hasBorder
              hasCancel
              closeModal={() => setOpenModal(false)}
              paymentOption={paymentOption}
              setPaymentOption={setPaymentOption}
              productId={productId}
              setProductData={setProductData}
            />
            {paymentOption === "card" && !isNigerian && (
              <StripeCardCheckout
                setPaymentOption={setPaymentOption}
                productData={productData}
                closePopup={() => setOpenModal(false)}
              />
            )}
          </ModalBody>
        </ModalContent>
      </Modal>
    </>
  );
};

export default PopupCheckout;

and below is how a user can call it:

<div style="height: 100vh;">
    <iframe src="https://jade-biscuit-7026ef.netlify.app/?productId=LprOsWjrho5B&type=popup" style="border: 0;"
      height="100%" width="100%"></iframe>
  </div>

javascript getting value from one to multiple data-testid tags [duplicate]

Using a tampermonkey script to get the text value from 1 to many possible data-testid tags. The page can have one or up to x of them that look like this. Need to extract Mercedes and all of the Auto’s from any data-testid=”autombile” on the page.

<span class="something" data-testid="automobile">
Auto:
<b>Mercedes</b>
</span>

Tried using different getElementById parameters.

RouteReuseStrategy not working for routing with dynamic params

router-strategy.ts

import {RouteReuseStrategy,ActivatedRouteSnapshot,DetachedRouteHandle,} from '@angular/router';

export class RtgRouteReuseStrategy implements RouteReuseStrategy {
  private routeLeftFrom: string | undefined;
  private handlers: { [key: string]: DetachedRouteHandle } = {};

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    this.routeLeftFrom = route.routeConfig!.path;
    return route.data['shouldReuseRoute'] || false;
  }

  store(route: ActivatedRouteSnapshot, handler: DetachedRouteHandle): void {
    if (handler) {
      this.handlers[this.getUrl(route)] = handler;
    }
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    const url = this.getUrl(route);
    return !!this.handlers[url];
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    if (!route.routeConfig || route.routeConfig.loadChildren) {
      return null;
    }

    return this.handlers[this.getUrl(route)];
  }

  shouldReuseRoute(future: ActivatedRouteSnapshot,current: ActivatedRouteSnapshot): boolean {
    const reUseUrl = future.routeConfig?.data?.['reuse'];
    const defaultReuse = future.routeConfig === current.routeConfig;
    return reUseUrl || defaultReuse;
  }

  getUrl(route: ActivatedRouteSnapshot): string {
    const url = route.url.map((segment) => segment.path).join('/');
    return url;
  }
}

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { AuthGuard } from './core/authguard/auth.guard';
import { RtgCreationComponent } from './modules/rtg-form/components/rtg-creation/rtg-creation.component';
import { RtgViewComponent } from './modules/rtg-form/components/rtg-view/rtg-view.component';

const routes: Routes = [
  { path: '', redirectTo: "rtgmaster", pathMatch: "full" },
  {
    path: "rtgmaster",
    canActivate: [AuthGuard],
    component: AppComponent
  },
  {
    path:"form/:rtgId/:email/:phnNumber",
    canActivate: [AuthGuard],
    component:RtgCreationComponent,
     data: {
        shouldReuseRoute: true,
        reuseRoutesFrom: ["rtgmaster","form/:rtgId/:email/:phnNumber/view"]
     }
  },
  {
    path: "form/:rtgId/:email/:phnNumber/view",
    canActivate: [AuthGuard],
    component:RtgViewComponent
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

I can create multiple instances of RtgViewComponent & single instance of RtgCreationComponent. I am just opening these components inside a stepper(i,e like browser tabs) by looping & each component instance will be created with dynamic query params for both RtgViewComponent & RtgCreationComponent.

I need to restore form data in RtgCreationComponent after routing from RtgViewComponent & AppComponent.

Issue I am facing is:

If I create RtgCreationComponent first then creates multiple number of RtgViewComponent. Then routing back to
RtgCreationComponent from RtgViewComponent/AppComponent works fine(i,e form data/router instance wont’t be destroyed).

but

If I create RtgViewComponent first, then creates RtgCreationComponent.Then routing back to
RtgCreationComponent from RtgViewComponent breaks the router instacne but routing back from AppComponent work fine.

Please suggest what wrong with my router-strategy.ts code

passportjs req.isAuthenticated() always returns false

I am using react for my frontend and its hosted on port 3001, while my backend is hosted on port 3000. I am sending a GET request to the server from my frontend to a route that runs “req.isAuthenticated()” and then returns “true” if the client is authenticated or “false” if it’s not, the problem is, as the title suggests, that it always returns “false” no matter what. When logging in i console.log the req.user after authentication and it successfully prints the user, thats not the case with the check-authentication route, it prints “undefined”, even though the cookie is sent with the request, well.. a cookie named “connect.sid” atleast, which I bet is the one.

My login route:

req.login(user, (err) => {
    if (err) {
      console.log(err);
      res.redirect("http://localhost:3001/signin");
    } else {
      passport.authenticate("local")(req, res, function () {
        req.session.save((err) => {
          if (err) {
            console.log(err);
          } else {
            console.log(req.user);
            res.redirect("http://localhost:3001/");
          }
        });
      });
    }
  });
});

My check-auth route:

app.get("/api/check-auth", (req, res) => {
  console.log("Session:", req.session);
  console.log("User:", req.user);

  if (req.isAuthenticated()) {
    // User is authenticated
    console.log("true");
    res.json({ authenticated: true, user: req.user });
  } else {
    console.log("false");
    // User is not authenticated
    res.json({ authenticated: false });
  }
});

General stuff/setup:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(
  cors({
    methods: ["GET", "POST", "PUT", "DELETE"],
    allowedHeaders: ["Content-Type", "Authorization"],
    origin: "http://localhost:3001",
    credentials: true,
  })
);

app.use(
  session({
    secret: "This is a secret key.",
    resave: false,
    saveUninitialized: false,
    store: MongoStore.create({
      mongoUrl:
        "myClusterUrl"
    }),
    cookie: {
      httpOnly: true,
      secure: true, //when false throws error "needs to be secure in order to be "none" samesite"      
      sameSite: "None",
      domain: "localhost:3001",
    },
  })
);

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect(
  "myClusterUrl"
);

const userSchema = new mongoose.Schema({
  username: String,
  password: String,
  email: String,
  cart: [productSchema],
  reviews: Array,
});

userSchema.plugin(passportLocalMongoose);

const User = mongoose.model("User", userSchema);

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

My frontend:

const [authenticated, setAuthenticated] = useState(false);

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const response = await axios.get(
          "http://localhost:3000/api/check-auth",
          { withCredentials: true }
        );
        console.log(response.data); //always prints "authenticated: false"
        setAuthenticated(response.data.authenticated);
      } catch (error) {
        console.error("Error checking authentication status:", error);
      }
    };

    checkAuth();
  }, []);

At first I had set my frontend using form, and I am pretty sure I had the same issue, no errors just returning false, and I saw on a forum that a guy used “fetch” to make the request so it can also send the cookies with it, so I went ahead and changed my request from “form” to “axios” and added “withCredentials: true” for the cookies, which lead to other errors with the request/response headers
which I tried to solve inside CORS configurations & res.headers, using the help of google, but they didn’t really do much, the error was still there, sometimes changing between an “origin cant be *” *(even tho I had specified it) or some allow-access-something doesnt include X (which was included), so someone recommended me to add a “proxy” on my frontend and that fixed this error.

After that I thought maybe its a serialize/deserialize issue so the session is not saved correctly and tried doing this insead of the above

passport.serializeUser(function (user, done) {
  done(null, user);
});

passport.deserializeUser(function (id, done) {
  User.findById(id, function (err, user) {
    done(err, user);
  });
});

but it still returned false.

Then copilot suggested I should use another way to authenticate the user cause this was “creating a new user instead”, and suggested I should use bcrypt to compare the passwords, but that was returning an error.

Also tried app.use(cookieParser()) as suggested from another post, nothing really changed.

Tried adding “http://” on “domain” under the cookies configuration

I think I have tried pretty much everything suggested by google/copilot/chatgpt but nothing fixed my problem.Any ideas?

Typescript: Taking a typescript object and converting each property into a union of separate objects

My objective is to take a typescript object and convert each property into a union of separate objects.

For example:

{
 200: number;
 500: string;
}

into

{
 200: number;
 500?: undefined;
} |
{
 500: string;
 200?: undefined;
}

I believe I was able to get this level except anytime I add a random property along with a valid property, it doesn’t error out. How do I make it error out?
ie

{
 100: "why no error", // this should error error...
 200: 100,
}

Full code sample:

type AllKeys<T> = T extends unknown ? keyof T : never;
type Id<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;
type _ExclusifyUnion<T, K extends PropertyKey> = T extends unknown
  ? Id<T & Partial<Record<Exclude<K, keyof T>, never>>>
  : never;
type ExclusifyUnion<T> = _ExclusifyUnion<T, AllKeys<T>>;
type split_return_type<T> = {
  [K in keyof T]: { [P in K]: T[P] };
};
type ValueOf<T> = T[keyof T];
export type SchemezLayoutReturnType<T> = Promise<
  ExclusifyUnion<ValueOf<split_return_type<Required<T>>>>
>;

function TestFnx<T>(input: T, handleAsync: () => SchemezLayoutReturnType<T>) {
    return {
        input,
        handleAsync,
    }
}

type required_return_type = {
    200: number;
    500: string;
}
const rrr: required_return_type = {
    200: 100,
    500: "00"
};
TestFnx(rrr, async () => {
    return {
        100: "200",
        200: 100,
        // 500: "oii",
    }
});

Reference: Playground

Listening for URL changes safari web extension

I want to create a safari web extension for iOS in Xcode 15 that execute some code or the code in the content.js file whenever the url changes

The default template only call the content.js file when the website changes but not on every url change. For example if I go to https://www.apple.com/ then https://www.apple.com/iphone/ the code does not being called, which I want it to be called

Is there a way to do that?

CCS + JS Flex display

I have a parent flex display with column orientation.
Inside this parent flex are flex containers of row orientation(there are elements inside as well).
CCS

This is for a table as shown below
Default image

I have another box for search option. As I type into that, the idea is to hide child elements on the table. Please see below:
Problem

My problem is the inputManageTableContainer doesn’t auto resize when some child elements are hidden or collapse. Also, I expect the shown elements to cascade automatically to top position because position is relative. In the case of problem image, element with name ‘EFG’ needs to appear on top. Hiding the elements is not an issue as you can see in the problem image.

I tried adding a load function for inputManageTableContainer and inputManageTableDataRowContainer , but result is the same.

Code snippet

Code

I know that my element tags or ID for 3 items below are correct since I can change their height manually
-parent container (m_strTagDataTableContainer)
-child container (strTagInputContainer)
-input name (strInputName)

What am I missing here?

Thanks!

Correct

JS form validation using ajax, for email validation

here i have a form email validation but its in server side i want it in client side (Real time Validation).

i want form validation for business email Checking. its nere accept gmail.com, yahoo, bing, yopmail , like public provides

 LtsCustomerRegistration.prototype.handleEvents = function () {
        var _this = this;
        $(".btn-next-step-1").click(function() {
            _this.step1Validation.validate().then(function (status) {
                if (status == 'Valid') {
                    var step1FormData = LtsMain.formSetData('#CustomerSignUpFormStep1');
                    _this.customerSignUp(step1FormData, function(res){
                        $('#customer_id_hidden').val(res.customerId);
                        _this.switchTabs(2);
                    }, 
                    function(res){
                        if(res.status === 'user_exist'){
                            $('#customer_email').parents('.form-group').find('.email-exists-validation-msg').removeClass('d-none');
                            $('#multi-step-form').animate({
                                scrollTop: 0
                            }, 1000);
                        } else if(res.status === 'invalid_email'){
                            $('#customer_email').parents('.form-group').find('.email-invalid-validation-msg').removeClass('d-none');
                            $('#multi-step-form').animate({
                                scrollTop: 0
                            }, 1000);
                        }
                    });
                }
            });
        });   

this validation is Check the user email invalid or not, in the submit button Click 
this pass to a method in symfony "customerSignUp"


here is validation is client side real time validation.

Why every() and find() behaves differently in javascript?

Get to know exact situations where we can use and where not.
every() returns true if all elements in an array pass a test function, while find() returns the first element in an array that passes a test function. below example

const surveyors = [{
    name: "Steve",
    answer: "Yes"
  },
  {
    name: "Jessica",
    answer: "Yes"
  },
  {
    name: "Peter",
    answer: "Yes"
  },
  {
    name: "Elaine",
    answer: "No"
  }
];


surveyors.find((value, index) => {
  if (value.answer === "Yes") {
    console.log(value);
  }
});

// output
/* {
  answer: "Yes",
  name: "Steve"
}
{
  answer: "Yes",
  name: "Jessica"
}
{
  answer: "Yes",
  name: "Peter"
} */

surveyors.every((value, index) => {
  if (value.answer === "Yes") {
    console.log(value);
  }
});

// output
/* {
  answer: "Yes",
  name: "Steve"
} */

How can I correctly use JavaScript’s import and export

Currently, I want to achieve real-time updating of the online user count in a chat room. The WebSocket is set up in room.js, and when a chat room connects, it updates index.html, which is handled by index.js. My approach is to import the module from index.js so that when room.js WebSocket receives a message, it calls a function in index.js. However, it seems that there are some issues.

I attempted to import the above code from index.js into room.js.Regardless of whether I place onlineCount inside or outside DOMContentLoaded in room.js, the program in index.js runs repeatedly until document.querySelector(“#roomInput”).focus();, and an error is displayed: “Cannot read properties of null (reading ‘focus’).” Furthermore, when room.js runs until the invocation of onlineCount, the same issue arises: room.js:100 Uncaught TypeError: onlineCount is not a function.

index.js is responsible for index.html, while room.js is responsible for room.html.

Considering the above, how can I correctly import and execute the desired code block?

index.js

let onlineCount;
export{onlineCount};

document.addEventListener('DOMContentLoaded', function(){

    function onlineCount(room, online){ 
    let roomSelect = document.querySelector('#roomSelect');
    console.log('hi')
    // testing  
    let newOption = document.createElement("option");
    newOption.value = room;
    newOption.innerHTML = room;
    roomSelect.appendChild(newOption);
       
    // focus 'roomInput' when user opens the page
    document.querySelector("#roomInput").focus();

    //....  
    }   

room.js

// chat/static/room.js
import {onlineCount} from '/static/index.js';

document.addEventListener('DOMContentLoaded', function(){
console.log("Sanity check from room.js.");

//....
function connect() {
    chatSocket = new WebSocket("ws://" + window.location.host + "/ws/chat/" + roomName + "/");
    //open
    chatSocket.addEventListener("open", () => {
        console.log("Successfully connected to the WebSocket.")
    })
    //close
    chatSocket.addEventListener("close", () => {
        console.log("WebSocket connection closed unexpectedly. Trying to reconnect in 2s...")
        setTimeout(function() {
            console.log("Reconnecting...");
            connect();
        }, 2000);
    })
    //message
    chatSocket.addEventListener("message", (e) => {
        const data = JSON.parse(e.data);
        console.log(data);
        
        switch (data.type) {

                //.....
                case "online_count":
                onlineCount(data.room, data.online)
                break;
                
               //....
     })
   }
   connect();
})

Help is much appreciated.

Github getting env value in js (without node.js)

I’m trying to get env value by JS in Github, but the solutions I found require Node.js, which my project doesn’t use.

I’ve made a yml in the workspace:

name: env

on:
  push:
    branches: [ main ]

jobs:
  secrets-in-github-actions:
    runs-on: windows-latest

    steps:
      - name: Setting env
        env:
          MYVAR: ${{ secrets.MYVAR }}
        run: echo "Process finished"

      - name: create env file
        run: |
          touch .env
          echo MYVAR=${{ secrets.MYVAR }} >> .env

How can I access the env value (MYVAR) in javaScript file? Thanks.

PS: I’m making an html website through github.io

and process.env.MYVAR doesn’t work as it requires Node.js (error: process is not defined)

And I didn’t create .env file, if it’s needed, should I put it in the root file?

how to Nodejs data to c#

with this code I get an authorization ticket and print it to json file

let authTicket = await this.steamUser.getAuthSessionTicket(730);

        if (!authTicket || !authTicket.appTicket) {
            reject(new Error("Failed to obtain authentication ticket."));
            return;
        }

        let ticketCrc = StdLib.Hashing.crc32(authTicket.appTicket);
        
        const dataToWrite = {
            pAuthTicket: authTicket.appTicket,
            cbAuthTicket: authTicket.appTicket.length,
            steamID: this.steamUser.steamID.getSteamID64(),
        };

        const jsonData = JSON.stringify(dataToWrite, null, 2);

        const filePath = 'C:\Users\Administrator\Desktop\tickets\output.json';  

        fs.writeFileSync(filePath, jsonData, 'utf-8');

        console.log('Data has been written to', filePath);

The json file looks like this:

{ “pAuthTicket”: {
“type”: “Buffer”,
“data”: [
20,
0,
0,
0,
141,
236,
97,
66,
27,
111,
202,
165,
133,
191,
202,
64,
1,
0,
16,
1,
139,
184,
177,
101,
24,
0,
0,
0,
1,
0,
0,
0,
2,
0,
0,
0,
79,
32,
197,
18,
0,
0,
0,
0,
47,
24,
0,
0,
1,
0,
0,
0,
190,
0,
0,
0,
62,
0,
0,
0,
4,
0,
0,
0,
133,
191,
202,
64,
1,
0,
16,
1,
218,
2,
0,
0,
79,
32,
197,
18,
13,
240,
173,
186,
0,
0,
0,
0,
145,
184,
177,
101,
17,
104,
205,
101,
1,
0,
26,
161,
4,
0,
2,
0,
40,
201,
34,
0,
0,
0,
41,
201,
34,
0,
0,
0,
0,
0,
14,
115,
141,
181,
104,
97,
167,
151,
206,
163,
57,
201,
56,
244,
100,
9,
77,
151,
187,
70,
117,
106,
35,
169,
97,
21,
174,
162,
43,
69,
254,
32,
70,
11,
54,
23,
119,
176,
156,
140,
146,
202,
225,
85,
183,
201,
64,
196,
165,
156,
139,
112,
81,
25,
91,
130,
119,
231,
75,
20,
91,
12,
179,
222,
130,
96,
190,
38,
24,
84,
191,
218,
221,
108,
250,
158,
221,
20,
232,
252,
91,
207,
178,
172,
232,
91,
98,
216,
84,
250,
143,
135,
8,
96,
148,
147,
158,
132,
254,
6,
122,
72,
90,
75,
46,
124,
75,
47,
13,
223,
241,
190,
228,
5,
172,
207,
23,
101,
176,
123,
254,
243,
222,
79,
196,
77,
117,
128
] }, “cbAuthTicket”: 246, “steamID”: “7656119xxxxxxxx” }

I need to export it to c# and verify it with steamworks.net. How can I do it in the easiest and smoothest way?

    try
    {
        AuthTicketData authTicketData = Newtonsoft.Json.JsonConvert.DeserializeObject<AuthTicketData>(jsonData);

        EBeginAuthSessionResult authResult = SteamGameServer.BeginAuthSession(
            authTicketData.pAuthTicket,
            authTicketData.cbAuthTicket,
            new CSteamID(authTicketData.steamID) 
        );

        if (authResult == EBeginAuthSessionResult.k_EBeginAuthSessionResultOK)
        {
            Console.WriteLine("Bilet doğrulandı!");
        }
        else
        {
            Console.WriteLine("Bilet doğrulaması başarısız! Sonuç: " + authResult.ToString());
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Hata: " + ex.Message);
    }
}


[Serializable]
public class AuthTicketData
{
    public byte[] pAuthTicket;
    public int cbAuthTicket;
    public ulong steamID;
    
}

I tried this but it doesn’t work.

How to ask for player input p5.js hex code

I have this code for a “cube clicker game” I was messing around with

let angleX = 0;
let angleY = 0;
let sideLength;
let vertices = [];
let particles = [];
let score = 1;
let variableToToggle = false;
let variableToToggle2 = false;
let variableToToggle3 = false;
let cubeScaleFactor = 0.5; // Adjust this factor to control the size of the cube
let particleScaleFactor; // This will be calculated based on the original canvas size
let col1 = null; // Updated to allow selection through buttons
let startScreen = true; // Added to track if the start screen is active
let buttonGraphics; // Graphics buffer for button text
let xenoxFont; // Declare xenoxFont variable

function preload() {
  // Load the Xenox font
  xenoxFont = loadFont('xenox.ttf'); 
}

function setup() {
  createCanvas(400, 400, WEBGL);

  // Calculate sideLength based on the smaller dimension of the canvas
  sideLength = min(width, height) * cubeScaleFactor / 2;

  // Calculate particleScaleFactor based on the original canvas size (400, 400)
  particleScaleFactor = sqrt((width * height) / (400 * 400));

  // Define vertices for the cube
  for (let i = -1; i <= 1; i += 2) {
    for (let j = -1; j <= 1; j += 2) {
      for (let k = -1; k <= 1; k += 2) {
        vertices.push(createVector(i * sideLength / 2, j * sideLength / 2, k * sideLength / 2));
      }
    }
  }

  // Create a graphics buffer for button text
  buttonGraphics = createGraphics(400, 400);
  buttonGraphics.textFont(xenoxFont); 
  buttonGraphics.textAlign(CENTER, CENTER);
  buttonGraphics.textSize(20);

  // Display start screen buttons
  displayStartScreen();
}

function draw() {
  // Draw the main content
  if (startScreen) {
    // Draw start screen background
    background(255);

    // Display start screen buttons
    displayStartScreen();
  } else {
    if (score % 50 === 0) {
      variableToToggle = !variableToToggle;
      score++;
      if (variableToToggle2 == false) {
        variableToToggle3 = !variableToToggle3;
      }
    }

    // Toggle background color
    if (variableToToggle == false) {
      background(220);
    } else {
      background(10);
    }
    cubeCreate();

    // Draw and update particles
    for (let i = particles.length - 1; i >= 0; i--) {
      particles[i].update();
      particles[i].display();
      if (particles[i].isOffScreen()) {
        particles.splice(i, 1);
      }
    }
  }
}

function mousePressed() {
  if (startScreen) {
    // Check if the mouse is over a color button on the start screen
    const numButtons = 5;
    const buttonHeight = height / numButtons;

    for (let i = 0; i < numButtons; i++) {
      let buttonY = height / 2 - buttonHeight + i * buttonHeight;
      if (mouseX > width / 2 - 200 && mouseX < width / 2 + 200 && mouseY > buttonY - 1.5 * buttonHeight && mouseY < buttonY - 0.5 * buttonHeight) {
        col1 = i; // Adjust the col1 value accordingly
        startScreen = false;
        clearStartScreen();
      }
    }
  } else {
    // Check if the mouse is inside the cube
    let d = dist(mouseX - width / 2, mouseY - height / 2, 0, 0);
    if (d < sideLength) {
      // Generate particles in both directions and update the score
      for (let i = 0; i < 10; i++) {
        particles.push(new CubeParticle(1)); // Particle in the current direction
        particles.push(new CubeParticle(-1)); // Particle in the opposite direction
      }
      score++;
    }
  }
}


function displayStartScreen() {
  // Display start screen with 5 buttons
  for (let i = 0; i < 5; i++) {
    buttonGraphics.fill(150);
    buttonGraphics.rect(0, i * 80, 400, 80);
    buttonGraphics.fill(255);
    buttonGraphics.text('Color ' + (i + 1), 200, 40 + i * 80);
  }
  texture(buttonGraphics);
  plane(400, 400);
}

function clearStartScreen() {
  // Clear start screen button
  background(255);
}

class CubeParticle {
  constructor(direction) {
    this.position = createVector(0, 0, 0);
    this.velocity = createVector(random(-2, 2) * particleScaleFactor * direction, random(-5, -1) * particleScaleFactor, random(-2, 2) * particleScaleFactor * direction);
    this.size = 5 * particleScaleFactor;

    // Contrast the hue of the cube color
    this.hue = (random(360) + 180) % 360; // Random hue with 180-degree contrast
  }

  update() {
    this.position.add(this.velocity);
    this.velocity.y += 0.1 * particleScaleFactor; // Gravity
  }

  display() {
    push();
    translate(this.position.x, this.position.y, this.position.z);
    fill(this.hue, 100, 100);
    box(this.size);
    pop();
  }

  isOffScreen() {
    return this.position.y > height / 2;
  }
}

function cubeCreate() {
  rotateX(angleX);
  rotateY(angleY);

  // Draw the cube
  if (variableToToggle2 == false) {
    variableToToggle3 = true;
    if (col1 == 0) {
      stroke(0);
      fill(150, 150, 255, 250);
    } else if (col1 == 1) {
      stroke(0, 0, 255, 250);
      fill(50, 50, 255, 150);
    } else if (col1 == 2) {
      stroke(255, 0, 0, 250);
      fill(255, 50, 50, 150);
    } else if (col1 == 3) {
      stroke(255, 150, 0, 250);
      fill(255, 200, 50, 150);
    } else if (col1 == 4){
      
    } else {
      stroke(0);
      fill(150, 150, 150, 250);
    }
  }

  beginShape();
  // Bottom face
  vertex(vertices[0].x, vertices[0].y, vertices[0].z);
  vertex(vertices[2].x, vertices[2].y, vertices[2].z);
  vertex(vertices[6].x, vertices[6].y, vertices[6].z);
  vertex(vertices[4].x, vertices[4].y, vertices[4].z);
  endShape(CLOSE);

  beginShape();
  // Top face
  vertex(vertices[1].x, vertices[1].y, vertices[1].z);
  vertex(vertices[3].x, vertices[3].y, vertices[3].z);
  vertex(vertices[7].x, vertices[7].y, vertices[7].z);
  vertex(vertices[5].x, vertices[5].y, vertices[5].z);
  endShape(CLOSE);

  beginShape();
  // Side faces
  vertex(vertices[0].x, vertices[0].y, vertices[0].z);
  vertex(vertices[1].x, vertices[1].y, vertices[1].z);
  vertex(vertices[3].x, vertices[3].y, vertices[3].z);
  vertex(vertices[2].x, vertices[2].y, vertices[2].z);
  endShape(CLOSE);

  beginShape();
  vertex(vertices[4].x, vertices[4].y, vertices[4].z);
  vertex(vertices[5].x, vertices[5].y, vertices[5].z);
  vertex(vertices[7].x, vertices[7].y, vertices[7].z);
  vertex(vertices[6].x, vertices[6].y, vertices[6].z);
  endShape(CLOSE);

  // Front and back faces
  beginShape();
  vertex(vertices[0].x, vertices[0].y, vertices[0].z);
  vertex(vertices[1].x, vertices[1].y, vertices[1].z);
  vertex(vertices[5].x, vertices[5].y, vertices[5].z);
  vertex(vertices[4].x, vertices[4].y, vertices[4].z);
  endShape(CLOSE);

  beginShape();
  vertex(vertices[2].x, vertices[2].y, vertices[2].z);
  vertex(vertices[3].x, vertices[3].y, vertices[3].z);
  vertex(vertices[7].x, vertices[7].y, vertices[7].z);
  vertex(vertices[6].x, vertices[6].y, vertices[6].z);
  endShape(CLOSE);

  // Update rotation angles
  angleX += 0.01;
  angleY += 0.01;
}


and I want the 5th button to go to a hex code input

I thought about using the key detection system
Example

You hit color5 button

outline of a rectangle with a flashing vertical line imitating your position in the code

function keyPressed() detecting the number and letter keys required for a hex code

an enter button to enter it or keypressed ENTER

should return with red text hexcode does not exist or something if it is not a valid hex code

Some issues with this
#1 You cant copy and paste hex codes
#2 (and arguably more important) I struggle to embed functions like this (I’m willing to do it if I know a method works)

can someone help me?

PLEASE NOTE – I am using the WEBGL format so the text is really weird
the only extra file I have is the xenox text (it can be any font renamed to xenox.ttf if you want to test it)