Skip to content

Instantly share code, notes, and snippets.

@ali-kamalizade
Last active April 26, 2024 12:47
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ali-kamalizade/05488b11e703b5e26c46e3a3d913bedf to your computer and use it in GitHub Desktop.
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
// 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