Skip to content

Instantly share code, notes, and snippets.

@tyrauber
Created October 4, 2023 18:47
Show Gist options
  • Save tyrauber/66a54ea4a62e6a9604995610d40e9a79 to your computer and use it in GitHub Desktop.
Save tyrauber/66a54ea4a62e6a9604995610d40e9a79 to your computer and use it in GitHub Desktop.
Koa / Express Shared Typescript Middleware
import Express, { Application, Request, Response, NextFunction } from 'express';
import Koa, { Context, Next } from 'koa';
const middleware = async (req: Request | Context['request'], res: Response | Context['response'], next: NextFunction) => {
console.log('Time:', Date.now());
await next();
}
interface Options {}
const Middleware = (app: Application | Koa, options:Options) => {
if (app instanceof Koa) {
app.use(async (ctx: Context, next: Next) => {
await middleware(ctx.request, ctx.response, next);
});
} else {
app.use(async (req: Request, res: Response, next: NextFunction) => {
await middleware(req, res, next);
});
}
};
export default Middleware;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment