Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing token on server-side using nestjs

Tags:

node.js

nestjs

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.

like image 528
Jacobdo Avatar asked Aug 12 '26 15:08

Jacobdo


2 Answers

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

like image 132
Jay McDoniel Avatar answered Aug 14 '26 11:08

Jay McDoniel


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.

like image 21
Arrrrny Avatar answered Aug 14 '26 12:08

Arrrrny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!