Merging Base 64 pdfs into one pdf Ionic Angular [closed]

I am trying to achieve something that I have a offline online functionallity
while user is offline everything is fetched from sqlite and stored in it when i am Online the data is synced in the online data base now i have a form with ability to upload additional Documents such as pdf in the end it’s report is formed in form of pdf includinf the attached PDFs for online it can work fine. where user want to see attached document he click on view pdf he sees behind it there is a url that fetches the pdf from the backend.But for the offline i can’t do that and it is must for me the offline stuff So client demands are that the pdfs should be merged but not view i said ok but how will merge all the base 64 attached pdfs into one along the form data
and to work it offline also this is very crucial to me

Only able to do Online but not accurate

Add i tag in HTML using JavaScript?

I try to add <i> tag in Html using JS. But JS is not appending this tag.

Actually the <i> tag is a Font-Awesome icon.
Font Awesome Script tag has already been inserted in HTML head tag.

// Add side navbar
let left_navbarList = [
    {
        name: "Home",
        item_Class: "fa-solid fa -house",
    },

    {
        name: "Today",
        item_Class: "fa-light fa-calendar-days",
    },

    {
        name: "Upcoming",
        item_Class: "fa-regular fa-angle-up",
    },

    {
        name: "Complete",
        item_Class: "fa-regular fa-flag",
    },

    {
        name: "Setting",
        item_Class: "fa-regular fa-gears",
    },
]

let left_nabar = document.querySelector(".left-navbar-list");
console.log(left_nabar);

const div = document.createElement('div')
div.className = "border-white border-solid rounded-3xl pl-3.5 p-1.5 bg-[#3D404A]"
const i_tag = document.createElement('i');
i_tag.className = left_navbarList[0].item_Class;
div.appendChild(i_tag);
div.innerText = left_navbarList[0].name;
left_nabar.append(div);
<div class="left-navbar-list"></div>

I want insert a icon in div tag. What I do to handle this problem?

dmn-js integration in existing Vue 2 project causes lezer-feel and chokidar errors

I’m trying to use dmn-js in my Vue 2 project. Initially, I created a fresh Vue project just to use this library and got it working the way I wanted. Now, I’m trying to copy the components and pages into my existing project to use them there. However, I keep getting the following error:

This dependency was not found:

  • lezer-feel in ./node_modules/@bpmn-io/feel-lint/dist/index.esm.js, ./node_modules/lang-feel/dist/index.js To install it, you can run: npm
    install –save lezer-feel

Error from chokidar (C:): Error: EBUSY: resource busy or locked,
lstat ‘C:DumpStack.log.tmp’

Even though I installed lezer-feel and added the following code block to vue.config.js, the error is not resolved:

devServer: {
  watchOptions: {
    ignored: [
      '**/node_modules',
      'C:/hiberfil.sys'
    ]
  }
}

How to clear validation error messages when I open modal editor for the second time?

In Laravel 12 / vuejs 3 app I use modal form with validation in edit and insert mode.

Problem is that when user clicks on edit button to open the model form and close it (even without editing/saving it)
and next click on add button to create a new item the modal form is opened with 2 validation error messages(Not required)

Code for add button is in vue file :

<el-button type="primary" @click="openEdit(newModel, form)">Add Item</el-button>

