Last active
September 18, 2024 14:57
-
-
Save ali-kamalizade/05488b11e703b5e26c46e3a3d913bedf to your computer and use it in GitHub Desktop.
A sample implementation of a health check endpoint for Node.js using Express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app.js: register the route. In our case, we don't want authorization for this route | |
app.use('/healthcheck', require('./routes/healthcheck.routes')); | |
// healthcheck.routes.js: return a 2xx response when your server is healthy, else send a 5xx response | |
import express from 'express'; | |
const router = express.Router({}); | |
router.get('/', async (_req, res, _next) => { | |
// optional: add further things to check (e.g. connecting to dababase) | |
const healthcheck = { | |
uptime: process.uptime(), | |
message: 'OK', | |
timestamp: Date.now() | |
}; | |
try { | |
res.send(healthcheck); | |
} catch (e) { | |
healthcheck.message = e; | |
res.status(503).send(); | |
} | |
}); | |
// export router with all routes included | |
module.exports = router; | |
// healthcheck.spec.js (services like Pingdom or Freshping do a similar approach to check whether your server is healthy) | |
describe('Healthcheck', () => { | |
it('returns 200 if server is healthy', async () => { | |
const res = await get(`/healthcheck`, null) | |
.expect(200); | |
expect(res.body.uptime).toBeGreaterThan(0); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment