One-Line Title Be Specific: Im

Certainly! Could you please provide the title or context of the problem you’re referring to? That will help me give you a detailed and accurate response.

It seems there may have been a misunderstanding or a formatting error. Could you please provide more context or specify the problem you’re facing? This will help me understand and assist you better

Delayed headline animation until in viewport

I have multiple headlines in a page that I want to animate to be shown word by word.

How can I achieve individual headline animation when they appear in the viewport? Right now all of them are animated on page load.

I have tried to change threshold from 0.1 to 0.8 but no difference.

window.onload = function() {
  const observerOptions = {
    root: null,
    rootMargin: "0px",
    threshold: 0.1

  const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {'span').forEach((span, index) => {
'--word-index', index);
  }, observerOptions);

  document.querySelectorAll('.heading-reveal').forEach(target => {
.heading-reveal {
  display: flex;
  flex-wrap: wrap;

.heading-reveal span {
  opacity: 0;
  animation: revealWord 0.5s forwards;
  animation-delay: calc(var(--word-index) * 0.25s);

@keyframes revealWord {
  to {
    opacity: 1;



Spring Boot check isHttpOnly cookie not working

I’m storing my authentication token on an http-only cookie. When an user logs-in, an http cookie carrying the token will be set. Here’s the code to process the login:

public ResponseEntity<String> processLogin(
    @RequestBody SigninDataDto signinDataDto,
    HttpServletResponse response
) {
    if(signinDataDto.getUserName()!=null && signinDataDto.getPassword()!=null) {
        String userName = signinDataDto.getUserName();
        String password = Common.sha256Hash(signinDataDto.getPassword());
        boolean rememberMe = signinDataDto.isRememberMe();
        UserDetails customUserDetails = new UserService(userRepository).loadUserByUsername(userName);
        if(password.equals(customUserDetails.getPassword())) {
            //Authenticate by cookie
            Cookie jwtCookie = new Cookie(Constants.JWT_NAME, jwtService.generateToken((CustomUserDetails) customUserDetails));
            if(rememberMe) {
            return ResponseEntity.ok("success");
    log.error("Login failed!");
    return ResponseEntity.badRequest().body("failed");

Then i made a filter to authenticate each request by getting the token cookie and verify it. Here’s the filter code:


import com.springdemo.library.utils.Common;
import com.springdemo.library.utils.Constants;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;


public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private JwtService jwtService;
    private UserService customUserDetailsService;
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String jwt = getJwt(request);

            if (StringUtils.hasText(jwt) && jwtService.validateToken(jwt)) {
                String userName = jwtService.getUserNameFromJWT(jwt);
                UserDetails userDetails = customUserDetailsService.loadUserByUsername(userName);
                if(userDetails != null) {
                            authentication = new UsernamePasswordAuthenticationToken(userDetails, null,
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                } else {
        } catch (Exception ex) {
            log.error("failed on set user authentication", ex);

        filterChain.doFilter(request, response);

    private String getJwt(HttpServletRequest request) {
        Cookie cookie = Common.getCookie(request, Constants.JWT_NAME);
        if(cookie!=null) {
            String token = cookie.getValue();
            if(StringUtils.hasText(token)) {
                return token;
        return null;

Security config:

protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            .authorizeRequests(authorizeRequests ->
                            .requestMatchers("/login", "/processlogin").permitAll()
    http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

It works fine if in the filter I don’t check isHttpOnly for the jwt cookie, but if I do, the browser denies access to /Library/home. Please can anyone explain why can’t the filter verify isHttpOnly for the jwt cookie, eventhough I set the cookie as HttpOnly? And any way to check if a cookie is HttpOnly in Java/Spring Boot?

Here’s the JavaScript code that I used to login

$('document').ready(function () {
    $('#id-form-login').on('submit', function (e) {
            url: '/Library/processlogin',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                userName: $("#login-username").val(),
                password: $("#login-password").val(),
                rememberMe: $("#rememberme").prop("checked")
            success: function () {
            error: function (jqXHR, textStatus, errorThrown) {
                console.warn('Error:', textStatus, errorThrown);

Appreciate anyone who helps

Is there a way to easily add new lines in an contenteditable div?

I am building a texteditor and using a contenteditable div for it.
It all works peachy except when I want to lower a line of text by hitting return at the start of the row.

In my app I color code the text based on the character used at the beginning of the row. And one such type of text is simple bodytext, which can be hidden by pressing a toggle. The text then is replaced by a placeholder showing the wordcount of the hidden text.

Now in this hidden state when I want to lower this placeholder by putting the caret at the beginning of the row and hitting return the placeholder no longer keeps the required placeholder class for it to be recognized as a placeholder.
What then happens is when I want to show the text again, the placeholder is not getting replaced with the hidden text, but instead the placeholder text itself overwrites the originally hidden text.

function handleInput(event) {
    const editor = document.getElementById('editor');
    const selection = window.getSelection();
    if (!selection.rangeCount) return;  // No selection available.

    let range = selection.getRangeAt(0);
    let node = selection.anchorNode;  // Get the node where the caret is.
    let div = node.nodeType === 3 ? node.parentNode : node;  // Get the closest div parent or the node itself.

    if (div === {  // If the node is the editor, create a new div.
        div = document.createElement('div');
        div.className = 'bodytext'; // Default to bodytext for new divs
    } else if (div.tagName !== 'DIV') {
        // If the parent is not a div, wrap the node in a new div.
        let newDiv = document.createElement('div');
        newDiv.className = 'bodytext'; // Default to bodytext for new divs
        div = newDiv;

    // Handling new lines after a placeholder-container specifically
    if (node === editor && div.previousElementSibling && div.previousElementSibling.classList.contains('placeholder-container')) {
        const newDiv = document.createElement('div');
        newDiv.className = 'bodytext';
        editor.insertBefore(newDiv, div.previousElementSibling.nextSibling);
        return;  // Prevent further processing

    // Apply class based on the content starting character or its absence.
    if (node.textContent.trim() === '') {
        div.className = 'empty'; // Handle empty divs specially if needed
    } else if (node.textContent.startsWith('#')) {
        div.className = 'heading';
    } else if (node.textContent.startsWith('=')) {
        div.className = 'synopsis';
    } else if (node.textContent.startsWith('@')) {
        div.className = 'non-narrative';
    } else {
        div.className = 'bodytext';

    moveCursorToDiv(div);  // Move the cursor to the end of the new or updated div

function moveCursorToDiv(div) {
    const range = document.createRange();
    const selection = window.getSelection();

All I want to do is to be able to lower a line of placeholder and have it keep the class it had.
It works with all other classes that I have used, except for my placeholder-container class, which gets overwritten by the bodytext class.

I tried just forcing new lines of
whenever a new line is created, but it then creates 2 lines always one that just is bodytext and the other an empty empty-div which brings with it other problems.

execute separate commands in order

I have an understanding problem about a command bus where I need to execute two separate commands in order.

In my case I have a command bus which dispatches commands into a queue to be executed later (possibly on a different instance) and I have two separate commands that I need to execute in order. The second one should only be executed after the first one has been succeeded.

It should look something like this (simplified):

  1. Controller: dispatch command1 (send into queue)
  2. Command Handler: execute command1 -> dispatch success event
  3. Event Handler: handle success event of command1 -> dispatch command2
  4. Command Handler: execute command2

Now, my problem is that command1 & command2 need different information only available in the controller but the commands are separate and command1 should not know about command2.
Additionally command2 should only be executed after command1 has been succeeded and the command bus uses a queue (not executed immediately).

Currently I only see possibilities that are either ugly or very complex:

  • Combine command2 into command1 just so that the event handler can dispatch command2 with all needed information
    (ugly as command1 should not know about command2)
  • separate storage to fetch command2 in event handler
    (high complexity as a separate storage service is needed)
  • create separate command which includes both commands and separate handler directly calling actual handler
    (possibly breaks auto generate events as the command bus does not know about the real commands to be executed)

What I’m missing / What I’m doing wrong here?

Upgrade Laravel from 9 to 10 [closed]

I have project which I need to upgrade from laravel 5.x to 11.x, but when I upgrade from laravel 9.x to 10.x I got the issue, the issue is when refresh the session will reset. Do you anything different with upgrade from 8.x to 9.x with 9.x to 10.x? because from 5 to 9.x no issue with session by using the old one. but when upgrade to 10.x, I get the issue.
Note : I’m using session driver file

explanation and solution

Laravel 11 not executing Policy

So I have a Model, Middleware and a Policy.
The problem is that I seem to can not get the policy to work correctly.

This is my policy code:


namespace AppPolicies;

use IlluminateSupportFacadesLog;
use AppModelsApiKey;

class ApiKeyPolicy
     * Determine if the given API key is valid for the given user.
     * @param  string  $apiUser
     * @param  string  $apiKey
     * @return bool
    public function access($apiUser, $apiKey)
        Log::info("Checking API key for user: $apiUser with key: $apiKey");

        $userApiKey = ApiKey::where('key_user', $apiUser)->first();

        if (!$userApiKey) {
            Log::warning("User not found: $apiUser");
            return false;

        $valid = $userApiKey->key === $apiKey;

        Log::info("API key valid: " . ($valid ? 'Yes' : 'No'));

        return $valid;

This is my middleware code:


namespace AppHttpMiddleware;

use Closure;
use IlluminateHttpRequest;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesGate;
use SymfonyComponentHttpFoundationResponse;

class VerifyApiKeyMiddleware
     * Handle an incoming request.
     * @param  Closure(IlluminateHttpRequest): (SymfonyComponentHttpFoundationResponse)  $next
    public function handle(Request $request, Closure $next): Response
        $apiKey = $request->header('X-AW-KEY');
        $apiUser = $request->header('X-AW-USER');

        Log::info("Received API User: $apiUser, API Key: $apiKey");

        if (!$apiKey || !$apiUser) {
            Log::warning('API key or user not found');
            abort(401, 'API key or user not found');

        // This is always false somehow
        $allowed = Gate::allows('access-api', [$apiUser, $apiKey]);

        Log::info("Gate check result for API User: $apiUser, API Key: $apiKey, Allowed: " . ($allowed ? 'Yes' : 'No'));

        if (!$allowed) {
            Log::warning('Unauthorized API key');
            abort(403, 'Unauthorized API key');

        return $next($request);

Inside the AppServiceProvider.php inside the boot() function I am registering the Policy the following way: Gate::define('access-api', [ApiKeyPolicy::class, 'access']);

This is how I use it:


use IlluminateSupportFacadesRoute;
use AppHttpControllersAPILoginController;

use AppHttpMiddlewareVerifyApiKeyMiddleware;

    ->middleware(['api', VerifyApiKeyMiddleware::class])
    ->group(function ()
        Route::post('/authenticate', [LoginController::class, 'DoAuth'])->name('api.user.authenticate');

My problem is that despite having all the logs and such it never actually does execute the Policy code therefore always returning a false. I really do not see where I did go wrong in this. I tried to map the policies inside the AppServiceProvider but this also did not help.

passing a json between as answer to ajax request [closed]

I use a php code to filter some data as a search engine in a sql database and send the results as json to the index where there is a function that will load these results, in localhost with xampp it works well and fast but on my online host I keep getting this error: Uncaught (in promise) SyntaxError: Unexpected end of JSON input
at index.php:866:29

there is the php code:

include 'config.php';

// Connexion à la base de données
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_error) {
    die("Erreur de connexion à la base de données: " . $mysqli->connect_error);

// Récupération du terme de recherche et formatage
$searchTerm = isset($_GET['recherche']) ? $_GET['recherche'] : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$projetsParPage = 2; // Nombre de projets affichés par page
$offset = ($page - 1) * $projetsParPage;

$searchTermFormatted = '%' . $mysqli->real_escape_string($searchTerm) . '%';

// Récupérer tous les projets correspondant au terme de recherche
$searchQuery = "SELECT * FROM projets WHERE statut=1 AND (titre LIKE ? OR description LIKE ? OR type LIKE ?) ORDER BY id DESC";
$searchStmt = $mysqli->prepare($searchQuery);
$searchStmt->bind_param('sss', $searchTermFormatted, $searchTermFormatted, $searchTermFormatted);
$searchResult = $searchStmt->get_result();
$searchProjects = [];
while ($row = $searchResult->fetch_assoc()) {
    $searchProjects[] = $row;


// Récupérer les autres projets non liés à la recherche
$otherQuery = "SELECT * FROM projets WHERE statut=1 AND id NOT IN (SELECT id FROM projets WHERE statut=1 AND (titre LIKE ? OR description LIKE ? OR type LIKE ?)) ORDER BY id DESC";
$otherStmt = $mysqli->prepare($otherQuery);
$otherStmt->bind_param('sss', $searchTermFormatted, $searchTermFormatted, $searchTermFormatted);
$otherResult = $otherStmt->get_result();
while ($row = $otherResult->fetch_assoc()) {
    $searchProjects[] = $row;

// Diviser les projets en pages
$totalProjects = count($searchProjects);
$totalPages = ceil($totalProjects / $projetsParPage);
$projectsByPage = array_chunk($searchProjects, $projetsParPage);

// Construction de la réponse JSON
$response = [
    'projects' => $projectsByPage,
    'currentPage' => $page,
    'totalPages' => $totalPages,
    'searchTerm' => $searchTerm,
    'notification' => $total1 == 0 ? "Aucun résultat trouvé pour votre recherche. Affinez votre recherche pour obtenir des résultats plus pertinents." : ""

// Fermeture de la connexion

// Renvoyer les projets au format JSON
header('Content-Type: application/json');
echo json_encode($response);

and there the function in the index:

function loadProjects(page, searchTerm) {
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            return response.json();
        .then(data => {
            projectsData = data.projects || []; // Assurez-vous que projectsData est toujours un tableau
            currentPage = data.currentPage || 1; // Défaut à la page 1 si la valeur est manquante
            totalPages = data.totalPages || 1; // Défaut à 1 si la valeur est manquante
            if (data.notification) {
        .catch(error => console.error('Error:', error));

Please help!!!

using the inspection tool i found that is the json I receive in localhost: enter image description here

but on the namecheap host, the json is simply empty

I tried to change the way I create the json, but still doesn’t work on my host wich is a Namecheap host. I tried to explore the server configuration to find something but nothing.

Move to first row with OpenSpout

I read an xlsx- or csv-file with OpenSpout and want to read the first row (column-titles) before further processing. I get the rowIterator like this:

$iterator = $reader->getSheetIterator()->current()->getRowIterator();

The key is at 0 at the beginning. I try to move the key to 1 with


but I get the error
Fatal error: Uncaught Error: Data must be loaded before reading…

What am I missing here?

Synchronous VS setting by reference

i have some trouble with my function who :

  • set product And price in stripe
  • Then set my postRequest with return of stripe ( product_id and price_id )
  • Get my collection product (subscription ) on my DB (firestore)
  • Push my postRequest in collection
  • And update collecttion

My probleme : process Stripe is always ok BUT sometime my collection is not update with product_id and stripe_id

I thinks, i have use await everywhere to be full synchronous .
But…i have always this random problerm

My function

const createSubscription = async(req, res, next) => {


    // const userToken = req.header('Authorization')
    // const userId = await userService.verifyUserToken(req, userToken)
    // await userService.verifyAdmin(req, userId)
    await stripeService.initStripe(req)

    //if itt's not a free offer : manage product and price in side stripe
    //then set body data with product_id and list_price
    if(await !req.body.isFree){
      const product = await stripeService.createProduct({data : req.body})

      if ( await {

        const allPriceForProduct = await setAllPriceProduct(, req)

        delete req.body.stripe_list_prices

        req.body.stripe_product_id =
        req.body.stripe_list_prices = [...allPriceForProduct]

      } else {
        throw new Error('No product idd');


    //Get and set collection subscription
    const subscriptionDB = await subscriptionService.getRefAndDataSubscription(req);

    await subscriptionService.updateSubscriptionRef(req, subscriptionDB.ref, )

    const subscriptionData = await subscriptionService.getRefAndDataSubscription(req);


  }catch (e){
    console.error('stripe_error_create_offer', e.message)
    //send mail admin + log admin ????



You will notice that result of my console.log() req.body and juste before update of collection are ALWAYS good. price_id and product_id are setting with response of stripe
BUt sometime…collection is update WHITOUT product_id and price_id

It’s like function who update collection is played before the real update of object

But all is synschronous with await…

What’s wrong ??
i thinks that timeout resolve problem but it”s a good practice ?

I except and update of my collection with and object updated in 100% of time

npm install error: npm ERR! code EUNSUPPORTEDPROTOCOL npm ERR! Unsupported URL Type “workspace:”: workspace:^

I want to create a new project using vite ( i used to do until now…). When i do npm create vite@latest it works normally. The problem come when i do npm install… Usually this will create the node modules folder, but now it gives me that error:

npm ERR! Unsupported URL Type “workspace:”: workspace:^

npm ERR! A complete log of this run can be found in: C:UsersoasisAppDataLocalnpm-cache_logs2024-05-28T08_35_41_093Z-debug-0.log

I’ve been looking for a solution, but nothing works properly, including yarn and pnpm. Dunno what else i can do.

I’ve been looking for a solution, but nothing works properly, including yarn and pnpm. Dunno what else i can do.

On Radio Button select, select dropdown option with same value

I created 2 input, one is Radio Button, and one is Dropdown. I want user to click on radio button and it will select the option in the dropdown with the same value.

How can I do this with JS, not using Jquery?

Please help me with this.

Thank you!

My sample code:

   <p class="line-item-property__field">
       <input type="radio" name="color" value="1"> <span>1</span><br>
       <input type="radio" name="color" value="2"> <span>2</span><br>
       <input type="radio" name="color" value="3"> <span>3</span><br>

   <p class="line-item-property__field">
         <select id="your-name" name="dropdown-color">
         <option value="1">1</option>
         <option value="2">2</option>
         <option value="3">3</option>

Register Form User Input Data Fetches ‘Null’ (Express/PostgreSQL)

I am trying to get the user’s information with a registration form from the frontend and and save it in database. However, each user entry results as a complete Null object in the terminal and a null row in the database;


The user is already registered
The user is already registered

PostgreSQL: (Table Name: customers)

Database Record

What should I change or add to my code to get the correct input? Any help is highly appreciated


const express = require('express')
const dotenv = require('dotenv').config()
const cookieParser = require('cookie-parser')
const helmet = require('helmet')
const path = require('path');
const db = require('./public/models')
var engines = require('consolidate');
const userRoutes = require ('./public/routes/userRoutes')
const { Pool} = require('pg');

const PORT = process.env.PORT || 8080
const app = express()

const client = new Pool({
  connectionString: process.env.DATABASE_URL,

app.use(express.urlencoded({ extended: false }))
app.set('views', __dirname);
app.engine('html', engines.mustache);
app.set('view engine', 'html');


  app.get('/', function(req, res){
    res.render(__dirname + '/views/mainpage');
    res.render(__dirname + '/views/details');
    res.render(__dirname + '/views/aboutus');
    res.render(__dirname + '/views/myprofile', {user: newUser});
    res.render(__dirname + '/views/payment', {user: newUser});
    res.render(__dirname + '/views/register.html');
    res.render(__dirname + '/views/summary', {user: newUser});
    res.render(__dirname + '/views/login.html');
  });'/register', async (req,res) =>{
    var newUser = await pool.query(   
      `INSERT INTO customers(first_name,last_name,e_mail,password,password2) VALUES ($1,$2,$3,$4,$5) RETURNING *`,  
      if( !== undefined){
        console.log('The user is already registered');
    });'/login', async (req,res) => {  
      if( !== undefined){  
        console.log('The user is already registered');

app.listen(PORT, () => console.log(`Server is connected on ${PORT}`))


    <form class="registerform"  id="register-form" action="/register" method="POST">    
        <h1> Sign Up </h1>
            <h2> Personal Information </h2>
            <div class="form-group row">
                <label for="firstname" class="col-2 col-form-label"> First Name: </label>
                <div class="col-10">
                    <input type="text" class="form-control" id="firstname" placeholder="First Name" required>
            <div class="form-group row">
                <label for="lastname"  class="col-2 col-form-label"> Last Name: </label>
                <div class="col-10">
                    <input type="text" class="form-control" id="lastname" placeholder="Last Name" required>
            <div class="form-group row">
                <label for="email" class="col-2 col-form-label"> Email: </label>
                <div class="col-10">
                    <input type="text" class="form-control" id="email" placeholder="Email" required>
            <div class="form-group row">
                <label for="password" class="col-2 col-form-label"> Password: </label>
                <div class="col-10">
                    <input type="text" class="form-control" id="password" placeholder="Password" required>
            <div class="form-group row">
                <label for="password2" class="col-2 col-form-label"> Password: </label>
                <div class="col-10">
                    <input type="text" class="form-control" id="password2" placeholder="Re-Enter Your Password" required>
            <h2> Address Information </h2>
            <div class="form-group row">
                <label for="Address" class="col-2 col-form-label"> Address: </label>
                <div class="col-10">
                    <input type="text" class="form-control" id="address" placeholder="1234 Main St">
            <div class="form-group row">
                <label for="address2" class="col-2 col-form-label"> Address 2: </label>
                <div class="col-10">    
                    <input type="text" class="form-control" id="address2" placeholder="District and Apartment No">
            <div class="form-group row">       
                <label for="city" class="col-2 col-form-label"> City: </label>
                <div class="col-10">       
                    <input type="text" class="form-control" id="city"> 
            <div class="form-group row"> 
                <label for="country" class="col-2 col-form-label"> Country: </label>
                <div class="col-10"> 
                <select id="country" class="form-control" style="font-size: 1rem;">
                    <option selected>Choose from the list</option>          
                    <option>United States</option>           
                    <option>United Kingdom</option>            
                    <option>South Korea</option>            
            <div class="form-group row">      
                <label for="postcode" class="col-2 col-form-label"> Postcode: </label>
                <div class="col-10"> 
                    <input type="text" class="form-control" id="postcode">
            <div class="button1">
                <input type="submit" value="Register" id="submitButton">
            <a style="font-weight:bold;padding-left:3em;padding-bottom: 5em;" href="/login">Already registered? Sign In here</a>
            const formRegister = document.querySelector('registerform');
            formRegister.addEventListener('submit',event =>{
                const formData = new FormData(formRegister);
                const data = new URLSearchParams(formData);
                fetch('http://localhost:4000/register', {
                    method: 'POST',
                    body: data
                }). then(res => res.json())
                .then(data => console.log(data))
                .catch(error => console.log(error));


module.exports = (sequelize, DataTypes) => {
    const newUser = sequelize.define( "customers", {
        first_name: {
            type: DataTypes.STRING,
            allowNull: false
        last_name: {
            type: DataTypes.STRING,
            allowNull: false
        e_mail: {
            type: DataTypes.STRING,
            unique: true,
            isEmail: true, //checks for email format
            allowNull: false
        password: {
            type: DataTypes.STRING,
            allowNull: false
        password2: {
            type: DataTypes.STRING,
            allowNull: false
        is_verified: {
            type: DataTypes.BOOLEAN,
            defaultValue: false

    }, {timestamps: false}, )

    return newUser

Google Translate and ReactFlagsSelect Integration Causing DOMException and TypeError

I’m working on a website where I’ve integrated a custom Google language translator. The translator changes the language correctly, but after changing the language, selecting a country in a form using ReactFlagsSelect throws the following errors:
Uncaught DOMException: Failed to execute ‘removeChild’ on ‘Node’: The node to be removed is not a child of this node.
at Cs (

Uncaught TypeError: Cannot read properties of undefined (reading ‘L’)
at _.oj (m=el_main:24:315)

Here’s the relevant part of my code:

import React, { useEffect, useRef, useState } from "react";
import { Container } from "reactstrap";
import ReactFlagsSelect from "react-flags-select";

function HeaderTop({ executeScroll, showNav }) {
  const [selectedCountry, setSelectedCountry] = useState('');
  const [selectedLanguage, setSelectedLanguage] = useState("");
  const languagesArray = ["en", "pt", "ar", "es", "af", "sq", "am", "da", "dv", "doi", "hmn", "pa", "qu", "lg", "lt", "ln", "is", "hu"];
  const languageRef = useRef(null);

  useEffect(() => {
    const country = JSON.parse(localStorage.getItem('Country'));
    if (country) {
  }, []);

  const handleLanguageChange = (language) => {

  const updateGoogleTranslateLanguage = (language) => {
    const translateSelect = document.querySelector(".goog-te-combo");
    if (translateSelect) {
      for (let i = 0; i < translateSelect.options.length; i++) {
        if (translateSelect.options[i].value === language) {
          translateSelect.selectedIndex = i;
      const event = new Event("change");

  useEffect(() => {
    const initializeGoogleTranslate = () => {
      const script = document.createElement("script");
      script.src = "//"; = "google-translator-script";
      window.googleTranslateElementInit = googleTranslateElementInit;
  }, []);

  return (
      {showNav && (
        <div className="header_top">
          <Container className="d-flex align-items-center">
            {/* Your existing code */}
            <div ref={languageRef}>
                <DropdownToggle caret color="white" className="notranslate text-white">
                  {, index) => (
                    <DropdownItem key={index} onClick={() => handleLanguageChange(language)}>
              <div className="d-none">
                <div id="google_translate_element"></div>

export default HeaderTop;
I’ve tried initializing the Google Translator script in different useEffect hooks and verified that the element is correctly appended to the DOM. I also ensured that the language change event is correctly triggered.
I expected the language change to work seamlessly with the country selection. Instead, I encountered DOMException and TypeError errors.

What would be the return type of the function below using Nextjs 14 and Typescript 5?

I am new to using NextJs and Typescript. I am making a route handler and I cannot figure out the return type of the below function. I thought NextApiResonse<userType | null> should work but it doesn’t. What am I doing wrong?

import { UserModel } from "@/lib/models";
import { connectMongoDb } from "@/lib/utils";
import { userType } from "@/types/types";
import { NextApiRequest, NextApiResponse } from "next";
import { NextResponse } from "next/server";

export const GET = async (request:NextApiRequest, { params }:{params:{id:"string"}}) => {
  const { id } = params;
  try {
    const user:userType = await UserModel.findById(id);
    if (user) {
      return NextResponse.json(user);
    } else {
      return NextResponse.json({ error: "User not found" });
  } catch (error) {
    console.log("API getuser error", error);
    return NextResponse.json({ error: "Failed to fetch user" });
    throw new Error("Failed to fetch user");

If anyone can guide me and help me figure out the correct return type of the above function, I will be thankful.