Login

A modular and accessible login control for Monster.js applications.

Import
the javascript logo
import { Login } from "@schukai/monster/source/components/form/login.mjs";
Source
the git logo
Package
the npm logo
Since
3.113.0

Log In

Use this form to access your account.

Two-factor authentication (2FA) enhances the security of your account.

Forgot Password

Reset your password using your email.

Two-Factor Authentication (2FA)

2FA requires you to enter a code sent to your device to log in. Request a code via email or SMS if needed.

This extra step ensures that your account remains secure.

Logged In

You are now logged in to your account.

Enter the Digits

Enter the verification digits received on your phone or email.

Introduction

The monster-login component is a complete, modular, and extensible authentication UI for Monster.js applications. It provides a secure and user-friendly login experience with support for classical username/password authentication, password recovery via e-mail, and full two-factor authentication flows. Designed with accessibility, internationalization, and customization in mind, it allows developers to integrate complex authentication processes without implementing the low-level details themselves.

The component follows Monster’s declarative option system, integrates seamlessly with custom backend endpoints, and exposes multiple callback hooks for validation, transformation, and custom business logic.

Key Features

  • Modular login flow: Includes separate collapsible sections for login, password recovery, digits input, second-factor authentication, and post-login success.
  • Structured Callback API: Callbacks for username and password recovery support a powerful return format (value, valid, message, stop), enabling custom validation logic, user feedback, and flow control — while remaining fully backward-compatible.
  • Custom form validation: Automatically highlights invalid inputs and displays contextual error messages. Validation covers username, password, email, and multi-digit verification codes.
  • Multi-language support: Labels and messages adapt automatically to the document’s locale. The component ships with translations for a broad set of languages, including English, German, French, Spanish, Chinese, Hindi, Portuguese, Russian, Japanese, and more.
  • Keyboard accessibility & usability: - Full keyboard navigation (Enter to submit)
    - Configurable accesskey shortcuts for fields and actions
    - Automatic focusing of the next relevant field across flow steps
  • Progressive authentication: Supports multi-step authentication: login → second factor → success state. The password reset flow also includes code verification via digits input.
  • Visual feedback with timeouts: All submission buttons provide consistent success/failure states, popper-based messages, and configurable display durations for user feedback.
  • Option-based configuration: Every component feature—labels, placeholders, classes, endpoints, behaviour—is configurable through data-monster-options or programmatically.
  • Access to internal events: Fires custom events such as:
    • login-success
    • digits-success
    • second-factor-success
    • redirect-to-first-success-url
    • monster-login-clicked
    allowing easy integration into application workflows.
  • Security-oriented design: The component expects backend-driven authentication and input validation, supports secure fetch configurations, and does not expose unnecessary internal state to the client.
  • Declarative HTML templates: Uses Monster’s templating and slot system for maximum flexibility when integrating custom headers, footers, or visual elements.

Benefits

Integrating monster-login significantly reduces the time and effort needed to implement a secure and polished authentication flow. Developers benefit from reusable form logic, built-in validation, consistent UI behavior, and automatic localization of labels and messages.

The component is ideal for both simple and advanced login scenarios—its modular structure allows swapping, extending, or customizing individual stages without affecting the rest of the flow. Additionally, the new structured callback system enables developers to embed complex custom validation rules, such as company-specific username formats or conditional business checks, without modifying the component itself.

Usage Context

The monster-login component is suitable for:

  • Public login pages of consumer-facing applications
  • Admin panels or internal operational tools
  • Business portals requiring multi-step login flows
  • Systems with mandatory two-factor authentication
  • Applications with custom validation requirements (e.g., customer number formats, pre-authentication controls)

It is especially useful in multilingual environments or where accessibility and consistent UX are important across devices and browsers.

Login Simple

The above markup demonstrates how to configure and extend the monster-login component for use within a Monster.js application. This example uses both data-monster-option-* attributes and named slots to customize behavior and content without modifying the internal structure of the component.

Configuration Options

The component is configured using declarative options via data-monster-option-* attributes. These attributes define the backend endpoints for the different parts of the login process:

  • data-monster-option-fetch-login-url: The URL endpoint for submitting the login credentials (username and password).
  • data-monster-option-fetch-digits-url: The URL used to verify digit codes received during password recovery.
  • data-monster-option-fetch-secondfactor-url: The URL to verify the second factor code for two-factor authentication (2FA).
  • data-monster-option-fetch-forgotpassword-url: The URL for submitting email addresses to request a password reset link.

Content Customization Using Slots

