User Authentication Pool

A Stacktape user authentication pool is a managed identity provider built on Amazon Cognito that handles user sign-up, sign-in, and access control. It supports email and phone verification, multi-factor authentication, social login (Google, Facebook, Apple), enterprise SSO (SAML, OIDC), and OAuth 2.0 flows — without requiring you to build or maintain auth infrastructure.

Amazon Cognito pricing is based on monthly active users (MAU), with different rates for native sign-in users and federated identities. Check current AWS Cognito pricing for exact regional rates.

When to use

Use a user authentication pool when your application needs user accounts with sign-up, sign-in, and password reset flows. It is the right choice when you want a fully managed identity layer that handles token issuance, email/SMS verification, and MFA. Common scenarios include:

  • Web or mobile apps with user accounts — the pool manages the full authentication lifecycle, including token refresh and session management.
  • Social login — let users sign in with Google, Facebook, Apple, Amazon, or any OIDC/SAML provider without writing OAuth plumbing.
  • Protecting API routes — pair the pool with an HTTP API Gateway to validate JWTs on every request, with zero custom middleware.
  • Admin-only account creation — set allowOnlyAdminsToCreateAccount: true to restrict sign-ups so only your team can create accounts (useful for internal tools and B2B apps).

When NOT to use

A user authentication pool is not the right fit for every authentication scenario. Skip it when:

  • You only need machine-to-machine auth. API keys or IAM credentials are simpler. Cognito is designed for human users with sign-in flows.
  • You already use a third-party identity provider (Auth0, Clerk, Supabase Auth, Firebase Auth) and want to keep it. There is no benefit to migrating unless you want to consolidate on AWS.
  • You need fine-grained authorization logic beyond token validation. Cognito handles authentication (who is this user?) well, but complex authorization (what can this user do?) typically lives in your application code or a policy engine.
  • Your app has no user-facing sign-in. If all your callers are backend services or cron jobs, a user pool adds unnecessary complexity.

Basic example

A user authentication pool can be declared without any properties. Stacktape creates the underlying Cognito user pool and a user pool client. In practice, most apps configure at least a verification type so that new users verify their email or phone before gaining access.

export default defineConfig(() => {
  const auth = new UserAuthPool({
    userVerificationType: 'email-code'
  });

  return {
    resources: { auth }
  };
});

This creates a user pool where new users verify their email address with a one-time code. By default, users can sign in with either their email address or phone number (allowEmailAsUserName and allowPhoneNumberAsUserName both default to true). The unusedAccountValidityDays defaults to 31.

Admin-only accounts

For internal tools, B2B dashboards, or any app where you do not want public sign-ups, set allowOnlyAdminsToCreateAccount: true. Accounts must then be created through an admin flow (using the Cognito AdminCreateUser API from your backend).

export default defineConfig(() => {
  const auth = new UserAuthPool({
    userVerificationType: 'email-code',
    allowOnlyAdminsToCreateAccount: true,
    unusedAccountValidityDays: 7
  });

  return {
    resources: { auth }
  };
});

Use unusedAccountValidityDays to control how long an unused admin-created account stays valid if the user never signs in. Setting it to 7 means the temporary password and account expire after 7 days. The default is 31 days. This is separate from passwordPolicy.temporaryPasswordValidityDays, which controls how long a temporary password is valid before it must be changed on first sign-in.

Connecting to resources

To use the user pool from a Lambda function, web service, or any other compute resource, add it to the resource's connectTo list. For a UserAuthPool, connectTo grants full-control permissions and injects ID, CLIENT_ID, and ARN environment variables.

export default defineConfig(() => {
  const auth = new UserAuthPool({
    userVerificationType: 'email-code'
  });

  const gateway = new HttpApiGateway({});

  const api = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/handler.ts'
    }),
    connectTo: [auth],
    events: [
      new HttpApiIntegration({
        httpApiGatewayName: 'gateway',
        method: '*',
        path: '/{proxy+}'
      })
    ]
  });

  return {
    resources: { auth, gateway, api }
  };
});

