0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-01-06 22:40:14 -05:00

Improved x-request-id handling

- Currently, we create a request ID for internal use if one isn't set & this is used in logs
- If a custom request ID is set via X-Request-ID header, this gets logged, however, we don't return this with the response
- Means that a custom ID gets lost on the way back out, and makes tracing requests through a system trickier
- This change ensures that if X-Request-ID is set on the request, it is also set on the response so that requests can be properly traced
- It's easy to set this in e.g. nginx so that the feature becomes available - Ghost doens't need to do this
- Note: also split request id handling out into new middleware
This commit is contained in:
Hannah Wolfe 2019-09-22 18:20:05 +01:00
parent 366e90ddef
commit ce6745b6a1
3 changed files with 23 additions and 7 deletions

View file

@ -1,17 +1,13 @@
var uuid = require('uuid'),
common = require('../../lib/common');
var common = require('../../lib/common');
/**
* @TODO:
* - move middleware to ignition?
* @TODO: move this middleware to ignition?
*/
module.exports = function logRequest(req, res, next) {
var startTime = Date.now(),
requestId = req.get('X-Request-ID') || uuid.v1();
var startTime = Date.now();
function logResponse() {
res.responseTime = (Date.now() - startTime) + 'ms';
req.requestId = requestId;
req.userId = req.user ? (req.user.id ? req.user.id : req.user) : null;
if (req.err && req.err.statusCode !== 404) {

View file

@ -0,0 +1,18 @@
const uuid = require('uuid');
/**
* @TODO: move this middleware to ignition?
*/
module.exports = (req, res, next) => {
const requestId = req.get('X-Request-ID') || uuid.v4();
// Set a value for internal use
req.requestId = requestId;
// If the header was set on the request, return it on the response
if (req.get('X-Request-ID')) {
res.set('X-Request-ID', requestId);
}
next();
};

View file

@ -10,6 +10,7 @@ var debug = require('ghost-ignition').debug('app'),
// local middleware
ghostLocals = require('./middleware/ghost-locals'),
requestId = require('./middleware/request-id'),
logRequest = require('./middleware/log-request');
module.exports = function setupParentApp() {
@ -22,6 +23,7 @@ module.exports = function setupParentApp() {
// (X-Forwarded-Proto header will be checked, if present)
parentApp.enable('trust proxy');
parentApp.use(requestId);
parentApp.use(logRequest);
// enabled gzip compression by default