The component exposes several named slots that allow developers to inject custom content into specific sections of the login workflow. These slots are optional and enhance the user experience with context-specific headers and explanatory text. The following slots are used in the example:

  • login-header: Displays a heading and paragraph above the login form to guide the user.
  • login-footer: Provides additional context or messages below the login button (e.g., 2FA info).
  • forgot-password-header: Appears above the email input field when the user chooses to reset their password.
  • second-factor-header: Shown before the user inputs the second factor code. Useful for instructions.
  • second-factor-footer: Provides extra information below the second factor input.
  • logged-in-header: Displayed once the login is successful, confirming the login state.
  • logged-in-content: A customizable section for messages or navigation options after login.
  • digits-header: Displayed before entering the verification code during the password reset flow.

What Users See

Users interacting with this component will follow a guided flow:

  1. They are presented with a login form that includes a heading and description.
  2. If they click "Forgot Password?", a reset form appears with a custom message.
  3. Upon submitting a reset request, they are prompted to enter a verification code (digits) with helpful instructions.
  4. If the server requires it, a two-factor authentication screen is shown for additional verification.
  5. After successful login or verification, the user sees a confirmation message along with any post-login instructions or navigation links.

Customizable Areas

Developers can customize both the data (via data-monster-option-*) and the presentation (via slots) without altering the internal structure of the component. This makes it easy to integrate the component into different projects with varied design or text requirements.

Log In

Use this form to access your account.

Two-factor authentication (2FA) enhances the security of your account.

Forgot Password

Reset your password using your email.

Two-Factor Authentication (2FA)

2FA requires you to enter a code sent to your device to log in. Request a code via email or SMS if needed.

This extra step ensures that your account remains secure.

Logged In

You are now logged in to your account.

Enter the Digits

Enter the verification digits received on your phone or email.

Javascript

import '@schukai/monster/source/components/form/login.mjs';

HTML

<monster-login
        data-monster-option-fetch-login-url="/login"
        data-monster-option-fetch-digits-url="/digits"
        data-monster-option-fetch-secondfactor-url="/secondFactorDigits"
        data-monster-option-fetch-forgotpassword-url="/forgot-password"
>
    <h2 slot="login-header">Log In</h2>
    <p slot="login-header">
        Use this form to access your account.
    </p>
    <p slot="login-footer">Two-factor authentication (2FA) enhances the security of your account.</p>

    <h2 slot="forgot-password-header">Forgot Password</h2>
    <p slot="forgot-password-header">
        Reset your password using your email.
    </p>

    <h2 slot="second-factor-header">Two-Factor Authentication (2FA)</h2>
    <p slot="second-factor-header">
        2FA requires you to enter a code sent to your device to log in. Request a code via email or SMS if needed.
    </p>
    <p slot="second-factor-footer">This extra step ensures that your account remains secure.</p>

    <h2 slot="logged-in-header">Logged In</h2>
    <p slot="logged-in-content">
        You are now logged in to your account.
    </p>

    <h2 slot="digits-header">Enter the Digits</h2>
    <p slot="digits-header">
        Enter the verification digits received on your phone or email.
    </p>

</monster-login>

Stylesheet

/** no additional stylesheet is defined **/

Login With Forgot Password

This example demonstrates how to enable and use the "Forgot Password" feature in the monster-login component. When users click the link, a separate view appears where they can enter their email to request a reset link or code.

Feature Activation

The data-monster-option-features-forgotpassword attribute must be set to true. The component will automatically display a "Forgot Password?" link beneath the login form.

Workflow

  1. The user clicks on the "Forgot Password?" link.
  2. A new view appears with an email input field.
  3. Upon submission, the backend is called using the configured URL.
  4. If successful, the user is asked to enter a verification code (digits).

Backend Requirements

  • The data-monster-option-fetch-forgotpassword-url must point to a working endpoint that accepts email addresses.
  • The data-monster-option-fetch-digits-url must point to the verification code validation endpoint.

Login

Please log in to continue.

Forgot Your Password?

Enter your email to receive a reset link.

Verification Code

Check your inbox and enter the code you received.

Welcome Back

You're now logged in successfully.

Javascript

import '@schukai/monster/source/components/form/login.mjs';

HTML

<monster-login
  data-monster-option-fetch-login-url="/login"
  data-monster-option-fetch-forgotpassword-url="/forgot-password"
  data-monster-option-fetch-digits-url="/digits"
  data-monster-option-features-forgotpassword="true"
>
  <h2 slot="login-header">Login</h2>
  <p slot="login-header">Please log in to continue.</p>

  <h2 slot="forgot-password-header">Forgot Your Password?</h2>
  <p slot="forgot-password-header">Enter your email to receive a reset link.</p>

  <h2 slot="digits-header">Verification Code</h2>
  <p slot="digits-header">Check your inbox and enter the code you received.</p>

  <h2 slot="logged-in-header">Welcome Back</h2>
  <p slot="logged-in-content">You're now logged in successfully.</p>