export default {
    components: {RegionCreateDialog, ModelTable},
    mixins: [model],
    data() {
        return {
            ...
            newModel: {
                locations: [],
                location_id: null,
            }
        }
    },

Method openEdit is in common.js file, which methods are used in many editors:

methods: {
    openEdit(model, theForm) {
        console.log('openEdit model::', model)
        console.log('openEdit theForm::', theForm)

        // if (model) {
        this.form = { ...model };
        // }
        if (theForm) {
            theForm.errors = {};  // No errors - but I still have validation error messages

            // If to uncomment line below I got error :  Uncaught TypeError: Cannot read properties of undefined (reading 'clean')
            // theForm.$validator.clean();


            // If to uncomment line below I got error :  Uncaught TypeError: theForm.errors.clear is not a function
            // theForm.errors.clear();


            const initialState = {
                locations: [],
                location_id: null,
            }
            Object.assign(theForm, initialState); // No errors - but I still have validation error messages

            console.log('CLEARING ::')

        }

        this.showEditForm = true;
    },
    ...
}

I try to pass new model with empty values newModel and the form form and try to clear validation error messages – but no methods working, some raises
errors (I show in the code above)…

How to clear them correctly ?

How to upload excel sheet in a webpage by Java Script and after upload the values should fetch to Tables in website

have to create a website for graphical representation (java script)

  1. first have upload the excel file with values in webpage
  2. second load into website
  3. third after loading excel sheet values it should reflect in tables in website in every pages

is anyone can help me with it

database we have azure.

I tried creating uploading button and files getting saved but it does not fetch to next page tables

REACT Why it won’t react the next line? – Await Axios.post

UPDATE: I removed async/await and it’s now working as I expect.
However I don’t know how I can use the async/await now with this code of mine. If you have suggestions on how I should do it, It’d be appreciated.

After posting, (I checked the data base and the data saves without any problem.) My goal is to send a ‘success’ dialog after the post is successful but it doesnt seem to reach the succeeding line of codes. Please help. PS sorry for how I write my code. I’m a newbie

import axios from "axios";
import { useNavigate } from "react-router";
import { motion } from "motion/react";
import { useState, useEffect } from "react";
const GameOverForm = (props) => {
  const [isPostSuccess, setPostSuccess] = useState(false);
  const nav = useNavigate();
  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = {
      playerName: e.target.playerName.value,
      score: e.target.score.value,
    };
    try {
      console.log("before submit");
      await axios.post("http://localhost:3000/submit", formData); // This line will push through 
      console.log("after submit"); //but the succeeding lines wont be reached.
      setPostSuccess(true);
      console.log("after setPostSuccess");
    } catch (err) {
      console.log("Error", err);
    }
  };

  useEffect(() => {
    if (isPostSuccess) closeThisDialog();
  }, [isPostSuccess]);

  const closeThisDialog = () => {
    nav("/");
  };

  return (
    <>
      <form
        className="flex flex-col gap-2 items-center my-3"
        method="POST"
        onSubmit={handleSubmit}
      >
        <input type="hidden" value={props.score} name="score" />
        <input
          name="playerName"
          type="text"
          id="input"
          className="rounded-2xl h-8 border-2 border-green-800 ring-1 ring-green-200 px-2 placeholder:text-center"
          placeholder="Enter Your Name"
          required
        />
        <input type="submit" className="w-1/3 h-7 border-2 rounded-2xl" />

        {isPostSuccess && (
          <motion.p
            className="fixed top-1/2 -translate-y-1/2 w-full left-0 text-2xl"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 1 }}
          >
            Success!
          </motion.p>
        )}
      </form>
    </>
  );
};
export default GameOverForm;

I tried to console log to double check what’s really going on and I confirmed that after the AXIOS post, it would never reach the next line of codes.

The player flickers when hovering over a thumbnail

I’m creating a section on a website that contains two columns. On the left side, there’s a video with three thumbnails below it. When hovering over one of the thumbnails, the corresponding video should play.

The problem is that when hovering over a thumbnail, the video player flickers for a moment, creating an annoying visual effect.

