Skip to content

Instantly share code, notes, and snippets.

@0ex-d
Created March 25, 2022 18:48
Show Gist options
  • Save 0ex-d/171e9ad0a7103b65bb8c4261e9175a04 to your computer and use it in GitHub Desktop.
Save 0ex-d/171e9ad0a7103b65bb8c4261e9175a04 to your computer and use it in GitHub Desktop.
Quick verbose middleware in Node.js frameworks (Koa & Express)
app.get("/check", middleWare, (_, res) => {
res.send("Hello boi");
});
// usage
router.get("/health", middleWare, (ctx) => {
ctx.body = { msg: "All systems is are a go!" };
});
// you may use dependencies as you deem fit
const middleWare = async (req, _, next) => {
const { body, url, headers, params, method, statusCode } = req;
console.log(
`${chalk.white.bgRed.bold(method)} - ${chalk.blue.underline(url)}`
);
console.log({ ...headers }); // this logs header to console
try {
const token = headers?.authorization?.slice(7);
if (token) {
console.log(token);
// do something with Auth header
}
return await next();
} catch (error) {
console.error(error?.message);
return res.status(500).json({ status: 500, message: msg });
}
};
// you may use dependencies as you deem fit
const middleWare = async (ctx, next) => {
const { request, response, params } = ctx;
const { method, url, header } = request;
log(`${chalk.white.bgRed.bold(method)} - ${chalk.blue.underline(url)}`);
log({ ...header }); // this logs header to console
log(params);
try {
const token = header?.authorization?.slice(7);
if (token) {
console.log(token);
// do something with Auth header
}
return await next();
} catch (error) {
console.error(error?.message);
return res.status(500).json({ status: 500, message: msg });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment