npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ngx-cognito-auth

v1.0.2

Published

Angular 21 library for AWS Cognito authentication

Readme

ngx-cognito-auth

npm version npm downloads license

Angular library for AWS Cognito authentication using the OAuth 2.0 Authorization Code flow with PKCE.

  • Zero AWS SDK dependency — communicates directly with the Cognito hosted UI and token endpoint
  • Works with standalone Angular apps (provideHttpClient) and classic NgModule apps
  • Signals-based reactive state (isAuthenticated, user, accessToken)
  • Automatic silent token refresh with deduplication of concurrent calls
  • HTTP interceptor with pre-emptive and reactive 401 handling

Requires Angular 21+


Installation

npm install ngx-cognito-auth

Setup

1. Configure the Cognito App Client

In the AWS Console, make sure your App Client has:

  • Hosted UI enabled
  • No client secret (public client)
  • Your redirect URI added under Allowed callback URLs
  • Your logout URI added under Allowed sign-out URLs

2. Register providers (standalone app)

In app.config.ts:

import { provideHttpClient } from '@angular/common/http';
import { provideCognitoAuth, withCognitoInterceptor } from 'ngx-cognito-auth';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient(withCognitoInterceptor()),
    provideCognitoAuth({
      userPoolId:  'us-east-1_XXXXXXXXX',
      clientId:    'YOUR_CLIENT_ID',
      domain:      'your-domain.auth.us-east-1.amazoncognito.com',
      redirectUri: 'https://yourapp.com/callback',
      scopes:      ['openid', 'email', 'profile'],
    }),
  ],
};

3. Register providers (NgModule app)

import { CognitoAuthModule } from 'ngx-cognito-auth';

@NgModule({
  imports: [
    CognitoAuthModule.forRoot({
      userPoolId:  'us-east-1_XXXXXXXXX',
      clientId:    'YOUR_CLIENT_ID',
      domain:      'your-domain.auth.us-east-1.amazoncognito.com',
      redirectUri: 'https://yourapp.com/callback',
      scopes:      ['openid', 'email', 'profile'],
    }),
  ],
})
export class AppModule {}

4. Add the callback route

import { CognitoCallbackResolver } from 'ngx-cognito-auth';

export const routes: Routes = [
  {
    path: 'callback',
    resolve: { auth: CognitoCallbackResolver },
    component: CallbackComponent, // or any placeholder component
  },
];

5. Protect routes

import { cognitoAuthGuard } from 'ngx-cognito-auth';

{ path: 'dashboard', canActivate: [cognitoAuthGuard], component: DashboardComponent }

Configuration

| Option | Type | Required | Description | |---|---|---|---| | userPoolId | string | yes | Cognito User Pool ID, e.g. us-east-1_AbCdEfGhI | | clientId | string | yes | App Client ID (no client secret) | | domain | string | yes | Cognito hosted UI domain, e.g. myapp.auth.us-east-1.amazoncognito.com | | redirectUri | string | yes | Full callback URI registered in the App Client | | scopes | string[] | yes | OAuth scopes, e.g. ['openid', 'email', 'profile'] | | postLoginRoute | string | no | Route to navigate to after login. Default: /dashboard | | postLogoutRoute | string | no | Route to navigate to after logout. Default: / | | storageKeyPrefix | string | no | Prefix for storage keys. Default: cog_auth |


API

CognitoAuthService

Inject this service wherever you need to interact with the auth state.

import { CognitoAuthService } from 'ngx-cognito-auth';

@Component({ ... })
export class AppComponent {
  private auth = inject(CognitoAuthService);

  isLoggedIn = this.auth.isAuthenticated; // Signal<boolean>
  user        = this.auth.user;           // Signal<CognitoUser | null>
  token       = this.auth.accessToken;    // Signal<string | null>

  login()  { this.auth.login(); }
  logout() { this.auth.logout(); }
}

Signals

| Signal | Type | Description | |---|---|---| | isAuthenticated | Signal<boolean> | true if an access or refresh token is present | | user | Signal<CognitoUser \| null> | Decoded ID token claims | | accessToken | Signal<string \| null> | Raw Bearer token |

Methods

| Method | Description | |---|---| | login(returnUrl?) | Starts the PKCE flow and redirects to Cognito | | logout() | Clears local state and redirects to Cognito global logout | | refreshTokens() | Silently refreshes tokens; concurrent calls are deduplicated | | getToken() | Returns the current access token or null | | getUser() | Returns the decoded CognitoUser or null |

cognitoAuthGuard / CognitoAuthGuard

Redirects unauthenticated users to login, preserving the requested URL as the post-login target.

// Functional (standalone apps)
{ path: 'secure', canActivate: [cognitoAuthGuard], component: SecureComponent }

// Class-based (NgModule apps)
{ path: 'secure', canActivate: [CognitoAuthGuard], component: SecureComponent }

cognitoBearerInterceptor / withCognitoInterceptor()

Automatically attaches Authorization: Bearer <token> to outgoing HTTP requests.

  • Skips requests to Cognito's own /oauth2/ endpoint
  • Performs a pre-emptive refresh if the local token is expired before sending
  • Retries once after a server-side 401
  • Redirects to login if the refresh itself fails

To skip token injection for a specific request:

import { SKIP_COGNITO_BEARER } from 'ngx-cognito-auth';

this.http.get('/api/public', {
  context: new HttpContext().set(SKIP_COGNITO_BEARER, true),
});

Token Storage

| Token | Storage | Notes | |---|---|---| | Access token | sessionStorage | Cleared on tab close | | ID token | sessionStorage | Cleared on tab close | | Refresh token | localStorage | Persists across sessions |

Storage keys use the storageKeyPrefix option as prefix (default: cog_auth).


License

MIT