this is my code:

  <!-- Seccion 2 -->
         <section class="info-section">
            <div class="info-container">
              <!-- Columna 1: video -->
              <div class="info-video">
                <video id="mainVideo" controls loop>
                  <source src="vid/vid1.mp4" type="video/mp4">
                  Tu navegador no soporta el video.
                </video>
                 
                
                
              </div>
              
              <div class="miniaturas">
                <video class="miniatura" muted loop src="vid/vid1.mp4"></video>
                <video class="miniatura" muted loop src="vid/vid2.MP4"></video>
                <video class="miniatura" muted loop src="vid/vid3.MP4"></video>
              </div>
               
              
              <!-- javascript video1 -->
              <script>
                const mainVideo = document.getElementById("mainVideo");
                const miniaturas = document.querySelectorAll(".miniatura");
            
                // Reproduce el video principal al hacer hover
                mainVideo.addEventListener("mouseenter", () => {
                  mainVideo.play();
                });
               
                // Al hacer hover en una miniatura, cambia el video principal
                miniaturas.forEach((miniatura) => {
                  miniatura.addEventListener("mouseenter", () => {
                    mainVideo.src = miniatura.src;
                    mainVideo.load();
                    mainVideo.play();
                  });
                });
              </script>
            
          
              <!-- Columna 2: Texto -->
              <div class="info-text">
                <h2>Title</h2>
                <p>main text.</p>
                <a href="curso.html" class="btn-info">Ver Cursos</a>
              </div>
            </div>
          </section>
        <!-- Style seccion 2 -->
          <style>
            .info-section {
            padding: 80px 40px;
            background-color: #f0f0f0;
            }

            .info-container {
            display: flex;
            position: relative;
            flex-wrap: wrap;
            align-items: center;
            justify-content: center;
            max-width: 1200px;
            margin: 0 auto;
            gap: 40px;
            }

            .info-video video {
            width: 100%;
            max-width: 500px;
            height: 450px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }

            .miniaturas {
              position: absolute;
              top: 103%;
              left: 13%;
              display: flex;
              justify-content: center;
              gap: 10px;
            }

            .miniatura {
              width: 100px;
              height: 60px;
              cursor: pointer;
              object-fit: cover;
              border: 2px;
              border-radius: 10px;
              transition: transform 0.2s;
            }

            .miniatura:hover {
              transform: scale(1.05);
              border-color: #333;
            }
            


            .info-text {
            max-width: 500px;
            }

            .info-text h2 {
            font-size: 2rem;
            margin-bottom: 20px;
            color: #333;
            }

            .info-text p {
            font-size: 1.1rem;
            margin-bottom: 20px;
            color: #555;
            }

            .btn-info {
            display: inline-block;
            padding: 10px 20px;
            background-color: #222;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            font-weight: bold;
            transition: background-color 0.3s ease;
            }

            .columna2 button:hover {
            background-color: #0056b3;
            }

          </style>

I’m trying to set up a Vite monorepo with HMR behind an Nginx reverse proxy — keep getting “Too Many Redirects”

I’m setting up a monorepo project that serves multiple Vite apps behind Nginx using reverse proxies. My goal is to support Hot Module Replacement (HMR) in development.

What I tried
I have two Vite apps:

One served from /

One served from /app/

When I reverse-proxy the first app to /, it works fine.
But when I try to reverse-proxy the second app to /app/, I always get a “Too Many Redirects” error in the browser.

To simplify debugging, I focused on a single Vite app and configured it to be accessible via http://localhost/app/ through Nginx. But I still get the redirect loop.

Vite config

//worko-ui-react/vite.config.ts

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import compression from "vite-plugin-compression";

import path from "path";
// https://vite.dev/config/

export default defineConfig({
  plugins: [react(), compression()],
  envDir: "./environments", // Manually specify the directory where the environment files are located
  envPrefix: "APP_", // Manually specify the prefix for the environment variables
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"), // Add alias for `src`
      "@Assets": path.resolve(__dirname, "src/assets/assets.ts"),
      "@Components": path.resolve(__dirname, "src/components"),
      "@Context": path.resolve(__dirname, "src/context"),
      "@Enums": path.resolve(__dirname, "src/types/enums"),
      "@Hooks": path.resolve(__dirname, "src/hooks"),
      "@Interfaces": path.resolve(__dirname, "src/types/interface"),
      "@Layouts": path.resolve(__dirname, "src/layouts"),
      "@Pages": path.resolve(__dirname, "src/pages"),
      "@Styles": path.resolve(__dirname, "src/styles"),
      "@Services": path.resolve(__dirname, "src/services"),
      "@Utils": path.resolve(__dirname, "src/utils"),
      "@Views": path.resolve(__dirname, "src/views"),
      "@Routes": path.resolve(__dirname, "src/routes.ts"),
      "lib-worko-ai": path.resolve(__dirname, "../../packages/lib-worko-ai/src"),
      "@LibWorko": path.resolve(__dirname, "../../packages/lib-worko-ai/src"),
    },
  },
  optimizeDeps: {
    exclude: ["lib-worko-ai"],
  },
  server: {
    fs: {
      allow: [".."],
    },
    proxy: {
      "/cognito": {
        target: "https://cognito-idp.ap-south-1.amazonaws.com",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^/cognito/, ""),
      },
    },
    host: "0.0.0.0", // listen on all interfaces (for proxy)
    port: 3001, // ensure it runs on the expected port
    strictPort: true, // do not fallback to a different port,
    open: true, // Manually open the browser window upon starting the server
  },
  base: "/app/",
});

