Search code examples
javascriptwebsocketcloudflare

Cloudflare websocket returns only one value of Date.now()


Ok so i made a websocket in cloudflare workers which creates a variable connectime when client connects with Date.now() and also when it disconnects. Then it calculates the difference and logs client disconnected after a connection of --ms, where -- is the difference between times..


addEventListener('fetch', (event) => {
    event.respondWith(handleRequest(event.request))
})


async function handleRequest(request) {
    const connecttime = Date.now();


const upgradeHeader = request.headers.get('Upgrade');
    if (!upgradeHeader || upgradeHeader !== 'websocket') {
      return new Response('Expected Upgrade: websocket', { status: 426 });
    }
  
    const webSocketPair = new WebSocketPair();
    const [client, server] = Object.values(webSocketPair);
        server.accept();

//Do something



server.addEventListener('close', event => {
        const endtime = Date.now();
        console.log(endtime);
        const contime = endtime-connecttime;
        console.log("client disconnected after a connection of " + contime + "ms");
    })



The problem is it returns 0 value;

client disconnected after a connection of 0ms


Solution

  • This is by design and part of the security model of Cloudflare Workers - from the documentation:

    Workers is designed to make it impossible for code to measure its own execution time locally. For example, the value returned by Date.now() is locked in place while code is executing. No other timers are provided.

    For a full explanation, I recommend the following documentation page