</monster-login>

Stylesheet

/** no additional stylesheet is defined **/

Login With Second Factor

This example demonstrates how to configure the monster-login component to support a two-factor authentication (2FA) login process. When the backend signals that a second factor is required, the component automatically switches to the verification step without any additional code.

How It Works

  1. The user enters a username and password.
  2. The backend responds with HTTP 401 and a WWW-Authenticate header that contains 2fa.
  3. The component interprets this automatically and opens the 2FA view.
  4. The user enters the code from their authenticator app or SMS.
  5. Upon success, the component fires second-factor-success and the login completes.

Required Backend Endpoints

  • data-monster-option-fetch-login-url: Validates username and password.
  • data-monster-option-fetch-secondfactor-url: Validates the second factor code.

UI Customization

Slots allow you to customize the displayed messages for the login, the second factor prompt, and the success confirmation:

  • login-header: Shown before entering username/password.
  • second-factor-header: Shown above the 2FA field.
  • second-factor-footer: Additional information below the 2FA input.
  • logged-in-header and logged-in-content: Shown when login is complete.

Developer Notes

No additional scripting is required to trigger the second factor step. The component reacts entirely based on backend responses and options.

Secure Login

Enter your username and password to start the secure login process.

Two-Factor Authentication

Enter the 2FA code from your authentication app or device.

This additional step protects your account against unauthorized access.

Login Successful

You have successfully completed 2FA and logged in.

Javascript

import '@schukai/monster/source/components/form/login.mjs';

HTML

<monster-login
  data-monster-option-fetch-login-url="/login"
  data-monster-option-fetch-secondfactor-url="/second-factor"
>
  <h2 slot="login-header">Secure Login</h2>
  <p slot="login-header">
    Enter your username and password to start the secure login process.
  </p>

  <h2 slot="second-factor-header">Two-Factor Authentication</h2>
  <p slot="second-factor-header">
    Enter the 2FA code from your authentication app or device.
  </p>
  <p slot="second-factor-footer">
    This additional step protects your account against unauthorized access.
  </p>

  <h2 slot="logged-in-header">Login Successful</h2>
  <p slot="logged-in-content">
    You have successfully completed 2FA and logged in.
  </p>
</monster-login>

Stylesheet

/** no additional stylesheet is defined **/

Login With Success Redirect

This example demonstrates how to enable automatic redirection after a successful login using the monster-login component.

Feature Activation

The option data-monster-option-features-redirecttofirstsuccessurl must be set to true. After the login flow completes successfully, the user is redirected to the first entry in the successUrls array.

Redirect Behavior

  1. After login and/or second factor validation is complete, the component waits for the configured success timeout.
  2. The first URL from the successUrls list is used for redirection.
  3. If no URLs are defined, no redirection occurs.

Configuration Requirements

  • data-monster-option-fetch-login-url must point to a working login endpoint.
  • data-monster-option-features-redirecttofirstsuccessurl must be set to true.
  • You can optionally override successUrls via data-monster-option-successurls or JS API.

UI Customization

The logged-in-header and logged-in-content slots will not be visible if redirection occurs immediately. If you want to delay redirection for a message display, use the timeoutForSuccess option.

Login

Please log in to be redirected to your dashboard.

Redirecting...

You will be redirected shortly after login.

Javascript

import '@schukai/monster/source/components/form/login.mjs';

HTML

<monster-login
  data-monster-option-fetch-login-url="/login"
  data-monster-option-features-redirecttofirstsuccessurl="true"
  data-monster-option-successurls='[{"label": "Dashboard", "url": "/dashboard"}]'
  data-monster-option-timeoutforsuccess="1500"
>
  <h2 slot="login-header">Login</h2>
  <p slot="login-header">Please log in to be redirected to your dashboard.</p>

  <h2 slot="logged-in-header">Redirecting...</h2>
  <p slot="logged-in-content">You will be redirected shortly after login.</p>
</monster-login>

Stylesheet

/** no additional stylesheet is defined **/

Login With Actions

This example demonstrates how to use the actions.click callback in the monster-login component.

Purpose

The actions.click callback allows developers to run custom logic whenever a user clicks inside the login control. This is useful for logging, telemetry, or intercepting behavior before the login is processed.

How It Works

  1. The component emits the monster-login-clicked event on any internal click.
  2. If actions.click is defined, the callback receives the original click event.
  3. Developers can inspect the clicked element and perform side effects.

Example Use Cases

  • Log when a user interacts with the login form
  • Send analytics data
  • Prevent clicks or show confirmations before submitting

Notes

The click callback is optional and non-blocking. If it returns nothing, the login flow proceeds as usual.

Login with Custom Actions

