How to prevent TransactionExpiredBlockheightExceededError while swapping using Jupiter api in solana

I have integrated Jupiter swap api on my react app and swapping tokens using Jupiter api but the swap is working sometimes and not working sometimes with TransactionExpiredBlockheightExceededError.
I was tried to raise prioritizationFeeLamports but not working well yet.

Here are my code.

  const JUPITER_QUOTE_API = 'https://quote-api.jup.ag/v6/quote';
  const JUPITER_SWAP_API = 'https://quote-api.jup.ag/v6/swap';


  // Step 1: Fetch swap info from Jupiter
  const fetchSwapInfo = async (inputMint: string, outputMint: string, amount: number) => {
    const url = `${JUPITER_QUOTE_API}?inputMint=${inputMint}&outputMint=${outputMint}&amount=${amount}&slippageBps=150&&swapMode=ExactIn&onlyDirectRoutes=false&asLegacyTransaction=false&maxAccounts=64&minimizeSlippage=false`;
    const response = await fetch(url);
    const data = await response.json();
    return {
        inAmount: data.inAmount,
        otherAmountThreshold: data.otherAmountThreshold,
        quoteResponse: data,
    };
  };

  // Step 2: Fetch swap transaction from Jupiter
  const fetchSwapTransaction = async (
    walletAddress: PublicKey | null,
    recipientAddress: string,
    swapInfo: any
  ) => {
    if (!walletAddress || !recipientAddress || !swapInfo?.quoteResponse) {
        throw new Error('Invalid parameters: Ensure walletAddress, recipientAddress, and swapInfo are defined.');
    }

    const requestBody = {
        userPublicKey: walletAddress.toBase58(),
        destinationTokenAccount: recipientAddress,
        useSharedAccounts: true,
        quoteResponse: swapInfo.quoteResponse,
        allowOptimizedWrappedSolTokenAccount : true,
        asLegacyTransaction : false,
        dynamicComputeUnitLimit : true,
        prioritizationFeeLamports:{
          priorityLevelWithMaxLamports:{
            global:false,
            maxLamports: 4000000,
            priorityLevel: "veryHigh"
          }
        },
        wrapAndUnwrapSol: true,
    };

    const response = await fetch(JUPITER_SWAP_API, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(requestBody),
    });

    if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`Error fetching swap transaction: ${errorText}`);
    }

    const { swapTransaction, lastValidBlockHeight } = await response.json();
    return { swapTransaction, lastValidBlockHeight };
  };
  // Function to find the fee account and get serialized transactions for the swap

  // Step 3: Send transaction to Solana blockchain
  const sendTransaction = async (swapTransaction: string,  walletAdapter: WalletAdapter) => {
      let  latestBlockHash = await connection.getLatestBlockhash();

      // deserialize the transaction
      const swapTransactionBuf = Buffer.from(swapTransaction, 'base64');
      var transaction = VersionedTransaction.deserialize(swapTransactionBuf);
      console.log(transaction);

      // Set the recent blockhash
      transaction.message.recentBlockhash = latestBlockHash.blockhash;
      
      const signedTransaction = await (walletAdapter as any).signTransaction(transaction);

      // Execute the transaction
      const rawTransaction = transaction.serialize()

      latestBlockHash = await connection.getLatestBlockhash();
      const txid = await connection.sendRawTransaction(rawTransaction, {
        skipPreflight: false,
        maxRetries: 5,
      });
      // get the latest block hash
      console.log(`https://solscan.io/tx/${txid}`);
      setIsConfirming(true);
      await connection.confirmTransaction({
        blockhash: latestBlockHash.blockhash,
        lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
        signature: txid
      });
      setIsConfirming(false);
      setTransactionLink(`https://solscan.io/tx/${txid}`);
      console.log(`https://solscan.io/tx/${txid}`);
      return txid;
  };

  // Step 4: Main function to swap and send token
  const swapAndSendToken = async (
    walletAdapter: WalletAdapter,
    recipientAddress: string,
    inputMint: string,
    outputMint: string,
    amount: number
  ) => {
    try {
        const walletPublicKey = walletAdapter.publicKey;

        // Step 1: Fetch swap info
        const swapInfo = await fetchSwapInfo(inputMint, outputMint, amount);

        // Step 2: Fetch the swap transaction
        const { swapTransaction, lastValidBlockHeight } = await fetchSwapTransaction(walletPublicKey, recipientAddress, swapInfo);
        console.log(swapTransaction);
        // Step 3: Send the transaction to the blockchain
        let txid = await sendTransaction(swapTransaction,  walletAdapter);

        console.log('$ sent successfully!n https://solscan.io/tx/' + txid);

        console.log('Swap and send transaction completed successfully.');
        setIsSuccessful(true);
    } catch (error) {
        console.error('Error during swap and send:', error);
        setIsBroken(true);
        //alert("Failed! " + error.message);
    }

  };
  const payCoin = async () => {
    if(isProcessing) return;
    setIsProcessing(true);

    const inputToken = token;
    var targetTokenName = data?.transactions?.currency;    
    if(inputToken.name == targetTokenName)
    {
      alert("direct token send, coming soon!")
    }
    else {
      var targetUnitNumber = 0;
      var targetMint = "";
      Tokens.forEach((element) => {
        if (element.name == targetTokenName) {
          targetMint = element.mintAddress;
          targetUnitNumber = element.decimals;
        }
      });
      var merchant_address = data?.transactions?.merchant_address
      //the public solana address
      const accountPublicKey = new PublicKey(
        merchant_address
      );
  
      //mintAccount = the token mint address
      const mintAccount = new PublicKey(
        targetMint
      );
      const account = await connection.getTokenAccountsByOwner(accountPublicKey, {
        mint: mintAccount});
      if(account.value.length==0) {
        alert("can not find merchant account address for this spl token!");
      }
      else {
        await swapAndSendToken(
          walletAdapter,
          account.value[0].pubkey.toString(), // Merchant's USDC address
          inputToken.mintAddress, // Input mint address
          targetMint, // Output mint address
          tokenAmount * (10 ** inputToken.decimals) // Example: 0.1 USDC in micro-lamports
        );
      }

    }
    setIsProcessing(false);
  }

In this code, I added prioritizationFeeLamports and tried to raise the fee to prevent failing transaction but it’s failing many times.

How to raise the fee amount for Jupiter transaction?

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