For a resource named auth, the following environment variables are injected by connectTo:

VariableDescription
STP_AUTH_IDCognito User Pool ID
STP_AUTH_CLIENT_IDUser Pool Client ID
STP_AUTH_ARNUser Pool ARN

The domain parameter is also available as a referenceable parameter via $ResourceParam — for example, $ResourceParam('auth', 'domain') for the Hosted UI domain.

Your application code can pass the injected pool ID, client ID, and ARN to AWS SDKs or Cognito-compatible libraries. For example, backend code commonly uses Cognito APIs for admin user creation or authentication flows. Libraries like amazon-cognito-identity-js or @aws-sdk/client-cognito-identity-provider accept the pool ID and client ID directly.

Protecting API routes

A Stacktape user authentication pool integrates with HTTP API Gateway to protect routes using JWT validation. When you add a cognito authorizer to an HTTP trigger, API Gateway validates the bearer token on every request before your code runs — unauthorized requests get a 401 response automatically.

export default defineConfig(() => {
  const auth = new UserAuthPool({
    userVerificationType: 'email-code'
  });

  const gateway = new HttpApiGateway({});

  const api = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/handler.ts'
    }),
    connectTo: [auth],
    events: [
      new HttpApiIntegration({
        httpApiGatewayName: 'gateway',
        method: 'GET',
        path: '/me',
        authorizer: {
          type: 'cognito',
          properties: {
            userPoolName: 'auth'
          }
        }
      })
    ]
  });

  return {
    resources: { auth, gateway, api }
  };
});

The cognito authorizer type validates JWTs issued by the referenced user pool. Stacktape uses userPoolName to set the expected audience to the user pool client ID and build the issuer URL from the user pool and AWS region. By default, the token is read from the Authorization header. You can customize this with the identitySources property on the authorizer to read from a different header, query parameter, or stage variable using the $request.* syntax.

Stacktape also supports a lambda authorizer type, where a Lambda function runs custom authorization logic for each request. Use this when your auth needs go beyond simple JWT validation — for example, checking API keys, looking up permissions in a database, or integrating with a non-Cognito identity system. See HTTP triggers for details on both authorizer types.

Verification

Stacktape user authentication pools support four verification strategies that control how new users prove ownership of their contact information. Set userVerificationType to choose the strategy:

StrategyBehavior
email-codeCognito emails a short numeric code the user enters during sign-up
email-linkCognito emails a clickable verification link
smsCognito sends a verification code via SMS to the user's phone number
noneNo email or phone verification is required during sign-up

For most web applications, email-code is the best default — it works without extra infrastructure and is familiar to users. Use email-link for a smoother UX where users just click a link instead of copying a code. Use sms when phone numbers are the primary identifier (ride-sharing, delivery apps). Use none only for internal tools where you trust all users.

You can customize the email subject and body text for both code and link verification using userVerificationMessageConfig. To fully customize the email sender and message format, configure emailConfiguration.sesAddressArn with a verified SES identity. Without SES configuration, Cognito sends emails through its built-in sender, which works for standard verification flows but has lower daily sending limits.

The requireEmailVerification and requirePhoneNumberVerification properties are reserved for forward compatibility. Stacktape currently derives verification behavior from userVerificationType, not from those flags directly.

Identity providers

A Stacktape user authentication pool supports six types of external identity providers, allowing users to sign in with existing accounts instead of creating new credentials:

Provider typeUse case
GoogleConsumer and business apps — most widely used social login
FacebookConsumer apps, especially social or e-commerce
SignInWithAppleRequired for iOS apps that offer other social logins
LoginWithAmazonE-commerce or Alexa-integrated apps
OIDCAny OpenID Connect provider (Okta, Azure AD, etc.)
SAMLEnterprise SSO (Active Directory, Ping Identity, etc.)

Each identity provider requires a clientId and clientSecret. These are required fields in the Stacktape type for all provider types. For social and OIDC providers, obtain them from the provider's developer console. For SAML and OIDC providers, advanced provider-specific options can be passed through providerDetails as Cognito ProviderDetails values. Store secrets using the $Secret directive to avoid exposing them in your config. See secrets or stacktape secret set for setup.

export default defineConfig(() => {
  const auth = new UserAuthPool({
    userVerificationType: 'email-code',
    enableHostedUi: true,
    hostedUiDomainPrefix: 'myapp-login',
    identityProviders: [
      {
        type: 'Google',
        clientId: "$Secret('google-credentials', 'clientId')",
        clientSecret: "$Secret('google-credentials', 'clientSecret')"
      }
    ],
    callbackURLs: ['https://myapp.com/auth/callback'],
    logoutURLs: ['https://myapp.com/logged-out']
  });

  return {
    resources: { auth }
  };
});

When you add an identity provider, Stacktape creates separate AWS::Cognito::UserPoolIdentityProvider resources and registers them in the user pool client's SupportedIdentityProviders. If you do not specify attributeMapping, Stacktape defaults to mapping email from the provider to the Cognito email attribute. You can override this with the attributeMapping property to map additional attributes like given_name or picture.

If you omit authorizeScopes, Stacktape uses a reasonable default per provider. Set authorizeScopes explicitly when your app needs specific provider scopes — for example, requesting access to a user's Google Calendar or Facebook friend list.

Set allowOnlyExternalIdentityProviders: true only after configuring at least one identityProviders entry. Stacktape then removes COGNITO from the user pool client's SupportedIdentityProviders, so users must sign in through the configured external providers.

Lambda hooks

Cognito triggers let you run custom logic at key points in the authentication lifecycle. The hooks property connects Lambda function ARNs to specific trigger points. Use $ResourceParam to reference a Lambda function from your stack:

HookWhen it runsCommon use case
preSignUpBefore a new user is createdValidate input, auto-confirm trusted domains, block sign-ups
postConfirmationAfter account confirmationCreate records in your database, provision resources
preAuthenticationBefore credential validationBlock sign-in by IP, device, or user state
postAuthenticationAfter successful sign-inUpdate last-login timestamps, record analytics
preTokenGenerationBefore tokens are issuedAdd custom claims (roles, permissions) to JWTs
customMessageBefore sending email/SMSCustomize message content, localize text
userMigrationWhen an unknown user signs inImport users on-the-fly from a legacy system
createAuthChallengeDuring custom auth flowGenerate a custom challenge (e.g., OTP)
defineAuthChallengeDuring custom auth flowDecide whether a challenge is needed
verifyAuthChallengeResponseDuring custom auth flowValidate the user's challenge response

Each hook value must be a Lambda function ARN. Stacktape maps the configured hooks to the Cognito user pool LambdaConfig.

export default defineConfig(() => {
  const createProfile = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/create-profile.ts'
    })
  });

  const auth = new UserAuthPool({
    userVerificationType: 'email-code',
    hooks: {
      postConfirmation: "$ResourceParam('createProfile', 'arn')"
    }
  });

  return {
    resources: { createProfile, auth }
  };
});

In this example, the createProfile Lambda function runs after each user confirms their account — a common pattern for writing the new user to your own database. The $ResourceParam('createProfile', 'arn') directive resolves to the Lambda ARN at deploy time.

Multi-factor authentication

MFA adds a second verification step during sign-in, making it harder for attackers to access accounts even if they know a user's password. Stacktape supports three MFA factor types:

FactorHow it worksRequirements
SOFTWARE_TOKENTime-based one-time codes from an authenticator app (Google Authenticator, Authy)None — works without extra configuration
SMSOne-time codes sent via text messageRequires an SNS role so Cognito can send SMS
EMAIL_OTPOne-time codes sent via emailRequires emailConfiguration.sesAddressArn with a verified SES identity

The mfaConfiguration.status property controls enforcement: ON requires MFA for all users, OPTIONAL lets users opt in, and OFF disables MFA entirely. For most apps, start with OPTIONAL and move to ON once your users have enrolled their second factor.

export default defineConfig(() => {
  const auth = new UserAuthPool({
    userVerificationType: 'email-code',
    mfaConfiguration: {
      status: 'OPTIONAL',
      enabledTypes: ['SOFTWARE_TOKEN']
    }
  });

  return {
    resources: { auth }
  };
});

SOFTWARE_TOKEN (TOTP-based authenticator apps) is the recommended default — it has no per-message cost, works globally, and does not require SES or SNS configuration. Use SMS only when your users might not have access to authenticator apps, keeping in mind the per-message SMS cost. Use EMAIL_OTP when you already have SES configured and want a low-friction second factor that does not require a separate authenticator app.

Hosted UI

Cognito provides a pre-built, hosted login and registration page so you do not have to build your own auth screens. Enable it with enableHostedUi: true. The Hosted UI is useful when you want authentication screens outside your main app. If you use OAuth redirects, configure callbackURLs and logoutURLs explicitly.

export default defineConfig(() => {
  const auth = new UserAuthPool({
    enableHostedUi: true,
    hostedUiDomainPrefix: 'myapp-auth',
    userVerificationType: 'email-code',
    callbackURLs: ['https://myapp.com/auth/callback'],
    logoutURLs: ['https://myapp.com/logged-out'],
    allowedOAuthFlows: ['code'],
    allowedOAuthScopes: ['email', 'openid', 'profile']
  });

  return {
    resources: { auth }
  };
});

The hostedUiDomainPrefix sets the first part of the Hosted UI URL: https://<prefix>.auth.<region>.amazoncognito.com. Choose a prefix that matches your project name. Cognito accepts 1 to 63 lowercase letters, digits and hyphens, starting and ending with a letter or digit, and rejects a prefix that contains aws, amazon or cognito; Stacktape checks this before deploying. Without hostedUiDomainPrefix, the prefix is <stack name>-<pool name>. When Cognito would reject that, for example for a pool named cognitoPool, a new pool gets the same name without the rejected parts and with a short hash. A deployed pool keeps the prefix it has. Use hostedUiCSS to provide custom CSS for the Hosted UI, applied via Cognito's AWS::Cognito::UserPoolUICustomizationAttachment resource.

When to enable the Hosted UI: Use it when you want to ship authentication quickly without building custom UI. It is especially useful with social login providers, since the Hosted UI handles the OAuth redirect flow for you. When to skip it: If you need full control over the login experience (custom animations, complex form validation, branded flows), build your own UI and use the Cognito SDK directly — you still get the same underlying user pool.

Custom domain

By default, the Hosted UI is served from a Cognito-managed subdomain. To use your own domain (e.g., auth.example.com), configure customDomain:

export default defineConfig(() => {
  const auth = new UserAuthPool({
    enableHostedUi: true,
    userVerificationType: 'email-code',
    customDomain: {
      domainName: 'auth.example.com'
    },
    callbackURLs: ['https://example.com/auth/callback'],
    logoutURLs: ['https://example.com/logged-out']
  });

  return {
    resources: { auth }
  };
});

When to use a custom domain: Use one when your auth URLs are user-visible and brand matters — for example, showing auth.yourcompany.com instead of a Cognito subdomain in login redirects. Custom domains are also useful when sharing OAuth client configurations across environments, since the domain stays consistent. When the default is fine: For prototypes, internal tools, and apps where users never see the auth URL directly, the Cognito-managed hostedUiDomainPrefix subdomain is simpler — no DNS setup, no certificate management, and no propagation delays. Expect DNS ownership verification and possible propagation debugging overhead when using a custom domain.

The domain must be registered and verified in your Stacktape account with a valid ACM certificate in us-east-1 (Cognito uses CloudFront for custom domains, which requires certificates in that region). Stacktape creates a DNS record for customDomain by default. Set customDomain.disableDnsRecordCreation: true to prevent Stacktape from creating that record. Use that flag if you manage DNS records outside of Stacktape — for example, through Cloudflare or another DNS provider. You can also provide a specific certificate ARN with customCertificateArn if you need a particular certificate.

OAuth

The user pool client's OAuth configuration controls which flows, scopes, and redirect URLs are allowed. Configure these explicitly when using the Hosted UI or integrating with external identity providers:

  • allowedOAuthFlows — which OAuth 2.0 flows the client can use: code (Authorization Code, recommended for web apps), implicit (legacy browser-only flow), or client_credentials (server-to-server with no end user). For most web applications, use ['code'].
  • allowedOAuthScopes — a string list of scopes the user pool client can request. Common values are email, openid, and profile. These are passed to the Cognito user pool client as AllowedOAuthScopes. For scopes requested from an external provider (e.g., Google Calendar access or Facebook friend list), set authorizeScopes on that provider's identityProviders entry instead.
  • callbackURLs — URLs where Cognito redirects users after authentication. Must exactly match the URLs configured in your application. Include http://localhost:3000/... during development and your production URL for deployed environments.
  • logoutURLs — URLs where Cognito redirects after sign-out. Must also be explicitly configured.
  • generateClientSecret — set to true when your backend can safely store a client secret (server-side apps, not SPAs). Defaults to false.

For server-rendered web apps or backend-mediated OAuth flows, use the code flow with generateClientSecret: true. For single-page applications that call Cognito directly from the browser, use the code flow without a client secret (PKCE is handled automatically by the Cognito SDK).

Password policy

Stacktape lets you configure password strength requirements through the passwordPolicy property. You can set minimumLength and require specific character classes (requireLowercase, requireUppercase, requireNumbers, requireSymbols).

export default defineConfig(() => {
  const auth = new UserAuthPool({
    userVerificationType: 'email-code',
    passwordPolicy: {
      minimumLength: 12,
      requireNumbers: true,
      requireUppercase: true,
      requireLowercase: true,
      temporaryPasswordValidityDays: 3
    }
  });

  return {
    resources: { auth }
  };
});

The temporaryPasswordValidityDays inside passwordPolicy controls how long a temporary password issued to a new user is valid before it must be changed on first sign-in. This is distinct from the top-level unusedAccountValidityDays, which controls when the entire unused admin-created account expires if the user never signs in at all.

The UserAuthPoolProps type does not document Stacktape-specific defaults for passwordPolicy; set these values explicitly when they matter for your application. For production applications, set at least minimumLength: 12 and enable requireNumbers and requireUppercase — this provides meaningful security without frustrating users.

Client restrictions

The pool's app client accepts every sign-in flow and can read and write every user attribute unless you limit it:

