InvalidTokenError: Invalid Compact JWS (Auth0 with ReactJS and NodeJs Express)

tried reading the similar issues in auth0 community and stack overflow but it doesn’t fix my problem. So trying to create myself questions and direct ask here.

the real-estate-api is the Custom API i create under applications->APIs, that’s the API audience.

the client id im using in react js is the SPA one:

i keep getting Invalid Compact JWS.

React JS:

import { Auth0Provider, useAuth0 } from "@auth0/auth0-react";

function LoginButton() {
  const { loginWithRedirect } = useAuth0();
  return (
    <button
      onClick={() =>
        loginWithRedirect({
          authorizationParams: {
            scope: "read:current_user email",
            screen_hint: "signin",
          },
        })
      }
    >
      Log In
    </button>
  );
}

function LogoutButton() {
  const { logout } = useAuth0();
  return <button onClick={() => logout()}>Log Out</button>;
}

function App() {
  const { isAuthenticated, isLoading, user, getAccessTokenSilently } =
    useAuth0();

  const getToken = async () => {
    try {
      const token = await getAccessTokenSilently({
        authorizationParams: {
          audience: "real-estate-api",
        },
      });

      console.log("Token:", token);
      return token;
    } catch (error) {
      console.error("Error getting token:", error);
    }
  };

  if (isLoading) {
    return <div>Loading...</div>;
  }

  return (
    <>
      {!isAuthenticated ? (
        <LoginButton />
      ) : (
        <div>
          <LogoutButton />
          <div>Hello, {user?.name}</div>
          <button onClick={getToken}>Get Token</button>
        </div>
      )}
    </>
  );
}

// Wrap your default export with Auth0Provider
export default function AppWithAuth() {
  return (
    <Auth0Provider
      domain="dev-q8w.....uk.auth0.com"
      clientId="vbvi......"
      authorizationParams={{
        redirect_uri: window.location.origin,
      }}
    >
      <App />
    </Auth0Provider>
  );
}

Node JS:

auth.ts:

import { auth } from 'express-oauth2-jwt-bearer';

export const jwtCheck = auth({
  issuerBaseURL: process.env.AUTH0_ISSUER_BASE_URL,
  audience: process.env.AUTH0_AUDIENCE,
});

authenticate.ts:

import httpStatus from 'http-status';

import ApiError from '@utils/handle-api-error';
import { NextFunction, Request, Response } from 'express';
import { UserService } from '@service/user-service';
import { UserRole } from '@common/interface/enums/user.enum';
import { jwtCheck } from '@utils/config/auth';
import { Auth0Request } from '@common/interface/auth.interface';

const userService = new UserService();

export const authMiddleware = (req: Request, res: Response, next: NextFunction): void => {
  console.log('Received auth header:', req.headers.authorization);
  console.log('Auth header length:', req.headers.authorization?.length);
  jwtCheck(req as Request, res, (err: string) => {
    console.log(err);
    if (err) return next(new ApiError(httpStatus.UNAUTHORIZED, 'Unauthorized'));

    const auth = (req as unknown as Auth0Request).auth;

    const userInfo = {
      auth0Id: auth.sub,
      email: auth.email,
    };

    req.user = userInfo;
    next();
  });
};

user-route.ts:

import express from 'express';

import UserController from '@controller/user-controller';

import { validate } from '@middleware/validate';
import { signupSchema, updateUserSchema } from '@utils/validations/user.validation.schema';
import { authMiddleware } from '@middleware/authenticate';

const router = express.Router();

const user = new UserController();

router.post('/register', authMiddleware, validate(signupSchema), user.register);
router.get('/me', authMiddleware, user.getUserById);
router.put('/me', authMiddleware, validate(updateUserSchema), user.updateUserInfo);

export default router;

backend .env:

AUTH0_ISSUER_BASE_URL=https://dev-q8wet.....uk.auth0.com/
AUTH0_AUDIENCE=real-estate-api

complete error:

InvalidTokenError: Invalid Compact JWS
    at C:Users...DocumentsPicturesnode_modulesexpress-oauth2-jwt-bearerdistindex.js:300:19
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async C:Users...DocumentsPicturesnode_modulesexpress-oauth2-jwt-bearerdistindex.js:403:24 {
  status: 401,
  statusCode: 401,
  headers: {
    'WWW-Authenticate': 'Bearer realm="api", error="invalid_token", error_description="Invalid Compact JWS"'
  },
  code: 'invalid_token'

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật