DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 87: Credentials

What is the Web Credentials API?

The Web Credentials API is a browser API that allows web applications to interact with credentials stored in the browser, such as usernames and passwords. It provides a programmatic way for developers to request, store, and retrieve credentials securely. This API is designed to enhance the user experience by streamlining the login process and improving security through the use of built-in credential managers.

Getting Started with the Web Credentials API

Let's jump into the practical side of things. To use the Web Credentials API, start by checking if the browser supports it:

if (navigator.credentials) {
  // Web Credentials API is supported
  // Continue with your code
} else {
  // Fallback to traditional authentication
Enter fullscreen mode Exit fullscreen mode

Storing Credentials

Storing credentials is a common task, especially in scenarios where you want users to stay logged in. Here's how you can store a username and password:

const credentials = new PasswordCredential({
  id: '',
  password: 'supersecret',
Enter fullscreen mode Exit fullscreen mode

Retrieving Credentials

Retrieving stored credentials is equally straightforward:

navigator.credentials.get({ password: true }).then((credential) => {
  if (credential) {
    // User is authenticated, proceed with the application logic
  } else {
    // User needs to log in
Enter fullscreen mode Exit fullscreen mode


1. Use Secure Contexts

Ensure your website is served over HTTPS. The Web Credentials API operates in secure contexts to prevent sensitive data from being intercepted.

2. Handle Edge Cases

Consider scenarios where the user has multiple accounts or where credentials need to be updated. The API provides methods to handle these cases gracefully.

Enter fullscreen mode Exit fullscreen mode

3. UI Customization

Customize the UI for credential requests using the mediation option. This can improve the user experience significantly.

  password: true,
  mediation: 'optional',
Enter fullscreen mode Exit fullscreen mode


Single Sign-On (SSO)

Implementing SSO becomes smoother with the Web Credentials API. Users can seamlessly log in across multiple services without repeatedly entering credentials.

Progressive Web Apps (PWAs)

For PWAs, where user engagement is paramount, the Web Credentials API facilitates a seamless login experience, enhancing user retention.

E-commerce Checkout

In e-commerce scenarios, where quick and secure authentication is crucial, the API can streamline the checkout process, reducing friction for users.

Top comments (1)

dhrn profile image
Dharan Ganesan