PropertyLimits
allowedAuthFlowsWhich sign-in flows the client accepts, for example ALLOW_USER_SRP_AUTH and ALLOW_REFRESH_TOKEN_AUTH only
readAttributesWhich user attributes tokens and GetUser return through the client
writeAttributesWhich attributes users can set through the client, for example to keep custom:role admin-only
new UserAuthPool({
  allowedAuthFlows: ['ALLOW_USER_SRP_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],
  readAttributes: ['email', 'name'],
  writeAttributes: ['name']
});

Token lifetimes

Stacktape lets you control how long tokens issued by the user pool remain valid:

PropertyControlsAllowed valuesDefault
accessTokenValiditySecondsHow long access tokens (used for API authorization) are valid300 to 86400 seconds3600 (1 hour)
idTokenValiditySecondsHow long ID tokens (containing user profile claims) are valid300 to 86400 seconds3600 (1 hour)
refreshTokenValidityDaysHow long refresh tokens can obtain new access/ID tokens1 to 3650 days30
export default defineConfig(() => {
  const auth = new UserAuthPool({
    userVerificationType: 'email-code',
    accessTokenValiditySeconds: 3600,
    idTokenValiditySeconds: 3600,
    refreshTokenValidityDays: 30
  });

  return {
    resources: { auth }
  };
});

Shorter access token lifetimes reduce the window for token theft at the cost of more frequent refresh calls. Longer refresh token lifetimes keep users signed in longer but extend the window for session hijacking. The defaults, 1 hour for access and ID tokens and 30 days for refresh tokens, are a common starting point.

Before Stacktape v4, Cognito read accessTokenValiditySeconds and idTokenValiditySeconds in hours, so only values from 1 to 24 deployed. Such a value still means that many hours, and the CLI warns you to write it in seconds instead: accessTokenValiditySeconds: 1 becomes accessTokenValiditySeconds: 3600.

The client's TokenValidityUnits are seconds for access and ID tokens and days for refresh tokens. An overrides entry that sets AccessTokenValidity or IdTokenValidity on the client is read in seconds too, so a value written in hours before v4 fails to deploy. Set the unit you mean in the same override; the other units stay as they are:

resources:
  auth:
    type: user-auth-pool
    properties:
      userVerificationType: email-code
    overrides:
      AuthUserPoolClient:
        AccessTokenValidity: 2
        TokenValidityUnits:
          AccessToken: hours

Custom attributes

The schema property lets you define custom attributes stored on each user record. These are useful for data like role, plan, tenantId, or companyName that you want attached to the user profile and optionally included in JWT claims (via the preTokenGeneration hook).

export default defineConfig(() => {
  const auth = new UserAuthPool({
    userVerificationType: 'email-code',
    schema: [
      {
        name: 'role',
        attributeDataType: 'String',
        mutable: true,
        stringMinLength: 1,
        stringMaxLength: 50
      },
      {
        name: 'tenantId',
        attributeDataType: 'String',
        required: true,
        mutable: false,
        stringMinLength: 1,
        stringMaxLength: 128
      },
      {
        name: 'loginCount',
        attributeDataType: 'Number',
        mutable: true
      }
    ]
  });

  return {
    resources: { auth }
  };
});

Each attribute specifies a name, attributeDataType (e.g., String, Number), and optional constraints like required, mutable, stringMinLength, and stringMaxLength. Attributes marked developerOnlyAttribute: true are only accessible from backend code — they are not exposed to end users.

Cognito user pool custom attribute schemas are difficult to change after creation. Plan the schema carefully before deploying to production.

Firewall

Stacktape user authentication pools can be protected by a web application firewall that inspects requests to the Hosted UI and Cognito token endpoints. useFirewall is the Stacktape resource name of a web-app-firewall resource; it is not an inline WAF rule definition. Set it to the name of a WebAppFirewall resource in your stack.

useFirewall creates a WebACLAssociation between the user pool and the referenced firewall. AWS requires a regional WAF web ACL for Cognito user pool associations, so the referenced WebAppFirewall resource must use scope: 'regional'. A CDN-scoped firewall targets CloudFront and cannot be associated with a Cognito user pool. See the web application firewall page for firewall scope configuration.

export default defineConfig(() => {
  const firewall = new WebAppFirewall({
    scope: 'regional'
  });

  const auth = new UserAuthPool({
    userVerificationType: 'email-code',
    useFirewall: 'firewall'
  });

  return {
    resources: { firewall, auth }
  };
});

When to enable a firewall: Use it when your Hosted UI is publicly accessible and you want to protect against credential stuffing, bot traffic, or IP-based attacks. AWS WAF charges per web ACL and per million requests inspected — typically a few dollars per month for low-traffic apps, more at scale. When to skip it: For internal-only apps or apps that use custom UI with backend-only Cognito API calls, the firewall adds cost without significant benefit.

Email configuration

By default, Cognito sends emails (verification codes, password resets, admin invitations) through its built-in email service. This works for development but has low daily sending limits. For production, configure emailConfiguration.sesAddressArn with a verified SES identity to use your own sender address and get higher throughput:

  • sesAddressArn — ARN of a verified SES email or domain. Required for EMAIL_OTP MFA because Cognito must switch into DEVELOPER email sending mode.
  • from — the "From" address shown to recipients. Must be verified in SES.
  • replyToEmailAddress — where replies go. If not set, replies go to the from address or the default Cognito sender.

The inviteMessageConfig property customizes the email and SMS sent when an administrator creates a user account. Use {username} and {####} placeholders in the message body for the username and temporary password.

API Reference

UserAuthPoolProps
Click a property in the tree to see its description, default value, and full type.

Referenceable parameters

The following parameters can be easily referenced using $ResourceParam directive directive.

To learn more about referencing parameters, refer to referencing parameters.

id
  • Id of the userpool

  • Usage: $ResourceParam('<<resource-name>>', 'id')
clientId
  • Id of the userpool

  • Usage: $ResourceParam('<<resource-name>>', 'clientId')
domain
  • Domain of the userpool

  • Usage: $ResourceParam('<<resource-name>>', 'domain')

connectTo auto-injects STP_[RESOURCE_NAME]_ID, STP_[RESOURCE_NAME]_CLIENT_ID, and STP_[RESOURCE_NAME]_ARN as environment variables. The remaining parameters (providerUrl, domain, clientSecret) are accessible via $ResourceParam.

User Authentication Pool FAQ

When should I use a user auth pool vs a third-party auth service like Auth0?

Use a Stacktape user auth pool when you want authentication integrated with your AWS infrastructure (IAM permissions, API Gateway JWT validation, Lambda hooks) without managing another vendor. Use Auth0 or Clerk when you need advanced features like passwordless login with passkeys, pre-built UI components for multiple frameworks, or want to stay cloud-agnostic. Cognito's MAU-based pricing makes it cost-effective for most apps.

How much does Amazon Cognito cost?

Amazon Cognito uses a pay-per-monthly-active-user (MAU) pricing model, and Stacktape adds no markup on top. Native sign-in users (username/password) and federated identities (social login, SAML/OIDC) are billed at different rates. Check the AWS Cognito pricing page for current regional rates.

How do I protect API routes with the user pool?

Add a cognito authorizer to your HTTP API Gateway trigger integration and set authorizer.properties.userPoolName to your user pool resource name. API Gateway then validates the JWT on every request with no middleware needed — unauthorized requests receive a 401 before your code runs. For auth logic beyond JWT validation (API keys, database permission lookups), use the lambda authorizer type instead. See HTTP triggers for the full reference.

Which social and enterprise identity providers are supported?

The identityProviders property supports Google, Facebook, SignInWithApple, LoginWithAmazon, OIDC, and SAML — covering both consumer social login and enterprise SSO (Active Directory, Okta, Ping Identity via SAML or OIDC). Each provider requires a clientId and clientSecret; store them with the $Secret directive. Set allowOnlyExternalIdentityProviders: true (after configuring at least one provider) to disable password-based login entirely for a fully federated experience.

Can I migrate users from another auth system?

Yes. Configure the userMigration Lambda hook with a function that looks up users in your legacy system. When a user tries to sign in but does not exist in Cognito, the hook fires — your function validates credentials against the old system and returns the user profile. Cognito then creates the user transparently. This lets you migrate incrementally without a big-bang cutover or requiring users to re-register.

How do I add custom claims (roles, tenant IDs) to JWT tokens?

Use the preTokenGeneration Lambda hook. Your function receives the user's attributes and can add, modify, or suppress claims in the access and ID tokens before Cognito issues them. This is how you include roles, permissions, tenant IDs, or feature flags in the JWT without a separate lookup. Pair it with the schema property to store those values as custom attributes on each user. See the Lambda hooks section for all available trigger points.

Why does my Hosted UI custom domain fail to deploy?

A customDomain for the Hosted UI requires an ACM certificate in us-east-1, because Cognito serves custom domains through CloudFront, which only accepts certificates from that region. The domain must also be registered and verified in your Stacktape account. If you manage DNS outside Stacktape (e.g., Cloudflare), set customDomain.disableDnsRecordCreation: true so Stacktape does not try to create the record itself.