How to use csurf middleware in tsoa express?

1.4k Views Asked by At

I am new to tsoa and I want to do CSRF implementation in my node app. I have been able to make api using app.use() but I want to write in tsoa. Is there any way?

2

There are 2 best solutions below

1
On

In the pre-released version, you can use the @Middlewares() decorator.

0
On

Just put what you had in a app.use() to the @Middlewares() decorator.

You can define your Middleware / Middlewares like this:

import { Request, Response, NextFunction } from 'express';

// ... controller logic ...

// @Get('/endpoint') | @Post('/endpoint') etc.
@Middlewares([
  (req: Request, res: Response, next: NextFunction) => {
    console.log(req.headers);
    next();
  },
  (req: Request, res: Response, next: NextFunction) => {
    console.log('Second middleware, but we can also use only one!');
    next();
  },
])
// getEndpoint(): string {
//   return 'Hello World!';
// }

// ... controller logic ...

Also remember to have set the experimentalDecorators to true in your tsconfig.json.1


1 https://github.com/lukeautry/tsoa/pull/1123#issuecomment-1018251162