Routes.tsx

  const AppRoutes = createBrowserRouter([
  {
    path: "/",
    // errorElement: <ErrorFallback />,
    element: <MainLayout />,
    children: [
{
    path: "auth/*",
    element: (
      <Suspense fallback={<MainLoader />}>
        <AuthRouter />
      </Suspense>
    ),
  },
  //   {path: 'dashboard/*', element: <DashboardRedirect />},
  { path: "*", element: <PageNotFound /> },
],
{
  basename:"/app",
});

export default AppRoutes;

Nginx config

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

server {
    listen       80;
    server_name  localhost;

    location /app/ {
        proxy_pass http://127.0.0.1:3001/;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }
}
    
}

How can I restrict screenshots and screen recording in my React Native app (Android, iOS, macOS, Windows, Web)

I’m currently working on an Admin Portal application using React Native, and I need to prevent users from taking screenshots or recording the screen while using sensitive parts of the app.

My app is expected to run on the following platforms:

  1. Android
  2. iOS
  3. macOS
  4. Windows
  5. Web (via React Native for Web or a separate frontend)

I want to ensure that certain screens (like admin views or confidential data displays) are protected from being captured either via screenshot or screen recording. I’ve done some research but haven’t found a unified, cross-platform solution yet. I’m okay with using native modules or platform-specific implementations as needed.

My questions:

  • Android: How do I disable screenshots and screen recording for specific screens or globally in React Native?
  • iOS: Is it possible to detect or block screen recording or screenshots programmatically in iOS via React Native?
  • macOS & Windows (Desktop): What are the available APIs or techniques to restrict screen capture in Electron or React Native for Windows/macOS?
  • Web: Are there any reliable techniques (e.g., CSS, JavaScript) to discourage or prevent screen recording or screenshots on web apps?

My setup:

  • React Native version: [Please insert version here]
  • Using Expo: [Yes/No]
  • Platforms: Android (Java/Kotlin), iOS (Obj-C/Swift), Web (React), Desktop (Electron or RN-Windows/macOS)

Any help, libraries, native code suggestions, or workarounds for any of these platforms would be much appreciated.

Auto fit for Y axis doesn’t work as expected

I noticed that under some circumstances the auto fit of the Y axis doesn’t work (even when invoking fit method manually).
It seems to be related to traces not having the same amount of points (length).
Zooming in the highlighted area won’t fit the Y axis:

first image

After you select the highlighted area from the previous image, I would expect the Y axis to automatically fit to the new data, but it doesn’t:

second image

This is my code:

import {
    emptyFill,
    htmlTextRenderer,
    lightningChart,
} from '@lightningChart/lcjs'

const chart = lightningChart({
    license: '',
    licenseInformation: {
        appTitle: 'LightningChart JS Trial',
        company: 'LightningChart Ltd.',
    },
    sharedContextOptions: {
        // Shared canvas mode for mozilla
        useIndividualCanvas: false,
    },
})
    .ChartXY({
        container: document.getElementById('chart-container') as HTMLDivElement,
        textRenderer: htmlTextRenderer,
        defaultAxisX: {
            type: 'linear-highPrecision',
        },
    })
    .setTitleFillStyle(emptyFill)
    .setPadding({ right: 40 })

const s1 = [
    {
        "x": "2022-02-01T00:00:00.000Z",
        "y": 260002.5
    },
    {
        "x": "2022-03-01T00:00:00.000Z",
        "y": 485898.3
    },
    {
        "x": "2022-03-31T23:00:00.000Z",
        "y": 363026.4
    },
    {
        "x": "2022-04-30T23:00:00.000Z",
        "y": 472677.5
    },
    {
        "x": "2022-05-31T23:00:00.000Z",
        "y": 426169.9
    },
    {
        "x": "2022-06-30T23:00:00.000Z",
        "y": 325075.9
    },
    {
        "x": "2022-07-31T23:00:00.000Z",
        "y": 361082.8
    },
    {
        "x": "2022-08-31T23:00:00.000Z",
        "y": 436457.9
    },
    {
        "x": "2022-09-30T23:00:00.000Z",
        "y": 385213.5
    },
    {
        "x": "2022-11-01T00:00:00.000Z",
        "y": 314850.3
    },
    {
        "x": "2022-12-01T00:00:00.000Z",
        "y": 248065.5
    },

]
const s2 = [
    {
        "x": "2021-06-30T23:00:00.000Z",
        "y": 104446.82
    },
    {
        "x": "2021-07-31T23:00:00.000Z",
        "y": 123269.35
    },
    {
        "x": "2021-08-31T23:00:00.000Z",
        "y": 125170.53
    },
    {
        "x": "2021-09-30T23:00:00.000Z",
        "y": 120678.58
    },
    {
        "x": "2021-11-01T00:00:00.000Z",
        "y": 129243.9
    },
    {
        "x": "2021-12-01T00:00:00.000Z",
        "y": 105639.28
    },
    {
        "x": "2022-01-01T00:00:00.000Z",
        "y": 130527.04
    },
    {
        "x": "2022-02-01T00:00:00.000Z",
        "y": 134972.79
    },
    {
        "x": "2022-03-01T00:00:00.000Z",
        "y": 160231.71
    },
    {
        "x": "2022-03-31T23:00:00.000Z",
        "y": 115727.49
    },
    {
        "x": "2022-04-30T23:00:00.000Z",
        "y": 149579.34
    },
    {
        "x": "2022-05-31T23:00:00.000Z",
        "y": 132888.5
    },
    {
        "x": "2022-06-30T23:00:00.000Z",
        "y": 85069.42
    },
    {
        "x": "2022-07-31T23:00:00.000Z",
        "y": 58082.97
    },
    {
        "x": "2022-08-31T23:00:00.000Z",
        "y": 127669.92
    },
    {
        "x": "2022-09-30T23:00:00.000Z",
        "y": 112249.18
    },
    {
        "x": "2022-11-01T00:00:00.000Z",
        "y": 88587.61
    },
    {
        "x": "2022-12-01T00:00:00.000Z",
        "y": 64808.21
    },
]

const series1 = chart
    .addPointLineAreaSeries({
        dataPattern: 'ProgressiveX',
    })
    .appendJSON(s1)

const series2 = chart
    .addPointLineAreaSeries({
        dataPattern: 'ProgressiveX',
    })
    .appendJSON(s2)

Thanks.

I want to initialize my input signal with a default class and some data manipulations

I am using this package, ang-jsoneditor, which contains the below initialization code.

@Component({ ... })
export class AppComponent {
  public editorOptions: JsonEditorOptions;
  public data: any;
  // optional
  @ViewChild(JsonEditorComponent, { static: false }) editor: JsonEditorComponent;

  constructor() {
    this.editorOptions = new JsonEditorOptions()
    this.editorOptions.modes = ['code', 'text', 'tree', 'view']; // set all allowed modes
    ...
  }

}

I want to convert this to the new signals method of handling inputs, but I cant seem to figure out how to move the initialization code inside the input signal.

@Component({ ... })
export class AppComponent {
  public editorOptions = input<JsonEditorOptions>({});
  public data: any = inpu.required();
  // optional
  editor = viewChild(JsonEditorComponent);

  constructor() {
    // how do I move this code inside the `input` default value?
    this.editorOptions = new JsonEditorOptions()
    this.editorOptions.modes = ['code', 'text', 'tree', 'view']; // set all allowed modes
    ...
  }

}

Mastercard Payment Gateway Hosted Checkout not loading—only shows loading animation in Flutter WebView (Session ID passed)

I’m integrating Mastercard’s Payment Gateway Hosted Checkout in my Flutter app using a WebView. The idea is to open the Mastercard payment portal by passing a session ID I get from the backend (API version 83, test environment).

My issue:
The payment portal loads only a loading animation—the actual payment page never appears. Console logs show some errors (see below).

My Dart/Flutter Code:

void loadPaymentPage() {
  print('Step: Starting loadPaymentPage at ${DateTime.now()}');
  if (sessionId == null) {
    print('Step: Session ID is null - Aborting loadPaymentPage at ${DateTime.now()}');
    return;
  }
  print('Step: Session ID available - $sessionId at ${DateTime.now()}');

  String htmlContent = """
<!DOCTYPE html>
<html>
<head>
  <script src="https://test-xxx.gateway.mastercard.com/static/checkout/checkout.min.js"
          data-error="errorCallback"
          data-cancel="cancelCallback"></script>
  <script type="text/javascript">
    function errorCallback(error) {
      console.log(JSON.stringify(error));
    }
    function cancelCallback() {
      console.log('Payment cancelled');
    }
    window.onload = function() {
      Checkout.configure({
        session: {
          id: '$sessionId'
        }
      });
      Checkout.showPaymentPage();
    };
  </script>
</head>
<body>
  <p>Loading payment...</p>
  <div id="embed-target"></div>
  <input type="button" value="Pay with Embedded Page" onclick="Checkout.showEmbeddedPage('#embed-target');" />
  <input type="button" value="Pay with Payment Page" onclick=";" />
</body>
</html>
""";

  _controller.loadHtmlString(htmlContent);
}

Console Log Errors

Possible Unhandled Promise Rejection: [object DOMException]
Unrecognized feature: 'payment'.
Uncaught SecurityError: Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document.

Using Flutter WebView to load the HTML.

API Reference: https://test-gateway.mastercard.com/api/documentation/apiDocumentation/checkout/version/83/api.html

Mastercard portal shows only a loading spinner, nothing else happens.

How do I fix the Mastercard payment gateway portal not loading in a Flutter WebView when passing a session ID?
Are there special WebView settings, permissions, or workarounds needed for Mastercard’s Hosted Checkout to work in Flutter?

Microservices user auth with better-auth in Expressjs

I am trying to build a software based on a microservices infrastructure and I just learned how powerful better-auth is, however I don’t know how to handle route protection in a microservices approach, so for example let’s say that there is one Expressjs app that is in charge on user authentication, and I have another Expressjs app for a service that is going to let users upload files, in the client I am using Reactjs, how would I protect the file service app routes if it doesn’t have a direct connection to the users database because is a different service connected to other DB, should I fetch the user auth service? isn’t there an easier way like JWT? does anybody have an example I can watch? I’ve tried many different solutions but most don’t work or are inefficient, help please

I tried something like this:

file service (this is just to test the user authentication system):

import express from "express";
import { fromNodeHeaders, toNodeHandler } from "better-auth/node";
import { auth, createAuthMiddleware } from "./auth";
import { isAuthenticated } from "./middleware/user";

const app = express();
const port = 3001;

// Mount express json middleware after Better Auth handler
// or only apply it to routes that don't interact with Better Auth
app.use(express.json());

app.get("/protected", createAuthMiddleware, (req, res) => {
  res.send("Hello");
  return;
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
import { betterAuth } from "better-auth";
import { bearer } from "better-auth/plugins";
import { NextFunction, Request, Response } from "express";

// Create a singleton instance
export const auth = betterAuth({
  plugins: [
    bearer({
      requireSignature: true,
    }),
  ],
});

export const createAuthMiddleware = async (
  req: any,
  res: Response,
  next: NextFunction
) => {
  try {
    const session = await auth.api.getSession({
      headers: req.headers,
    });

    if (!session) {
      res.status(401).json({ error: "Unauthorized" });
      return;
    }

    req.session = session;
    next();
  } catch (error) {
    res.status(401).json({ error: "Invalid token" });
    return;
  }
};

user authentication service:

import express from "express";
import { fromNodeHeaders, toNodeHandler } from "better-auth/node";
import { auth } from "./auth";
import { isAuthenticated } from "./middleware/user";

const app = express();
const port = 3000;

app.all("/api/auth/*", toNodeHandler(auth)); // For ExpressJS v4
// app.all("/api/auth/*splat", toNodeHandler(auth)); For ExpressJS v5

// Mount express json middleware after Better Auth handler
// or only apply it to routes that don't interact with Better Auth
app.use(express.json());

// Add this middleware before your protected routes
app.use(async (req, res, next) => {
  const session = await auth.api.getSession({
    headers: fromNodeHeaders(req.headers),
  });

  console.log(session);

  if (!session) {
    req.user = null;
    req.session = null;
    return next();
  }

  req.user = session.user;
  req.session = session.session;
  return next();
});

app.get("/protected", isAuthenticated, (req, res) => {
  res.send("Hello");
  return;
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
// If your Prisma file is located elsewhere, you can change the path
import { PrismaClient } from "@prisma/client";
import { bearer } from "better-auth/plugins";

const prisma = new PrismaClient();
export const auth = betterAuth({
  emailAndPassword: {
    enabled: true,
  },
  database: prismaAdapter(prisma, {
    provider: "postgresql", // or "mysql", "postgresql", ...etc
  }),
  plugins: [
    bearer({
      requireSignature: true,
    }),
  ],
});

Unable to use fields in jsGrid from import

I am puzzled at how to get this working properly. Have looked at many different ways but unable to get my jsGrid to load properly.

  • Java SpringBoot 2.7.18
  • Tomcat Embedded
  • jsGrid 1.5.3
  • jQuery 3.2.1

I have a js-grid-helper.js which has static information for the columns:

export var TABLE_COLUMNS = [
    { name: 'column_1',  title: 'Column 1',  type: 'text'}
    ,{ name: 'column_2',    title: 'Column 2', type: 'text'}
    ,{ name: 'column_3', title: 'Column 3', type: 'text'}
];

I import this into my page.js and then reference it in my jsGrid initialization

import {
    TABLE_COLUMNS
} from "../components/jsgrid-helpers.js";

$('#my-table').jsGrid({
    width: '100%',
    height:'700px',

    filtering:true,
    editing:  false,
    paging:   true,
    autoload: false,
    sorting:  true,
    pageLoading: true,
    pageSize: 20,
    controller: jsGridController,
    fields: TABLE_COLUMNS,

    rowClick: function(args){
    },
    onDataLoading: function(args){
    },
    onDataLoaded: function(args){
    }
});

I get an error for the following, because TABLE_COLUMNS is undefined

jsgrid.min.js:7 Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at new d (jsgrid.min.js:7:30218)
    at jsgrid.min.js:7:3982
    at r.map (jquery-3.2.1.min.js:2:3309)
    at d._initFields (jsgrid.min.js:7:3882)
    at d._init (jsgrid.min.js:7:3131)
    at new d (jsgrid.min.js:7:200)
    at HTMLDivElement.<anonymous> (jsgrid.min.js:7:22224)
    at r.each (jquery-3.2.1.min.js:2:2715)
    at r.fn.init.each (jquery-3.2.1.min.js:2:1003)
    at b.fn.jsGrid (jsgrid.min.js:7:22040)
d   @   jsgrid.min.js:7
(anonymous) @   jsgrid.min.js:7
map @   jquery-3.2.1.min.js:2
_initFields @   jsgrid.min.js:7
_init   @   jsgrid.min.js:7
d   @   jsgrid.min.js:7
(anonymous) @   jsgrid.min.js:7
each    @   jquery-3.2.1.min.js:2
each    @   jquery-3.2.1.min.js:2
b.fn.jsGrid @   jsgrid.min.js:7
(anonymous) @   page.js:199

However, if I place the TABLE_COLUMNS in the SAME file it works absolutely fine like so:

var TABLE_COLUMNS = [
    { name: 'column_1',  title: 'Column 1',  type: 'text'}
    ,{ name: 'column_2',    title: 'Column 2', type: 'text'}
    ,{ name: 'column_3', title: 'Column 3', type: 'text'}
];

$('#my-table').jsGrid({
    width: '100%',
    height:'700px',

    filtering:true,
    editing:  false,
    paging:   true,
    autoload: false,
    sorting:  true,
    pageLoading: true,
    pageSize: 20,
    controller: jsGridController,
    fields: TABLE_COLUMNS,

    rowClick: function(args){
    },
    onDataLoading: function(args){
    },
    onDataLoaded: function(args){
    }
});

Is this a timing thing, ES Module thing, or a jsGrid library thing? Cannot figure it out. I have also tried setting it to when the document is ready and also a delay of a few seconds and neither works.