@codebundlesbyvik/ntp-sync
v1.1.3
Published
A basic Network Time Protocol synchronization library.
Maintainers
Readme
NTP Sync
A basic Network Time Protocol synchronization library.
Table of Contents
Usage
If you're not familiar with NTP yet then you'll probably want to read up on what the values mean first.
# Install package from npm
npm install @codebundlesbyvik/ntp-syncIf you're not using a module bundler then:
- Download the latest
@codebundlesbyvik/js-helpersrelease from GitHub or load it directly via jsdelivr. - Download the latest
@codebundlesbyvik/ntp-syncrelease from GitHub or load it directly via jsdelivr.
For the example below I assume the main JavaScript file is processed by a module bundler.
import Ntp, { convertUnixTimeFormatToMs } from "@codebundlesbyvik/ntp-sync";
const ntp = new Ntp({
t1EndpointUrl: "./api/ntp/get-server-time.php",
t1CalcFn: async function (response: Response) {
const fetchedData = (await response.json()) as unknown;
const isValidData = (data: unknown): data is { received_time: number } =>
typeof data === "object" && data !== null && "received_time" in data;
return isValidData(fetchedData)
? convertUnixTimeFormatToMs(fetchedData.received_time)
: null;
},
// Providing a t2CalcFn for greater accuracy is recommended but not required.
t2CalcFn: function (responseHeaders: Headers) {
// Header value example: t=1747777363406069 D=110
const header = responseHeaders.get("Response-Timing");
if (!header) return null;
const reqReceivedTime = /\bt=([0-9]+)\b/.exec(header);
const reqProcessingTime = /\bD=([0-9]+)\b/.exec(header);
if (!reqReceivedTime || !reqProcessingTime) return null;
const respTransmitTime =
Number.parseInt(reqReceivedTime[1]) + Number.parseInt(reqProcessingTime[1]);
return convertUnixTimeFormatToMs(respTransmitTime);
},
});
const values = await this.ntp.sync();
// {
// clientOffset: -296,
// correctedDate: 1747828823908,
// roundTripDelay: 591,
// }Compatibility
Requires an ECMAScript 2022 (ES13) compatible environment. Practically speaking, all browsers released in 2021 and onwards are fully supported.
Instance options
| Property | Type | Default | Description |
| :-------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- |
| t1EndpointUrl Required if t1Endpoint not provided. | string | - | URL of the endpoint to retrieve t1 from. |
| t1Endpoint Required if t1EndpointUrl not provided. | @codebundlesbyvik/js-helpers fetchWithTimeout parameters | - | Parameters for the fetcher used to retrieve t1. |
| t1CalcFn Required | (response: Response) => Promise<number \| null> | - | Function used to process t1. |
| t2CalcFn | (responseHeaders: Headers) => number \| null | undefined | Function used for calculating t2. Recommended for greater precision. If not provided then t1 = t2. |
| maxSyncAttempts | number | 6 | Maximum amount of t1 fetch requests when .sync() is called (i.e. the amount of times .generateData() is called). |
| requiredOkSyncAttempts | number | 4 | Required amount of successful t1 fetch requests per .sync() call (i.e. the amount of .generateData() calls that must return a HTTP 200 status code). |
Methods
.generateData()
Returns an object containing round-trip delay and client offset.
.sync()
Calls .generateData() at most maxSyncAttempts times, calculates an average of each value and returns them alongside a corrected Unix timestamp.
A helper function convertUnixTimeFormatToMs() is also available and can be used to convert any format Unix timestamp dated after September 9th 2001 to one with millisecond precision.
License
MIT © 2025 Viktor Chin-Kon-Sung
