How To Measure Your Server's Round-trip Time In Remix (React)
Tags: react, javascript, typescript, webdev
Published: 2023-05-26 11:57:38

---
title: How To Measure Your Server's Round-trip Time In Remix (React)
published: true
description: 
tags: react, javascript, typescript, webdev
cover_image: https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/BXOXnQ26B7o/upload/9b6d496e4a2a458d868e4ca66f0fe4f5.jpeg?w=1600&h=840&fit=crop&crop=entropy&auto=compress,format&format=webp
# Use a ratio of 100:42 for best results.
# published_at: 2023-05-26 11:50 +0000
canonical_ref: https://pmbanugo.me/how-to-measure-your-servers-round-trip-time-in-remix-react
---

## Problem

In the world of web development, every millisecond counts. Web developers are constantly driven to achieve maximum speed and efficiency. They meticulously measure [round-trip time (RTT)](https://www.imperva.com/learn/performance/round-trip-time-rtt/) and other related metrics to understand page load time and network latency. However, there's a challenge: the further our server is from the user, the longer it takes to respond. So, how do we tackle this hurdle and measure network latency accurately?

![Latency Diagram](https://cdn.hashnode.com/res/hashnode/image/upload/v1685101428165/5ce051a6-c147-49d1-824a-dd948b980aa5.webp)

## Solution

We can measure the full network transfer time between the browser and the Remix server by calculating the difference between when the request was made from the browser, and when a response was gotten from the server. We can achieve this by creating a function that makes a request to a resource and calculates the time (in milliseconds) it takes to fulfil it. We'll add a page that executes that function every second and the result will be displayed in the browser.

Sounds too theoretical? Let's get started with the code 👨🏽‍💻

We're going to start by defining the function that pings the server and calculates the duration. Add the following `pingServer()` function to your code. You can choose to put it anywhere you prefer, for example, in a separate file called **ping.js**.

```javascript
const pingServer = async () => {
  try {
    const startTime = new Date().getTime();
    await fetch("/ping");
    const endTime = new Date().getTime();
    const responseTime = endTime - startTime;

    return `Server responded in ${responseTime}ms`;
  } catch (error) {
    console.error("Ping failed:", error);
    return "Ping failed";
  }
};
```

The `pingServer()` function calls the `/ping` route, calculates the duration, and returns a message that contains the measured time. If the server can't be reached, then an error message is returned.

Next, we're going to add a `/ping` resource route that returns an empty HTTP response. Add a new file **/routes/ping.js** and paste the code snippet below into it.

```javascript
export async function loader() {
  return new Response(null, {
    status: 200,
    headers: {
      "Cache-Control": "no-store",
    },
  });
}
```

Finally, add a page that would display a button to trigger the `pingServer()` function and display the result in the browser.

```jsx
export default function Index() {
  const [message, setMessage] = useState("");
  return (
    <div>
      <h1>Ping Test</h1>
      <button
        disabled={message !== ""}
        onClick={async () => {
          setInterval(async () => {
            setMessage(await pingServer());
          }, 1000);
        }}
      >
        Click to start ping
      </button>
      <p>{message}</p>
    </div>
  );
}
```

That's all you need to add a page that constantly pings the server and calculates the round-trip time.

Let's see our solution in action! The GIF below shows me running my Remix app with the ping time measured and displayed in the browser.

![Demo - calculate ping time](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5bujxk91ylj1tjx2tj4f.gif)

## Conclusion

You've seen how to measure and display the latency for your Remix application. You can use that page for diagnostic purposes with your users or as a support engineer. When you have the needed data, the next step is to decide how to improve the user experience and decrease latency. That begs the question; Are there ways to ensure a lightning-fast web experience, regardless of distance?

Regarding latency, one solution would be to distribute the servers geographically closer to your users. How you achieve that would vary depending on how you're hosting the application. I'll discuss more about this solution in my next post, so stay tuned 😎