npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

server-timing-header

v1.9.7

Published

Allow you add metrics via Server-Timing header

Downloads

1,153

Readme

Server-Timing Header

This is middleware for Express that allow you monitor server-side performance in the browser with use of Service-Timing headers.

  • Great for identifying server-side performance issues.
  • Supported in Chrome, Safari and Mozilla.
  • 1.52 KB with all dependencies, minified and gzipped.
  • Tested.

Usage

Step 1: install package.

npm i -S server-timing-header

Step 2: add middleware.

+ const serverTimingMiddleware = require('server-timing-header');
const express = require('express');
const app = express();

+ app.use(serverTimingMiddleware({sendHeaders: (process.env.NODE_ENV !== 'production')}));

Step 3: measure how long take to get data.

app.get('/', function (req, res, next) {
+  req.serverTiming.from('db');
  // fetching data from database
+  req.serverTiming.to('db');
  // …
});

Step 4: check Server-Timing in the network tab of Chrome DevTools.

screenshot from chrome

Examples

Most common use-case — measure time between two points.

const express = require('express');
const serverTimingMiddleware = require('server-timing-header');
const port = 3000;
const app = express();
app.use(serverTimingMiddleware({sendHeaders: (process.env.NODE_ENV !== 'production')}));
app.get('/', function (req, res, next) {
  req.serverTiming.from('db');
  // fetching data from database
  req.serverTiming.to('db');
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

In case we recieve timing from external source we may just add metric we need.

const express = require('express');
const serverTimingMiddleware = require('server-timing-header');
const port = 3000;
const app = express();
app.use(serverTimingMiddleware());
app.get('/', function (req, res, next) {
  // You got time metric from the external source
  req.serverTiming.add('cache', 'Cache Read', 23.2);
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

In some cases you may need to modify data before send it to browser. In example bellow we can't separate time of rendering and time of acquiring data. To make render time more precise we may devide time we use to get data from the rendering time.

const express = require('express');
const serverTimingMiddleware = require('server-timing-header');
const port = 3000;
const app = express();
app.use(serverTimingMiddleware());
app.get('/', function (req, res, next) {
  req.serverTiming.from('render');
    req.serverTiming.from('data');
    // fetching data from database
    req.serverTiming.to('data');
  req.serverTiming.to('render');
});
app.use(function (req, res, next) {
  // If one measurement include other inside you may substract times
  req.serverTiming.addHook('substractDataTimeFromRenderTime', function (metrics) {
    const updated = { ...metrics };
    if (updated.data && updated.render) {
      const renderDuration  = req.serverTiming.calculateDurationSmart(updated.render);
      const dataDuration  = req.serverTiming.calculateDurationSmart(updated.data);
      updated.render.duration = Math.abs(renderDuration - dataDuration);
    }
    return updated;
  });
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

screenshot from chrome

screenshot from safari

You may access data from JavaScript with help of PerformanceServerTiming.

['navigation', 'resource']
        .forEach(function(entryType) {
          performance.getEntriesByType(entryType).forEach(function({name: url, serverTiming}) {
            serverTiming.forEach(function({name, duration, description}) {
              console.info('expressjs middleware =',
                JSON.stringify({url, entryType, name, duration, description}, null, 2))
            })
          })
      })

screenshot

Support

Current support:

  • Chrome v.60
  • FF v.63
  • Safari v.12.1 (no api support)

Documentation

Table of Contents

ServerTiming

Middleware for express.js to add Server Timing headers

Meta

addHook

Add callback to modify data before create and send headers

Parameters

  • name string — hook name
  • callback function — function that may modify data before send headers
  • callbackIndex number index that will be used to sort callbacks before execution

Examples

Add hook to mutate the metrics

const express = require('express');
const serverTimingMiddleware = require('server-timing-header');
const port = 3000;
const app = express();
app.use(serverTimingMiddleware());
app.use(function (req, res, next) {
  // If one measurement include other inside you may substract times
  req.serverTiming.addHook('substractDataTimeFromRenderTime', function (metrics) {
     const updated = { ...metrics };
     if (updated.data && updated.render) {
       const renderDuration  = req.serverTiming.calculateDurationSmart(updated.render);
       const dataDuration  = req.serverTiming.calculateDurationSmart(updated.data);
       updated.render.duration = Math.abs(renderDuration - dataDuration);
     }
     return updated;
  });
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

removeHook

Remove callback with specific name

Parameters

from

Set start time for metric

Parameters

  • name string — metric name
  • description string? — description of the metric

Examples

You may define only start time for metric

const express = require('express');
const serverTimingMiddleware = require('server-timing-header');
const port = 3000;
const app = express();
app.use(serverTimingMiddleware());
app.get('/', function (req, res, next) {
  // If you define only start time for metric,
  // then as the end time will be used header sent time
  req.serverTiming.from('metric', 'metric description');
  // fetching data from database
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

to

Set end time for metric

Parameters

  • name string — metric name
  • description string? — description of the metric

Examples

You may define only end time for metric

const express = require('express');
const serverTimingMiddleware = require('server-timing-header');
const port = 3000;
const app = express();
app.use(serverTimingMiddleware());
app.get('/', function (req, res, next) {
  // fetching data from database
  // If you define only end time for metric,
  // then as the start time will be used middleware initialization time
  req.serverTiming.to('metric');
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

description

Add description to specific metric

Parameters

  • name string — metric name
  • description string — description of the metric

duration

Add duration to specific metric

Parameters

  • name string — metric name
  • duration float — duration of the metric

add

Add metric

Parameters

  • name string metric name
  • description string — metric description
  • duration number — metric duration (optional, default 0.0)

Examples

Add metric

const express = require('express');
const serverTimingMiddleware = require('server-timing-header');
const port = 3000;
const app = express();
app.use(serverTimingMiddleware());
app.get('/', function (req, res, next) {
  // You got time metric from the external source
  req.serverTiming.add('metric', 'metric description', 52.3);
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

calculateDurationSmart

Calculate duration between two timestamps, if from or two is undefined — will use initialization time and current time to replace

Parameters

  • metric object — object that contain metric information
    • metric.name string — metric name
    • metric.description string — metric description
    • metric.from Array<integer> — start time [seconds, nanoseconds], if undefined, initialization time will be used
    • metric.to Array<integer> — end time [seconds, nanoseconds], if undefined, current timestamp will be used
    • metric.duration integer — time in milliseconds, if not undefined method will just return durations

Returns integer duration in milliseconds

oldStyle

Build server-timing header value by old specification

Parameters

  • name string metric name
  • description string metric description
  • duration string metric duration

Returns string — server-timing header value

newStyle

Build server-timing header value by current specification

Parameters

  • name string metric name
  • description string metric description
  • duration string metric duration

Returns string — server-timing header value

index

Express middleware add serverTiming to request and make sure that we will send this headers before express finish request

Parameters

  • options object? — middleware options (optional, default {})
    • options.sendHeaders boolean? should middleware send headers (may be disabled for some environments) (optional, default true)

Examples

How to add middleware

const express = require('express');
const serverTimingMiddleware = require('server-timing-header');
const port = 3000;
const app = express();
app.use(serverTimingMiddleware());
app.get('/', function (req, res, next) {
  req.serverTiming.from('db');
  // fetching data from database
  req.serverTiming.to('db');
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Returns function return express middleware