How to prevent HTMX from going back to /login page after sign in?

I have a Go + HTMX web app. On the Login page, there’s a form that sends a POST request to the /login route, which is guarded by a middleware, which checks if the user is already logged in, and if that’s the case, redirects them to the Dashboard page.

The post /login handler, adds an HX-Location header, set to /dashboard, so that on successful login, the user is taken straight to the Dashboard page.

The problem is that if after login, the browser’s back button is pressed, the user is taken back to the Login page. Normally that’s guarded by the middleware, but since HTMX saves the page into localStorage, the browser doesn’t make a new request to the server, and instead serves the page from the localStorage, and so the guard isn’t implemented.

What’s the best way to work around this?

Pass variable into FetchXML via Javascript for Dynamics 365

I’ll keep this concise as I find I ramble on too much if I don’t.

I’ve come up with the code below, but I continue to get an error stating that the addCustomView isn’t a function. I’ve found numerous guides online but they don’t seem to run into this issue, so I suspect I am calling the wrong control.

https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/clientapi/reference/controls/addcustomview

For context:

I have three tables in a model driven app that have connections to each other.

Account
Contact
Facility

The facility table has a form in which I want a subgrid that can only add contacts that are already associated with the “parent” account to the facility. So only contacts with parentcustomerid (from the contact) == associatedaccount (on the facility) can be seen when a user adds them via the subgrid. I think I am making a mistake with the gridContext portion and either looking at the wrong control which might explain the error?

function setFacilityContactView(executionContext) 

{
        var formContext = executionContext.getFormContext();
        var gridContext = formContext.getControl("xyz_accountlookup");
        var fetchXml = "<fetch><entity name='contact'><attribute name='fullname' /><attribute name='emailaddress1' /><attribute name='parentcustomerid' /><link-entity name='xyz_facilities' from='xyz_associatedaccount' to='parentcustomerid' alias='Facility'><attribute name='xyz_associatedaccount' /></link-entity><filter><condition attribute='parentcustomerid' operator='eq' valueof='Facility.xyz_associatedaccount' /></filter></entity></fetch>";
    
        var layoutXml = "<grid name='resultset' object='2' jump='fullname' select='1' icon='1' preview='1'><row name='result' id='contactid'><cell name='fullname' width='142' /><cell name='emailaddress1' width='131' /></row></grid>";

        var viewId = "{00000000-0000-0000-0000-000012112023}";
        var viewDisplayName = "Facility Contacts";

        gridContext.addCustomView(viewId, "contact", viewDisplayName, fetchXml, layoutXml, true);
    
}

How to run vanilla HTML and Vanilla Javascript in React?

I have the task to “copy+paste” a page that used to be run in vanilla html and javascript into this React Application… I want to avoid refactoring as much as possible because this singular html and the vanilla.js that comes with it are really specific and big and it works with another .php file but that doesn’t come into account (for now?)

Anyway, I thought it was going to be easy at first, just copy paste the html and use the script, but apparently its not that simple, so after a lot of trials and errors I got to this solution:

Files layout:

/public
- vanilla.js

.../components/career-page/
- index.js
//index.js
const loadScript = (src, type = 'text/javascript', defer = true) => {
    return new Promise((resolve, reject) => {
        if (document.querySelector(`script[src="${src}"]`)) {
            resolve();
            return;
        }

        const script = document.createElement('script');
        script.src = src;
        script.type = type;
        script.defer = defer;
        script.onload = () => resolve(script);
        script.onerror = () => reject(new Error(`Script load error: ${src}`));
        document.body.appendChild(script);
    });
};

const CareerPage = () => {
    const [scriptsLoaded, setScriptsLoaded] = useState(false);

    useEffect(() => {
        Promise.all([
            loadScript('https://code.jquery.com/jquery-3.6.0.min.js','text/javascript'),
            loadScript('https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js'),
            loadScript('./vanilla.js')
        ]).then(() => {
            setScriptsLoaded(true);
        }).catch(error => {
            console.error('Error loading scripts:', error);
        });
    }, []);

    useEffect(() => {
        if (scriptsLoaded) {
            const container = document.getElementById('dynamic-content');
            if (container) {
        container.innerHTML = `
            <section class="section section-lg bg-default" id="jobs">
               <div class="container">
                ...
            </section>
           `;
         }
       }
     }, [scriptsLoaded]);

     return (
    <>
        <img src={bannerCareer} className="w-100" alt="careers"/>
        <div id="dynamic-content" />
    </>
  );
};