This example logs a message when the user clicks anywhere in the login control.

Javascript

import "@schukai/monster/source/components/form/login.mjs";

const login = document.getElementById("customLogin");

login.setOption("actions.click", (event) => {
  const clicked = event.target;
  console.log("[monster-login] Click detected on:", clicked);
});

HTML

<monster-login id="customLogin" data-monster-option-fetch-login-url="/login">
  <h2 slot="login-header">Login with Custom Actions</h2>
  <p slot="login-header">
    This example logs a message when the user clicks anywhere in the login
    control.
  </p>
</monster-login>

Stylesheet

/** no additional stylesheet is defined **/

Login Custom Callbacks

This example demonstrates how to use the callbacks.username and callbacks.forgotPassword options in the monster-login component.

What Callbacks Do

These callbacks allow you to validate or transform user input before it is submitted to the backend. You can return:

  • A modified value (e.g., value.toLowerCase())
  • false to indicate validation failure
  • An object like { value, valid, message, stop } to control behavior in detail

Username Callback

Used to validate the username before login. In this example, usernames shorter than 3 characters are rejected.

Forgot Password Callback

Used to validate the email address before requesting a reset code. This example checks if the address ends with @example.com.

Behavior

  1. If a callback returns false or valid: false, a message is shown and submission is blocked.
  2. If stop: true is returned, no further processing happens.
  3. The value is always used as the input sent to the backend.

Custom Messages

You can define a message in the callback result to show a specific validation error.

Login with Validation

The username must be at least 3 characters long.

Forgot Password

Only emails ending with @example.com are accepted.

Welcome

Login successful.

Javascript

import "@schukai/monster/source/components/form/login.mjs";

const login = document.getElementById("customLogin");

login.setOption("callbacks.username", (value) => {
  if (typeof value !== "string" || value.trim().length < 3) {
    return {
      valid: false,
      message: "Username must be at least 3 characters.",
    };
  }

  return value.trim();
});

login.setOption("callbacks.forgotPassword", (value) => {
  if (!value.endsWith("@example.com")) {
    return {
      valid: false,
      message: "Only @example.com addresses are allowed.",
    };
  }

  return value.toLowerCase();
});

HTML

<monster-login
  id="customLogin"
  data-monster-option-fetch-login-url="/login"
  data-monster-option-fetch-forgotpassword-url="/forgot-password"
>
  <h2 slot="login-header">Login with Validation</h2>
  <p slot="login-header">The username must be at least 3 characters long.</p>

  <h2 slot="forgot-password-header">Forgot Password</h2>
  <p slot="forgot-password-header">
    Only emails ending with <code>@example.com</code> are accepted.
  </p>

  <h2 slot="logged-in-header">Welcome</h2>
  <p slot="logged-in-content">Login successful.</p>
</monster-login>

Stylesheet

/** no additional stylesheet is defined **/

Login Multilingual

This example demonstrates the multilingual capabilities of the monster-login component. Labels, placeholders, and error messages are automatically localized based on the document language.

How It Works

  1. The component reads the language setting from <html lang="...">.
  2. It loads default labels and messages for supported languages (e.g., de, es, fr, etc.).
  3. If the language is not recognized, English is used as fallback.

Supported Languages

Monster.js supports many languages including German (de), Spanish (es), French (fr), Italian (it), Chinese (zh), Russian (ru), and more.

Customization

You can override any localized label by using the labels option programmatically or via data-monster-option-labels-* attributes.

Notes

  • The example uses lang="es" (Spanish) on the root HTML element.
  • All UI labels are automatically translated, including validation messages.

Iniciar sesión

Use este formulario para acceder a su cuenta.

¿Olvidaste tu contraseña?

Solicita un enlace de restablecimiento por correo electrónico.

Ingrese el código

Escriba el código que recibió por correo electrónico o SMS.

Autenticación de dos factores

Ingrese su código 2FA desde la aplicación autenticadora.

Sesión iniciada

Ahora ha iniciado sesión correctamente.

Javascript

import "@schukai/monster/source/components/form/login.mjs";

HTML

<!doctype html>
<html lang="es">
  <head>
    <meta charset="UTF-8" />
    <title>Monster Login Multilingual</title>
  </head>

  <body>
    <monster-login
      id="customLogin"
      data-monster-option-fetch-login-url="/login"
      data-monster-option-fetch-forgotpassword-url="/forgot-password"
      data-monster-option-fetch-digits-url="/digits"
      data-monster-option-fetch-secondfactor-url="/second-factor"
    >
      <h2 slot="login-header">Iniciar sesión</h2>
      <p slot="login-header">Use este formulario para acceder a su cuenta.</p>

      <h2 slot="forgot-password-header">¿Olvidaste tu contraseña?</h2>
      <p slot="forgot-password-header">
        Solicita un enlace de restablecimiento por correo electrónico.
      </p>

      <h2 slot="digits-header">Ingrese el código</h2>
      <p slot="digits-header">
        Escriba el código que recibió por correo electrónico o SMS.
      </p>

      <h2 slot="second-factor-header">Autenticación de dos factores</h2>
      <p slot="second-factor-header">
        Ingrese su código 2FA desde la aplicación autenticadora.
      </p>

      <h2 slot="logged-in-header">Sesión iniciada</h2>
      <p slot="logged-in-content">Ahora ha iniciado sesión correctamente.</p>
    </monster-login>
  </body>
</html>

Stylesheet

/** no additional stylesheet is defined **/

Login Custom Buttons

This example shows how to apply custom styling classes to the buttons used in the monster-login component using the classes.button option.

How It Works

  • The value of classes.button is applied to every button inside the login flow.
  • This includes the login button, forgot password submit button, digits submit button, and second factor button.

Use Case

By overriding the button class, you can apply your project’s design system, theming, or custom styles.

Example

This example uses a custom class btn-ghost to give buttons a minimal transparent look. You can freely replace this with any class from your CSS.

Customization Options

  • Set data-monster-option-classes-button in HTML
  • Or use JavaScript: setOption("classes.button", "your-class")

Note

This option only affects button styling — logic and behavior remain unchanged.

Custom Styled Login

These buttons use a custom class to change their appearance.

Welcome

You have successfully logged in.

Javascript

import "@schukai/monster/source/components/form/login.mjs";

HTML

<monster-login
  id="customLogin"
  data-monster-option-fetch-login-url="/login"
  data-monster-option-fetch-forgotpassword-url="/forgot-password"
  data-monster-option-fetch-digits-url="/digits"
  data-monster-option-fetch-secondfactor-url="/second-factor"
  data-monster-option-classes-button="btn-ghost"
>
  <h2 slot="login-header">Custom Styled Login</h2>
  <p slot="login-header">
    These buttons use a custom class to change their appearance.
  </p>

  <h2 slot="logged-in-header">Welcome</h2>
  <p slot="logged-in-content">You have successfully logged in.</p>
</monster-login>

Stylesheet

