skip to Main Content

I have a nestjs application that consumes third party API for data. In order to use that third party API, I need to pass along an access token. This access token is application-wide and not attached to any one user.

What would be the best place to store such a token in Nestjs, meeting the following requirements:

  • It must be available in the application and not per given user
  • It must not be exposed to the frontend application
  • It must work in a load balancer setup

I am looking at Nestjs caching https://docs.nestjs.com/techniques/caching, but I am not sure whether that’s the best practice and if it is – should I use it with in-memory storage or something like redis.

Thank you.

2

Answers


  1. If you’re working with Load Balancing, then in-memory solutions are dead on arrival, as they will only affect one instance of your server, not all of them. Your best bet for speed purposes and accessibility would be Redis, saving the token under a simple key and keeping it alive from there (and updating it as necessary). Just make sure all your instances connect to the same Redis instance, and that your instance can handle it, shouldn’t be a problem, more of a callout

    Login or Signup to reply.
  2. I used a custom provider. Nest allows you to load async custom providers.

    export const apiAuth = {
      provide: 'API_AUTH',
      useFactory: async (authService: AuthService) => {
        return await authService.createOrUpdateAccessToken()
      },
      inject: [AuthService]
    }
    

    and below is my api client.

    @Injectable()
    export class ApiClient {
      constructor(@Inject('API_AUTH') private auth: IAuth, private authService: AuthService) { }
      public async getApiClient(storeId: string): Promise<ApiClient> {
        if (((Date.now() - this.auth.createdAt.getTime()) > ((this.auth.expiresIn - 14400) * 1000))) {
          this.auth = await this.authService.createOrUpdateAccessToken()
        }
        return new ApiClient(storeId, this.auth.accessToken);
      }
    }
    

    This way token is requested from storage once and lives with the application, when expired token is re-generated and updated.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search