Updating authentication for OpenTelemetry in React app

Hey everyone! I’m working on a React app and I want to send logs to a collector using OpenTelemetry. The thing is I’m setting my token when the app starts but it only lasts for 5 minutes. I need to find a way to update it smoothly.

Here’s what I’ve got so far:

// Sending logs
logHandler.send({
  level: severity,
  content: log,
  metadata: {
    ...extraInfo,
    logTime: new Date().toISOString(),
  },
});

// Setting up the logger
const logHandler = new LogHandler({ resourceInfo });
const logSender = new CustomLogSender({ endpoint: `${LOG_SERVER}/api`, authHeaders });
logHandler.useProcessor(new LogBatchProcessor(logSender));

const logger = logHandler.createLogger('main-logger');
export { logger };

// Trying to update the token
class DynamicLogSender extends CustomLogSender {
  constructor(endpoint) {
    super({ endpoint });
  }

  transmit(data, onComplete, onFail) {
    this.authHeaders = {
      Token: window.currentToken ?? '',
      MaxConcurrency: '1',
    }
    super.transmit(data, onComplete, onFail);
  }
}

I tried to override the send method but I’m not sure if it’s the best approach. Any ideas on how to handle this token update smoothly? Thanks in advance!

I’ve faced a similar challenge with token expiration in OpenTelemetry for a React application. Instead of overriding the send method, I found it more effective to implement a token refresh mechanism.

Consider creating a separate service that manages token refresh. This service can handle the token expiration logic and provide a method to get the current valid token, which you can then integrate into your CustomLogSender.

Before every transmission, use this service to obtain the latest token. This ensures that you always use a valid token without altering core OpenTelemetry components. Implement proper error handling and retry logic for cases when token refresh fails to maintain a smooth logging experience.

ooh, interesting challenge! have u considered using an interceptor for ur API calls? it could handle token refreshes automatically. what about websockets for real-time updates? curious to hear ur thoughts on these approaches. whats ur app’s main purpose anyways?

hey, been through this. try a custom hook like useToken() to auto-refresh the token and store it in state. then pull the token from state in your logSender before sending. its worked for me in similar cases. cheers!