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

express-ruid

v1.1.5

Published

Express.js Request Unique ID middleware

Downloads

6,459

Readme

express-ruid

An Express.js middleware to generate unique id for incoming requests. The generated id will have a prefix and a sequence number.

In case a request has the request-id header valued, then the middleware will use it (header name can be configured, as described in the options section).

Contents

Installation

npm install express-ruid

Request id format

The request id will be composed of the three parts. The first two will form the prefix while the third will be the sequence id part:

  • prefix
    • pid
    • hostname
  • unique part (generated)
  • sequence id (number)

Theese parts will be composed in the form of pid@hostname/unique_part-sequenceid

As an example, a reuest id might be something like this: 4409@redrock/4f1704658fdd4d797c833563-0000000000000001.

The prefix part and the separators '/' and '-' can be configured, as described in the options section.

Request attribute

The request id (generated or inherited from the request-id header) will be set as req attribute. The default attribute name is rid, but it can be configured, as described in the options section. You can access the request id directly from the Express req object:

app.get('/', (req, res) => {
    console.log(`incoming request-id: ${req.rid}`);
});

Express http context

Starting from v1.1.0 you can choose to set the request id even in the http context of your app configuring the setInContext option to true. The default attribute name is yet rid, but it can be configured.

The request id attribute in http context can be useful in all those situations where it is not possible to have direct access to the request object.

To get this job done, express-ruid needs you to initialize the express-http-context and use its middleware in your app.

If you don't want to set request id in http context, you can leave the setInContext option configuredwith its default (false), and you are free to no use the espress-http-context middleware in your app. But note that if you configure setInContext to true without using the express-http-context middleware in your app, you will not have any request id in context.

All of the warnings stated by the express-http-context lib remains:

Use the middleware immediately before the first middleware that needs to have access to the context. You won't have access to the context in any middleware "used" before this one.

Note that some popular middlewares (such as body-parser, express-jwt) may cause context to get lost. To workaround such issues, you are advised to use any third party middleware that does NOT need the context BEFORE you use this middleware.

// app.js
const ruid = require('express-ruid');
const httpContext = require('express-http-context');
const express = require('express');

// be sure to user the httpContext.middleware
app.use(httpContext.middleware);

// configure the 'setInContext' option to true
app.use(ruid({ setInContext: true }));
...
...
...

// your-awesome-service.js
const httpContext = require('express-http-context');

function doAwesomeThingsService(app) {
    return {
        getAllStrangerThings() {
            const rid = httpContext.get('rid');
            // ...
        },
        saveFantasticThing() {
            const rid = httpContext.get('rid');
            try {
                // .....
            } catch(err) {
                mySuperErrorNotificationAsyncService.notify(rid, err);
            }
        },
        // just your imagination...
    }
}
module.exports = doAwesomeThingsService;

Response header

The request id will be returned as response header. It is added to the Express res object headers as request-id header. The name for the response header is configurable. Note that you can choose to not add the res header, by configuring the setHeader option to false, as described in the options section.

Max id and unique part regeneration

When the sequence id reach the max (default is Number.MAX_DAFE_INTEGER = 9007199254740991 on a 64bit machine), the unique part of the prefix will be regenerated and the sequence restart from 0 (so the first id will be ...00001). The max id is configurable.

$ curl -i localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
request-id: 7522@redrock/4f1704658fdd4d797c833563-9007199254740991

$ curl -i localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
request-id: 7522@redrock/dafbb8dd5eb2193ee436e8b4-0000000000000001

Options

ruid() supports the following options:

  • setHeader: (boolean) to add or not the response header. Default: true
  • setInContext: (boolean) to set or not the request id into the Http Context. Default is false
  • header: (string) to specify the response header name. Default: 'request-id'
  • attribute: (string) to specify the attribute name to set the request id into to Express req object. Default: 'rid'
  • prefixRoot: (string | function) to specify custom prefix part of the request id string. Default: '<process-pid>@<machine-hostname>'
  • prefixSeparator: (string) to set custom separator between prefix and unique part of the request id string. Default: '/'
  • upBytes: (number) number of bytes to generate the unique part of the riquest id. Default: 12
  • idSeparator: (string) to set custom separator between the unique part and the sequene number of the request id string. Default: '-'
  • isMax: (number) the max number for the sequence number in the request id string. Default: Number.MAX_SAFE_INTEGER

Sample usage

const express = require('express');
const ruid = require('express-ruid');

const app = express();

app.use(ruid());

app.get('/', function (req, res, next) {
    return res.sendStatus(200);
});

const server =
    app.listen(3000, '0.0.0.0')
        .on('listening', () => {
            console.log(`server listening on ${server.address().address}:${server.address().port}`);
        })
        .on('error', (err) => {
            console.error(err);
            process.exit(1);
        });

To test the sample:

$ curl -i localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
request-id: 7522@redrock/4f1704658fdd4d797c833563-0000000000000001

$ curl -i localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
request-id: 7522@redrock/4f1704658fdd4d797c833563-0000000000000002

...
...
$ curl -i localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
request-id: 7522@redrock/4f1704658fdd4d797c833563-0000000000002491

Acknowledgements

This project is inspired by express-request-id and the chi request_id middleware.

License

express-ruid is MIT licensed.