export default CareerPage;
//vanilla.js
const filedev = document.querySelector("#selectFile");
const curriculumDev = document.querySelector(".file__picture");
const choiceArchive = "Pick your file";
const arquivoText = "Select your file...";
curriculumDev.innerHTML = arquivoText;
const message = document.getElementById("fileExceeded");

filedev.addEventListener("change", function (e) {
  e.preventDefault();
  const inputTarget = e.target;
  const file = inputTarget.files[0];
  if (file) {
    const reader = new FileReader();
    if (file.size > 26214400) {
      message.innerHTML = "File Size Exceeded";
      return false;
    } else {
      reader.addEventListener("load", function (e) {
        const readeTarget = e.target;
        if (readeTarget) {
          curriculumDev.innerHTML = file.name;
        } else {
          alert("Please, select a file");
        }
      });
    }
    reader.readAsDataURL(file);
  } else {
    curriculumDev.innerHTML = choiceArchive;
  }
});

The above script is one of the many that repeat throughout the .js file and even though I get no errors when entering accessing this specific page, the script does not seem to work, it does load and I can see it on Network, I get a “Status Code: 304 Not Modified” , but the reason I think it doesn’t work is this this button for example:

<button type="button" class="btn-shared shadow-sm">
 Share our stuff!
  <a href="" id="whatsapp-share-android"
   rel="noopener external nofollow" target="_blank"
   class="link-whatsapp"></a>
 </button>

The following code is inside our vanilla.js:

document.addEventListener(
  "DOMContentLoaded",
  function () {
    var content = encodeURIComponent(
      document.title + " " + window.location.href
    );
    document.getElementById("whatsapp-share-btt").href =
      "https://api.whatsapp.com/send?text=" + content; //
    document.getElementById("whatsapp-share-sap").href =
      "https://api.whatsapp.com/send?text=" + content; //
    document.getElementById("whatsapp-share-android").href =
      "https://api.whatsapp.com/send?text=" + content; //
    document.getElementById("whatsapp-share-ios").href =
      "https://api.whatsapp.com/send?text=" + content; //
    document.getElementById("whatsapp-share-frontend").href =
      "https://api.whatsapp.com/send?text=" + content; //
    document.getElementById("whatsapp-share-testes").href =
      "https://api.whatsapp.com/send?text=" + content; //
    document.getElementById("whatsapp-share-c").href =
      "https://api.whatsapp.com/send?text=" + content;
    document.getElementById("whatsapp-share-cloud").href =
      "https://api.whatsapp.com/send?text=" + content;
  },
  false
);

Even if I click the button “Share our stuff” i get redirected to the page I currently am, not the phone app page, which is another strong indication that the script is not working…

Any help on how I can make the script work given this awful case?

I already tried using DangerouslySetHTML too but I got some other errors
Also here is a pictuer showing that the script does load in network and that it does say that the scripts loaded which is here

 if (scriptsLoaded) {
            const container = document.getElementById('dynamic-content');
            console.log('Scripts loaded, setting innerHTML');

            if (container) {

        container.innerHTML = `

enter image description here

enter image description here

Implementing Instagram Share Functionality in Spring Boot Project

I’m currently working on a feature for our blogging project that allows users to share post links on various social media platforms, including Facebook, Instagram, and Telegram.

I’ve successfully implemented sharing via Telegram using the following format:
https://t.me/share/url?url=${encodeURIComponent(text)}&text=${encodeURIComponent('Check this out!')}

However, I need assistance with implementing a similar sharing feature for Instagram, particularly to allow users to share post links directly to Instagram DMs, stories, or posts. So far, I haven’t found a straightforward way to achieve this, as Instagram’s API and sharing mechanisms differ from other platforms.

Could anyone provide guidance or suggestions on how to create shareable links for Instagram, or share their experiences if they’ve tackled a similar issue?

For Instagram, I attempted to use the intent:// scheme to copy the link to the clipboard and then redirect to the Instagram app. Here’s the code I used:

    var dummy = document.createElement("textarea");
    const text = window.location.href;
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
    window.location.href = `intent://send?text=${encodeURIComponent(text)}#Intent;scheme=instagram;package=com.instagram.android;end`;

    setTimeout(function () {
        if (document.visibilityState === "visible") {
            window.location.href = `https://www.instagram.com/direct`;
        }
    }, 100);
}

I expected that this approach would either:

Open the Instagram app with a prompt to share the link directly in a DM, or
Open the Instagram app with a prompt to share the link as a story or post.
However, it appears that Instagram’s current API and sharing mechanisms might not support direct sharing of links in this manner. I am looking for a more reliable way to achieve the desired functionality, or any alternative methods that could be used for sharing content on Instagram.

New Google maps loading error: not-loading-api-from-google-maps-error

My app uses Google Maps API, and has worked well so far. Yet, when trying to update my Android app, I get the awful white page with the message:

Oops! Something went wrong.

My web app works fine, it is just the Android one (same HTML, same JS) which has problems.

I then went to the javascript console in Android Studio, and it says:

[INFO:CONSOLE(139)] "Google Maps JavaScript API error: NotLoadingAPIFromGoogleMapsError

with the link

 https://developers.google.com/maps/documentation/javascript/error-messages#not-loading-api-from-google-maps-error

I went to that page, and it says:

 NotLoadingAPIFromGoogleMapsError: The script element that loads
 the Maps JavaScript API is not being included correctly on your page.
 In order for the API to work correctly, it must be loaded directly from
 https://maps.googleapis.com.

Yet, I load the API with the lines:

 <script src="https://www.google.com/jsapi"></script>
 <script src="https://maps.googleapis.com/maps/api/js?key=...."></script>

which is of course the Google server.

Again: My web app works fine, it is just the Android one (same HTML, same JS) which has problems.

To make things even more strange, I have another Android app that uses Google maps as above, without problems.

What is going on?

how to solve google authentication error when using passport.js

I am trying to impliment google authentication feature to my Node.js application using Passport.js middleware and google oAuth strategy when click the button after sometimes the user is created in database but page does not redirect to the home page

it’s redirect to authentication route and keep loading after sometimes user created in mongodb database but not redirect to the home

How do I unlink node from a javascript file?

I have two javascript files, one for node and one for my frontend javascript. However, whenever I run the frontend javascript file, I get Node.js v20.16.0. How can I unlink it and link it to the other file?

I tried to change it on package.json but it still does that. Any tips?

auth.currentUser = null, NextJS 14 AuthJS v5 Firebase Auth

I’m facing a problem for almost 2 days. I want to make a change-password page with Firebase Auth

change-password/page.tsx

"use client";
import React, { useState, useEffect } from "react";
import { auth } from "@/firebase";
import { useSession } from "next-auth/react";
import {
  reauthenticateWithCredential,
  EmailAuthProvider,
  updatePassword,
  onAuthStateChanged,
  getAuth,
} from "firebase/auth";
import { User } from "next-auth";

const ChangePass = () => {
  const [oldPassword, setOldPassword] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [passMatch, setPassMatch] = useState(true);

  async function changePassword(currentPassword: string, newPassword: string) {
    const user = auth.currentUser;

    if (!user) {
      throw new Error("No user logged in");
    } else {
      if (!passMatch) {
        return console.log("Passwords don't match");
      }

      const credential = EmailAuthProvider.credential(
        user.email!,
        currentPassword
      );
        reauthenticateWithCredential(user, credential);
        updatePassword(user, newPassword);
  }
}

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    try {
      await changePassword(oldPassword, password);
      alert("Password changed successfully!");
    } catch (error: any) {
      alert(error.message);
    }
  };

  return (
    <main className="lg:w-10/12 lg:mx-auto p-8 h-[90vh] flex justify-center items-center">
      <form
        onSubmit={handleSubmit}
        className="flex flex-col bg-white p-10 py-10 rounded-xl shadow-xl lg:items-center justify-center lg:w-fit"
      >
        <label className="text-lg font-normal mb-1">Current Password : </label>
        <input
          name="oldPassword"
          type="password"
          className="bg-transparent placeholder:text-gray-300 border-2 bg-white border-red-400 rounded-2xl py-0.5 px-2 w-80 outline-none"
          placeholder="Enter old password"
          value={oldPassword}
          onChange={(e) => setOldPassword(e.target.value)}
        />
        <label className="text-lg font-semibold mb-1 mt-5">Password</label>
        <input
          name="password"
          type="password"
          className="bg-transparent border-2 placeholder:text-gray-300 bg-white border-red-600 rounded-2xl py-0.5 px-2 w-80 outline-none"
          placeholder="Enter new password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <label className="text-lg  font-semibold mt-5 mb-1">
          Confirm password
        </label>
        <input
          name="confirmPassword"
          type="password"
          className="bg-transparent border-2 placeholder:text-gray-300 bg-white border-red-600 rounded-2xl py-0.5 px-2 w-80 outline-none"
          placeholder="Confirm new password"
          value={confirmPassword}
          onChange={(e) => setConfirmPassword(e.target.value)}
        />
        {!passMatch && (
          <p className="text-xs pl-2 mt-1 text-red-400 text-left">
            Passwords don&apos;t match
          </p>
        )}
        <button
          type="submit"
          className="bg-gradient-to-b from-red-800 to-red-600 text-gray-100 w-fit rounded-lg mx-auto py-2 px-4 font-semibold mt-8"
          disabled={!passMatch || !password || !oldPassword}
        >
          Change password
        </button>
      </form>
    </main>
  );
};

