Send the log to local loki server from react js

My Loki and Promtail server up and running. I want to send the log from my react js front end application. if try to post data it will give cors error. even i try to post ngnix proxy server also not working. how to achive that ?

const postLogsToLoki = async () => {
  const lokiURL = 'http://localhost:3100/loki/api/v1/push'; // Replace with your Loki URL
  const headers = {
    'Content-Type': 'application/json',
    // Add any other custom headers you need
    'Access-Control-Allow-Origin':"*",
    'Access-Control-Allow-Methods': 'GET, POST',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization'
  };

  const logData = {
    streams: [
      {
        stream: {
          lablename: 'test lable', // Replace with your labels
        },
        values: [
          [new Date().toISOString(), 'post message from culture'],
          // Add more log entries as needed
        ],
      },
    ],
  };

  try {
    const response = await axios.post(lokiURL, logData,{ headers }).catch((e)=>{
      console.log(e);
    });
    console.log('Log posting successful:', response);
  } catch (error) {
    console.error('Error posting logs to Loki:', error);
  }
};

@mohamedisak

As you can see here Grafana Loki HTTP API you use the right endpoint and structure.
But the date value produced by new Date().toISOString() produces a date like this: 2024-01-30T20:46:55.129Z, which is not valid.

Date.now() produces a timestamp in millis, but you need it in nano.
So you need to do Date.now() * 1000 * 1000 for nanoseconds.

But I think that still fails, because of the CORS headers. The server determines the accepted CORS headers and I cannot find settings for that on Loki.
So I did not test it, but I guess it will fail.

Can you open the developer tools of your browser and see what kind of error is reported for the request send?

You mentioned about an Nginx reverse proxy. Does that reverse proxy add CORS headers in the response?
Here is how you can add CORS headers with Nginx: enable cross-origin resource sharing

Other option is to use Grafana Faro Web SDK: https://github.com/grafana/faro-web-sdk
That can send the data to Grafana Cloud and Grafana Agent with https://grafana.com/docs/agent/latest/static/configuration/integrations/integrations-next/app-agent-receiver-config/
This can receive the data and push the data to loki.

2 Likes