NestJS: ipinfo middleware


Dependency: @sansamour/express-ip

File middleware/ip.ts

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
import {getIpInfoMiddleware} from '@sansamour/express-ip'
 
@Injectable()
export class IpMiddleware implements NestMiddleware {          
  use(req: Request, res: Response, next: Function) {
    return getIpInfoMiddleware()(req, res, next)
  }
}

File app.module.ts

import {IpMiddleware} from './middleware/ip';
...
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(IpMiddleware)
      .forRoutes('*');
  }
}

Leave a Reply