export default ChangePass;

I searched that i need auth.currentUser, but for some reason it is null and i can’t updatePassword

I tried to make use of onAuthStateChanged but unfortunately it didn’t help me.
What I found out about this problem is that if I log in from the /signin page and then I was redirected to / and in the main page.tsx i did
const session = await auth(); const user = authFirebase.currentUser; console.log(user);
and it showed me the user but only after i logged in, and then when i changed the link to /change-password it became null.
Session is working but currentUser no.
Any thoughts on this?

Thanks and best wishes :*

I have a React project that does not want to run

Everytime i try creating the react app, i get following error:

PS C:UsersTashs NovemberDesktopEvent Management> npm create vite@litenpm error code SELF_SIGNED_CERT_IN_CHAIN
npm error request to https://registry.npmjs.org/create-vite failed, reason: self-signed certificate
in certificate chain

npm error A complete log of this run can be found in: C:UsersTashs NovemberAppDataLocalnpm-cac
he_logs2024-07-31T08_45_49_900Z-debug-0.log
PS C:UsersTashs NovemberDesktopEvent Management> npm create vite@latest
npm error code SELF_SIGNED_CERT_IN_CHAIN
npm error errno SELF_SIGNED_CERT_IN_CHAIN

I tried opening a react folder using the following command prompts :
npm create vite@latest
npm create vite@lite
npx create-react-app events management

in hopes of it creating the actual app but it does not run

I keep receiving this error: Cannot destructure property ‘blockhash’ of ‘(intermediate value)’ as it is undefined

This is the code in question. Anyone know how i can fix this?

// Function to send transaction
async function sendTransaction(transaction) {
  try {
    transaction.feePayer = wallet.publicKey;
    const { blockhash, lastValidBlockHeight } = await rateLimitedRequest(() => connection.getLatestBlockhash({
      commitment: 'confirmed',
    }));
    transaction.recentBlockhash = blockhash;
    transaction.lastValidBlockHeight = lastValidBlockHeight;
    transaction.sign(wallet);
    const signature = await rateLimitedRequest(() => connection.sendRawTransaction(transaction.serialize()));
    await connection.confirmTransaction({
      signature,
      blockhash,
      lastValidBlockHeight,
    });
    logger.info(`Transaction sent with signature: ${signature}`);
  } catch (error) {
    logger.error(`Error sending transaction: ${error.message}`);
  }
}

I havent found a solution for this

Issues with Logging into Web Application locally Running in Docker on Windows

I’m encountering a problem with a web application running in a Docker container on Windows. Although the application starts correctly and is accessible in the browser, I am unable to log in even though the credentials are correct. ( I am junior )
Details:
App – Nextjs 13.4.8
Docker Desktop 4.33.1
node v20.10.0

Docker Image:
I am using the node:18-alpine image to run a Next.js application. Here is my Dockerfile:


# Install dependencies only when needed
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app

COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN 
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; 
  elif [ -f package-lock.json ]; then npm ci; 
  elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; 
  else echo "Lockfile not found." && exit 1; 
  fi

FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN 
  if [ -f yarn.lock ]; then yarn run build; 
  elif [ -f package-lock.json ]; then npm run build; 
  elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; 
  else echo "Lockfile not found." && exit 1; 
  fi

FROM base AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public
RUN mkdir .next
RUN chown nextjs:nodejs .next

COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000
ENV PORT 3000

CMD HOSTNAME="0.0.0.0" node server.js

Issues:

The application starts correctly and listens on port 3000.
The application is accessible in the browser, but I cannot log in despite using the correct credentials.
I have checked environment variables and ensured that NEXT_PUBLIC_API_URL is correctly set in the .env.local file.

Container Logs:
The container logs indicate that the application is running correctly, but there are errors related to missing image resources that might be non-critical:

2024-07-31 19:21:43 The requested resource isn't a valid image for /images/logo.png received text/html; charset=utf-8

What I’ve Tried:
Checked .env.local configuration and file paths.
Verified that the application is accessible in the browser and listening on port 3000.
Question:
What could be causing the login issues with the application in a Docker container on Windows despite using the correct credentials? Are there additional diagnostic steps I can take to resolve this problem?

Puppeteer Heroku/Node script accessing stale data

I am running a Puppeteer script on Heroku which logs into a company website, navigates to a reports page, selects a tab which triggers an ajax call (i believe) and displays the data related to the tab selected.

When the script runs in puppeteer (headless = false so i can observe) it clicks everything correctly, and the UI appears correct however when it goes to download the file, the original data (from page load) is downloaded, but not the data which is currently displayed in the UI after selecting the tab.

When i manually interact with the chromium browser that is being run by the server and click the download button myself, it downloads the correct data.

I have added all sorts of delays and wait for request idle functions.. however nothing seems to fix the issue.

Is there anything obvious as to why this is happening?

I should note it is a relatively new issue, the same script was working on this website one week ago.


    await page.waitForSelector('ul.nav.nav-tabs > li:nth-child(4) > a'); // Wait for the fourth <li> to be available
    await page.click('ul.nav.nav-tabs > li:nth-child(4) > a'); // Click the <a> inside the fourth <li>
    
    await delay(3000)

    console.log(7)

    // open the filters and add the activityReference to the filter options
    await page.evaluate(() => {
      // Select the parent div
      const parentDiv = document.querySelector('.col-3.col-md-6.text-right.ng-binding');
      // Select all buttons within the parent div
      const buttons = parentDiv.querySelectorAll('button');
      console.log("buttons1: ", buttons)
      // Click the third button
      buttons[2].click();
    });

    console.log(8)

    await page.evaluate(() => {
      const labels = Array.from(document.querySelectorAll('label.form-check-label'));
      const targetLabel = labels.find(label => label.textContent.includes('ActivityReference'));
      if (targetLabel) {
          targetLabel.click();
        }
    });
  
    console.log(9)

    // save and close the filter modal
    await page.waitForSelector('button[ng-click="close()"]', { visible: true });

    await page.click('button[ng-click="close()"]');

    console.log(10)
    
    await delay(3000)

    // select the download button
    await page.evaluate(() => {
      // Select the parent div
      const parentDiv = document.querySelector('.col-3.col-md-6.text-right.ng-binding');
      // Select all buttons within the parent div
      const buttons = parentDiv.querySelectorAll('button');
      console.log("buttons2: ", buttons)
      // Click the third button
      buttons[1].click();
  });

    // ensure file is downloaded
    await delay(10000)

I have tried a myriad of ways to click the tab button which loads the new data prior to downloading. Each method shows the button being clicked and the correct data loading, however not matter how long I wait before clicking the download button, the old data is still downloaded.

touchstart event listener causing glitches in JavaScript game animation

I’ve made a Flappy Bird clone using vanilla JavaScript.

It runs pretty well on all non-mobile browsers.

However, when I play it using Chrome or Safari on iPhone, the tapping meant to make the bird jump causes the sliding obstacles to glitch (briefly shake in place). This happens every time I tap but only when I tap.

All of my animations use requestAnimationFrame().

I thought increased load during implementation of the jump() logic would be the cause, but the issue persists even after I have disabled:

-jump()
-crash detection
-gravity
-score tracker

