JavaScript NestJs integration with FireBack

User-flow built for you.

If you want to create a backend project with NestJs, you can use FireBack in 2 minutes within your project, and skip the user/role authentication part.

Step 1: Initialize a new project or open existing one

You need a nestjs project to continue with this tutorial.

Step 2: Create a new middleware, fireback

import { HttpService } from '@nestjs/axios';
import { HttpException, Injectable, NestMiddleware } from '@nestjs/common';
import { catchError, map, of } from 'rxjs';

// Change the port, or load it from ENV if you have multiple fireback apps.
const FIREBACK_HOST = 'http://localhost:4500';

@Injectable()
export class FirebackMiddleware implements NestMiddleware {
  constructor(private readonly httpService: HttpService) {}

  use(req: any, res: any, next: any) {
    this.httpService.post(`${FIREBACK_HOST}/token`, {'token': req.headers['authorization']}).pipe(
      map(res => {
        req.user = res.data;
        next();
      }),
      catchError((error) => {
        next(new HttpException( error.response.data.error.message, error.response.status))
        return of(false)
      })
    ).subscribe();
  }
}

Step 3: Assign the middleware to routes you want to access the user data

By adding this middleware to routes of nestjs app, it will check the header Authorization with microservice of fireback, and if token is valid, req.user will be available.

import { HttpModule } from '@nestjs/axios';
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthGuard } from './auth.guard';
import { FirebackMiddleware } from './fireback.middleware';

@Module({
  imports: [HttpModule],
  controllers: [AppController],
  providers: [AppService, AuthGuard, FirebackMiddleware],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    
    // We are assigning all routes to be authenticated, make sure you exclude
    // your public APIs, for example healthcheck api
    consumer
      .apply(FirebackMiddleware).forRoutes({path: '*', method: RequestMethod.ALL})

  }
}

Step 4: Access user data

Now every function will have the user information, such as name, passports, workspaces, and many more.

import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  // Since middleware is applied to this route, only if user signed in with correct
  // token will reach to this function, and req.user will have the username, passports,
  // and all information which is stored in FireBack.
  @Get()
  getHello(@Req() req): string {
    return req.user;
  }
}