/* Not included in component. Must be in global styles. */
.btn-ghost {
  background-color: transparent;
  border: 1px solid #444;
  color: #444;
  padding: 0.5em 1em;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.btn-ghost:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

Login Accessibility

This example demonstrates how to improve keyboard accessibility in the monster-login component using the accessKeys option.

What Are Access Keys?

Access keys define keyboard shortcuts that allow users to quickly activate key actions without using the mouse. These can be especially helpful for screen reader users or for fast navigation.

Available Target Actions

  • login: Submit the login form
  • forgot: Trigger the forgot password flow
  • resend: Request a new code (in digits or 2FA view)

How It Works

  1. The component listens for key combinations (e.g., Alt + L)
  2. If the defined access key is pressed, the associated action is triggered
  3. The browser may display underlined letters depending on OS and browser behavior

Configuration

Access keys are defined via the data-monster-option-accesskeys attribute using a JSON object. For example:


    {
    "login": "l",
    "forgot": "f",
    "resend": "r"
    }
  

This assigns Alt + L to login, Alt + F to forgot password, etc.

Note

Shortcut behavior may vary across browsers and platforms. Make sure your shortcuts do not conflict with browser or OS-level access keys.

Accessible Login

Use Alt + L to log in, Alt + F to reset your password.

Forgot Password

Triggered by pressing Alt + F.

Logged In

Login complete.

Javascript

import "@schukai/monster/source/components/form/login.mjs";

HTML

<monster-login
  id="customLogin"
  data-monster-option-fetch-login-url="/login"
  data-monster-option-fetch-forgotpassword-url="/forgot-password"
  data-monster-option-accesskeys='{"login": "l", "forgot": "f", "resend": "r"}'
>
  <h2 slot="login-header">Accessible Login</h2>
  <p slot="login-header">
    Use <kbd>Alt</kbd> + <kbd>L</kbd> to log in, <kbd>Alt</kbd> +
    <kbd>F</kbd> to reset your password.
  </p>

  <h2 slot="forgot-password-header">Forgot Password</h2>
  <p slot="forgot-password-header">
    Triggered by pressing <kbd>Alt</kbd> + <kbd>F</kbd>.
  </p>

  <h2 slot="logged-in-header">Logged In</h2>
  <p slot="logged-in-content">Login complete.</p>
</monster-login>

Stylesheet

/* Not included in component. Must be in global styles. */
.btn-ghost {
  background-color: transparent;
  border: 1px solid #444;
  color: #444;
  padding: 0.5em 1em;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.btn-ghost:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

Login Style Overrides

This example demonstrates how to override the visual styles of the monster-login component using the ::part pseudo-element and global classes.

Why Style Overrides?

Because the component uses Shadow DOM, direct styling from outside is limited. Instead, the component exposes internal parts via the ::part() mechanism, allowing developers to customize appearance in a controlled way.

Available Parts

  • container: Main wrapper
  • field: Each form field
  • button: All action buttons
  • error: Error messages
  • label: Form labels
  • input: Input elements

Styling Options

  1. Use a global stylesheet with ::part(...) selectors
  2. Optionally add your own global wrapper classes to target outer layout

Browser Support

The ::part pseudo-element is supported in all modern browsers, but not in legacy versions like IE11.

Important

You cannot target internal elements directly via class names. Use ::part only for exposed parts.

Styled Login

This login box has scoped styles using ::part on its ID only.

Login Successful

You are now logged in with style 🎨

Javascript

import "@schukai/monster/source/components/form/login.mjs";

HTML

<style>
  monster-login::part(container) {
    background-color: #fefefe;
    border: 1px solid #ccc;
    border-radius: 8px;
    padding: 1.5em;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  monster-login::part(button) {
    background-color: #0044cc;
    color: white;
    padding: 0.6em 1.2em;
    font-weight: bold;
    border: none;
    border-radius: 4px;
  }

  monster-login::part(button):hover {
    background-color: #003399;
  }

  monster-login::part(input) {
    border-radius: 4px;
    border: 1px solid #aaa;
    padding: 0.5em;
  }

  monster-login::part(label) {
    font-weight: bold;
  }

  monster-login::part(error) {
    color: #c00;
    font-style: italic;
  }
</style>

<monster-login
  id="customLogin"
  data-monster-option-fetch-login-url="/login"
  data-monster-option-fetch-forgotpassword-url="/forgot-password"
  data-monster-option-fetch-digits-url="/digits"
  data-monster-option-fetch-secondfactor-url="/second-factor"
>
  <h2 slot="login-header">Styled Login</h2>
  <p slot="login-header">
    This login box has custom visual styling applied using <code>::part</code>.
  </p>

  <h2 slot="logged-in-header">Login Successful</h2>
  <p slot="logged-in-content">You are now logged in with style 🎨</p>
</monster-login>

Stylesheet

/* Not included in component. Must be in global styles. */
.btn-ghost {
  background-color: transparent;
  border: 1px solid #444;
  color: #444;
  padding: 0.5em 1em;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.btn-ghost:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

Component Design

The monster-login component is implemented using the Shadow DOM. This encapsulation technique ensures that the component's structure and styles are isolated from the rest of the document. By operating inside a shadow root, it prevents external CSS or JavaScript from unintentionally altering its internal layout or behavior.

Shadow DOM and Accessibility

Because the component uses the Shadow DOM, its internal elements are not directly accessible from outside. This promotes consistency and reliability in both design and interaction. To preserve accessibility, focusable elements like input fields and buttons are correctly managed, and keyboard interaction is supported throughout the login flow.

Customizing Through Exported Parts

Although the internal structure is encapsulated, the component exposes key elements through exported parts. These parts can be styled externally using the CSS part pseudo-element, allowing for targeted customization of visual elements without breaking encapsulation.

Available Part Attributes

SectionElementPart AttributeExported As
Collapselogin-collapsecontrol, container, deco
Fieldsetlogin-field-setcontrol, header, title, container, content, collapse
Label (username)login-label-
Password Labellogin-password-label-
Login Buttonlogin-buttoncontrol, button, popper, message, button-button, button-control
Forgot Password Linkforgot-password-link-
Footer Slotlogin-footerslot
Collapseforgot-password-collapsecontrol, container, deco
Fieldsetforgot-password-field-setcontrol, header, title, container, content, collapse
Email Labelforgot-password-label-
Request Link Buttonrequest-link-buttoncontrol, button, popper, message, button-button, button-control
Login Linklogin-link-
Footer Slotforgot-password-footerslot
Collapsesecond-factor-collapsecontrol, container, deco
Fieldsetsecond-factor-field-setcontrol, header, title, container, content, collapse
Labelsecond-factor-label-
Send Code ButtonsecondFactor-digits-buttoncontrol, button, popper, message, button-button, button-control
Reset Linkreset-login-process-link-
Footer Slotsecond-factor-footerslot
Collapsedigits-collapsecontrol, container, deco
Fieldsetdigits-field-setcontrol, header, title, container, content, collapse
Labeldigits-label-
Send Digits Buttondigits-buttoncontrol, button, popper, message, button-button, button-control
Reset Linkreset-login-process-link-
Footer Slotdigits-footerslot
Collapselogged-in-collapsecontrol, container, deco
Header Slotlogged-in-headerslot
Content Slotlogged-in-contentslot
Footer Slotlogged-in-footerslot

You can customize the appearance of these parts by using the ::part() selector in your CSS:


monster-login::part(login-button) {
    background-color: #007acc;
    color: white;
    font-weight: bold;
    border-radius: 4px;
}

Explanation of the Example

  • monster-login::part(login-button): Applies custom styles to the login button, changing its background color, text color, font weight, and border radius.

Accessibility

The component follows accessibility best practices to ensure a seamless experience for all users. This includes:

  • Use of proper label elements to describe input fields.
  • Focus management between input steps and buttons.
  • Support for keyboard interaction, including Enter key handling for form submission.
  • Consistent feedback through visual cues and screen reader messages when inputs are invalid or submission fails.

These features help ensure the component is usable in assistive contexts, including screen readers and keyboard-only navigation.

HTML Structure

<monster-login></monster-login>

JavaScript Initialization

const element = document.createElement('monster-login');
document.body.appendChild(element);

Exported

Login

Derived from

CustomElement

Options

The Options listed in this section are defined directly within the class. This class is derived from several parent classes, including the CustomElement class. Therefore, it inherits Options from these parent classes. If you cannot find a specific Options in this list, we recommend consulting the documentation of the CustomElement.

Option
Type
Default
Description
templates
object
Template definitions
templates.main
string
undefined
The main HTML template used for rendering the login form
labels
object
undefined
Label definitions used for localization and form messages
labels.username
string
undefined
Label for the username or email field
labels.password
string
undefined
Label for the password field
labels.login
string
undefined
Label for the login button
labels.forgotPasswordLink
string
undefined
Text for the "forgot password" link
labels.mailAddress
string
undefined
Label for the email input in password reset flow
labels.requestLink
string
undefined
Label for the button that sends a password reset code
labels.digits
string
undefined
Label for the digits input field
labels.loginLink
string
undefined
Label for the back-to-login link
labels.secondFactor
string
undefined
Label for the second factor authentication input
labels.sendDigits
string
undefined
Label for the button that submits the digits input
labels.sendSecondFactorDigits
string
undefined
Label for the button that submits the second factor code
labels.resetLoginProcess
string
undefined
Label for the link to return to the login form
labels.messageEmptyUserName
string
undefined
Message shown when username is empty
labels.messageEmptyPassword
string
undefined
Message shown when password is empty
labels.messageEmptyBoth
string
undefined
Message shown when both username and password are empty
labels.messageEmptyEmail
string
undefined
Message shown when email field is empty
labels.messageInvalidEmail
string
undefined
Message shown when an invalid email address is entered
labels.digitsEmpty
string
undefined
Message shown when digits field is empty
labels.digitsInvalid
string
undefined
Message shown when digits input is invalid
labels.messageLoginFailed
string
undefined
Message shown on failed login attempt
labels.messageForbidden
string
undefined
Message shown on successful login with insufficient permissions
labels.messageSomethingWentWrong
string
undefined
Fallback error message
labels.messageThisFormIsNotConfigured
string
undefined
Message shown if no backend URL is configured
labels.messagePasswordResetDisabled
string
undefined
Message shown if password reset is disabled due to 2FA
classes
object
Class definitions for visual styling
classes.usernameInvalid
string
CSS class applied when username is invalid
classes.passwordInvalid
string
CSS class applied when password is invalid
classes.emailInvalid
string
CSS class applied when email input is invalid
classes.button
string
monster-button-outline-primary
CSS class applied to all form buttons
disabled
boolean
false
If true, disables interaction with the component
features
object
Feature flags to toggle optional behavior
features.forgotPassword
boolean
true
Enables the forgot password flow
features.redirectToFirstSuccessUrl
boolean
false
If true, redirects to the first success URL after login
actions
object
undefined
Action definitions for custom event handling
actions.click
function
undefined
Callback function for generic click actions within the login component
callbacks
object
Optional callback hooks for modifying internal behavior
callbacks.username
function
A function that receives and can transform the entered username before submission
callbacks.forgotPassword
function
A function that receives and can transform the entered email before submission
digits
number
6
Number of digits required for second factor or password reset code input
successUrls
object[]
undefined
List of URLs shown after successful login (e.g., home or logout)
successUrls.label
string
undefined
Label for the success URL (displayed)
successUrls.url
string
undefined
Actual target URL
timeoutForMessage
number
3500
Duration in milliseconds to show error messages
timeoutForSuccess
number
1000
Duration in milliseconds before triggering the post-login success state
accessKeys
object
Keyboard access keys for accessibility and shortcuts
accessKeys.loginLink
string
x
Access key for switching to login form
accessKeys.username
string
u
Access key for focusing the username field
accessKeys.password
string
p
Access key for focusing the password field
fetch
object
undefined
Definitions for backend requests to support login workflows
placeholder
object
Placeholder text for input fields
placeholder.username
string
Placeholder for the username field
placeholder.password
string
Placeholder for the password field
placeholder.email
string
Placeholder for the email field
fetch.login
object
undefined
Fetch config for login request
fetch.login.url
string
Endpoint to post login credentials to
fetch.login.method
string
POST
HTTP method for login (e.g., "POST")
fetch.login.mode
string
same-origin
Fetch mode (e.g., "same-origin")
fetch.login.headers
object
undefined
HTTP headers to be sent with the login request
fetch.login.headers.accept
string
undefined
Accept header value
fetch.login.headers.Content-Type
string
undefined
Content-Type header value
fetch.login.credentials
string
same-origin
Credential mode (e.g., "same-origin")
fetch.forgotPassword
object
undefined
Fetch config for password reset code request
fetch.forgotPassword.url
string
Endpoint to request a reset link/code
fetch.forgotPassword.method
string
POST
HTTP method
fetch.forgotPassword.mode
string
same-origin
Fetch mode
fetch.forgotPassword.headers
object
undefined
Headers
fetch.forgotPassword.headers.accept
string
undefined
Accept header
fetch.forgotPassword.headers.Content-Type
string
undefined
Content-Type header
fetch.forgotPassword.credentials
string
same-origin
Credential mode
fetch.digits
object
undefined
Fetch config for submitting password reset code
fetch.digits.url
string
Endpoint for validating the code
fetch.digits.method
string
POST
HTTP method
fetch.digits.mode
string
same-origin
Fetch mode
fetch.digits.headers
object
undefined
Headers
fetch.digits.headers.accept
string
undefined
Accept header
fetch.digits.headers.Content-Type
string
undefined
Content-Type header
fetch.digits.credentials
string
same-origin
Credential mode
fetch.secondFactor
object
undefined
Fetch config for submitting second factor code
fetch.secondFactor.url
string
Endpoint to validate second factor code
fetch.secondFactor.method
string
POST
HTTP method
fetch.secondFactor.mode
string
same-origin
Fetch mode
fetch.secondFactor.headers
object
undefined
Headers
fetch.secondFactor.headers.accept
string
undefined
Accept header
fetch.secondFactor.headers.Content-Type
string
undefined
Content-Type header
fetch.secondFactor.credentials
string
same-origin
Credential mode

  • since
  • deprecated

Properties and Attributes

The Properties and Attributes listed in this section are defined directly within the class. This class is derived from several parent classes, including the CustomElement class and ultimately from HTMLElement. Therefore, it inherits Properties and Attributes from these parent classes. If you cannot find a specific Properties and Attributes in this list, we recommend consulting the documentation of the CustomElement.

  • data-monster-options: Sets the configuration options for the collapse component when used as an HTML attribute.
  • data-monster-option-[name]: Sets the value of the configuration option [name] for the collapse component when used as an HTML attribute.

Methods

The methods listed in this section are defined directly within the class. This class is derived from several parent classes, including the CustomElement class and ultimately from HTMLElement. Therefore, it inherits methods from these parent classes. If you cannot find a specific method in this list, we recommend consulting the documentation of the CustomElement.

Behavioral methods

openDigits()
Opens the digits collapse and focuses the digit control.
openForgotPassword()
Throws
  • {Error} If the feature is not enabled
Opens the forgot password collapse. If the feature forgotPassword is not enabled, an error will be thrown.
openLoggedIn()
Opens the logged in collapse. If the feature redirectToFirstSuccessUrl is enabled, the user will be redirected to the first success URL.
openLogin()
Opens the login collapse and focuses the username control.
openSecondFactor()
Opens the second factor collapse and focuses the second factor control.

Static methods

[instanceSymbol]()
This method is called by the instanceof operator.
getCSSStyleSheet()
Returns
  • {CSSStyleSheet[]}
getTag()
Returns
  • {string}

Lifecycle methods

Lifecycle methods are called by the environment and are usually not intended to be called directly.

[assembleMethodSymbol]()
Returns
  • {void}

Events

The component emits the following events:

  • login-success
    Fired after successful login (always)
  • redirect-to-first-success-url
    Fired if feature redirectToFirstSuccessUrl is enabled
  • second-factor-success
    Fired after successful second factor validation
  • digits-success
    Fired after successful password reset code validation
  • monster-login-clicked
    Fired on any click inside the login control (before internal handling)

For more information on how to handle events, see the mdn documentation.

The current width of the area is too small to display the content correctly.