Essentially, the only thing left running are my obstacles animation and the ‘touchstart’ event listener with no callbacks, yet the issue persists.

I tried preventDefault() on the event listener, but still to no avail.

Here is the animation which slides the objects:

function runShips() {
    //create random ship every 5 seconds
    generateShipsInterval();

    let previousTime = null;

    function slideShipsAnimation(currentTime) {
        if (!previousTime) {
            previousTime = currentTime;
        }
        let dt = (currentTime - previousTime) / 1000;
        document.querySelectorAll('.ships').forEach(ship => {
            ship.style.left = `${(parseFloat(getComputedStyle(ship).left) - 3 * dt * 60)}px`;
        });

        previousTime = currentTime;
        loops.slideShipsAnimation = requestAnimationFrame(slideShipsAnimation);
    }
    loops.slideShipsAnimation = requestAnimationFrame(slideShipsAnimation);

    //clear ships that are out of the screen every 10 seconds
    clearShipsInterval();
}

and here is my event handler whose logic I have disabled:

if (isMobile()) {
    //listen for tap
    document.addEventListener('touchstart', function(event) {
        event.preventDefault(); 
        handleTap();
    });
}

function handleTap() {
    if (mode === gameStates.start) {
        getReady();
        return
    }
    if (mode === gameStates.play) {
        jump();
        return
    }
    if (laughingElon.style.display === 'block') return

    if (mode === gameStates.crash) {
        getReady();
        return
    }
    if (mode === gameStates.ready) {
        startGame();
        jump();
        return
    }
}

function jump() {
    // const x = 32;

    // birdFrames.forEach((frame, index) => {
    //     setTimeout(() => {
    //         bird.src = frame;
    //     }, index * x);
    // });

    // velocity = -9.5;
}

Log4j ScriptFilter for only logging when logger name starts with a certain word?

I am trying to write a log4j2 xml file where some of the appenders will only allow logs if the logger name starts with a specific word, for example “foo”. In this instance I’m using a Kafka filter to write to an event hub.

To get into the weeds a bit — I’m using a shell script to write the xml file and using the shell script as an init file for a databricks compute cluster and then using that cluster to send logs to the event hub instance. But without using a ScriptFilter, the rest of the process works fine in that I’m able to listen to the messages the event hub receives, and the messages are what I would expect to see.

I’ve tried many variations of this ScriptFilter with no luck. Whenever I remove the ScriptFilter, it logs everything, but when I add back in any variation of my ScriptFilter, the event hub stops receiving any messages at all.

Here are some things I’ve tried:

<!-- in Appenders section -->
<Kafka name="kafkaAppender" topic="eventHubInstanceName">
    <JsonTemplateLayout eventTemplateUri="path/to/template.json"/>
    <Property name="bootstrap.servers">event-hub-namespace.servicebus.windows.net:9093</Property>
    <Property name="sasl.mechanism">PLAIN</Property>
    <Property name="security.protocol">SASL_SSL</Property>
    <Property name="sasl.jaas.config">
      org.apache.kafka.common.security.plain.PlainLoginModule required username="$ConnectionString" password="[REDACTED]";
    </Property>
    <Filters>
      <ScriptFilter onMatch="ACCEPT" onMismatch="DENY">
      <Script name="scriptFilter" language="javascript"><![CDATA[
         var loggerName = logEvent.getLoggerName();
         loggerName.startsWith("foo");
      ]]></Script>
      </ScriptFilter>
    </Filters>
</Kafka>

I’ve also tried this variation of the Script:

<Script name="scriptFilter" language="javascript"><![CDATA[
  if (logEvent.getLoggerName().startsWith("foo")) {
    return true;
  }
    return false;
  ]]>

and this one:

<Script name="scriptFilter" language="javascript"><![CDATA[
  if (logEvent.getLoggerName().startsWith("foo")) {
    true;
  }
    false;
  ]]>

I’ve also tried moving the filter out of the appender section entirely and adding it to the Root section instead along with the AppenderRef to kafkaAppender, as well as moving the filter into its own Logger and adding the AppenderRef to it that way. Nothing works — whenever I add in a ScriptFilter, nothing logs at all.

I’m unable to use a regex filter here because it only checks the message itself, whereas I want to check the name of the logger.

Please help!