How to encrypt / decrypt query params in Angular automatically?

939 Views Asked by At

I want to encrypt query params URL in Angular.

my URL now looks like this: https://example.com/posts/235645?asc=1&published=true

what I want to approach is to see the previous URL like: https://example.com/posts/ksjz654fezf?asc=sfeui54sf&published=eirjh54561

but in condition when I'll use the this.activatedRoute.queryParams.subscribe(params => {}) I want to see the parameters I have from the pushed observable like it was in the first URL to use in the API call.

  • which class or package do you think it's going to help me out?

I've used the functions (btoa, atoa) in ngOnInit() to encrypt/decrypt. but I have a large app so it's not the best solution to approach what I want. also, I find it bad practice to add the code in many components classes.

I appreciate your help and time.

Thanks

CoderNadir

1

There are 1 best solutions below

3
On

I suggest this version. I am using on route events to encrypt and decrypt queryParams.

   router.events
          .pipe(filter(event => event instanceof NavigationStart))
          .subscribe((event) => {
            const urlSplitted = (event as NavigationStart).url.split('?q=');
            const basePart = urlSplitted[0];
            let queryParamPartDecrypt = '';
            if (urlSplitted.length > 1) {
              queryParamPartDecrypt = decodeURI(this.decode(urlSplitted[1]));
              router.navigateByUrl(`${basePart}?${queryParamPartDecrypt}`);
            }
          });
    
        router.events
          .pipe(filter(event => event instanceof ActivationEnd))
          .subscribe((event) => {
            const urlSplitted = router.url.split('?');
            const basePart = urlSplitted[0];
            const queryParamPart = urlSplitted.length > 1 ? urlSplitted[1] : null;
    
            let queryParamPartCrypt = '';
            if (queryParamPart) {
              queryParamPartCrypt = `?q=${this.encode(queryParamPart)}`;
            }
            this._location.go(`${basePart}${queryParamPartCrypt}`);
          });
      }
    
    
      encrypt(url: string): string {
        /** code of encrypt**/
        return base16String;
      }
    
      decrypt(base16String: string): string {
        /** code of decrypt **/
        return url;
      }
    }