Klarna Docs - Web SDK integration

Web SDK integration

Integrate Sign in with Klarna to offer a fast, simple and smoooth login to your customers.

Implementing Sign in with Klarna on your website involves five essential steps:

  • Display the Sign in with Klarna Button
  • Select UI Mode
  • Handle Events
  • Finalize the Flow
  • Integrate into Purchase Flow

1. Display the Sign in with Klarna button.

Load the Klarna JavaScript library on pages where the Sign in with Klarna button will be featured.

HTML
<script defer 
src="https://js.klarna.com/web-sdk/v1/klarna.js"><
/script>

Typically within login components or account pages. Ensure the library is included only once to prevent conflict.

Next, initialize and mount the Sign in with Klarna button within your desired container by: 

  • Initialize Klarna by using Klarna.init() with your client_id, specifying the environment and locale. Refer to the Before you start article for instructions on how to obtain your client_id.
  • Initiate the creation of the Sign in with Klarna button using klarna.Identity.button(), supplying it with configuration options including scopes, redirectUri, interactionMode, hideOverlay, shape, theme, and logoAlignment. Customize these settings to align with your website's aesthetic and authentication needs. Refer to the  table below which lists the available scopes and how they correspond to claims and permissions. 
HTML
<script>
  window.onload = async function () {
    const klarnaSDK = await Klarna.init({
      clientId: "klarna_live_client_id...",
      environment: "production",
      locale: "en-GB"
    });

    const siwkButton = klarnaSDK.Identity.button({
      scope: "profile:email profile:phone profile:billing_address",

An example of how to initialize and mount the Sign in with Klarna button.

For a custom button style, you can create your own button UI and integrate the Sign in with Klarna flow into it. Refer to our Custom button article for essential design considerations.

HTML
<button id="custom-button"></button>

<script>
  window.onload = async function () {
    const klarnaSDK = await Klarna.init(...);
    const siwkButton = klarnaSDK.Identity.button(...);
    siwkButton.attach("#custom-button");
  }
</script>

Here’s an example of code to custom the button.

The table below lists the available scopes and how they correspond to claims and permissions. 

ScopeClaimsTypeCan be toggled off
profile:namegiven_namestringNo
profile:namefamily_namestringNo
profile:emailemailstring (Email)No
profile:emailemail_verifiedboolean
profile:phonephonestring (E. 164)No
profile:phonephone_verifiedboolean
profile:billing_addressstreet_addressstringYes
profile:billing_addressstreet_address2string
profile:billing_addresspostal_codestring
profile:billing_addresscitystring
profile:billing_addressregionstring
profile:billing_addresscountrystring (ISO 3166-1 alpha-2)
profile:national_idnational_idstringYes
profile:countrycountrystring (ISO 3166-1 alpha-2)Yes

Remember to always add 'openid', 'offline_access' and 'payment:request:create' scopes to receive full functionality of Sign in with Klarna.

The mock-ups below show how users will see required versus optional scopes when entering the Sign in with Klarna flow.   

The Sign in with Klarna flow can be initiated in two main modes: POPUP or REDIRECT. You have the option to explicitly select the preferred mode or let the SDK automatically decide the most suitable one based on user's conditions or instance, it may opt for a REDIRECT if POPUP blockers are enabled. By default, POPUP mode is activated for web browsers, whereas the REDIRECT mode is favored for mobile browsers.

To specify the desired behavior, utilize the interactionMode parameter in your script, with the following values:

  • POPUP
  • REDIRECT
  • DEVICE_BEST (default) - lets the SDK determine the optimal choice between POPUP and REDIRECT (if implemented).

To successfully implement the REDIRECT mode, below prerequisites must be met:

  • The redirect URL must be whitelisted and share the same domain as the initiating page to prevent fallback to popup mode due to domain mismatch.
  • The SDK must receive the redirect page's URL, where the authentication process resumes post-login. This URL should be passed to the script using the redirectUri parameter.
  • The SDK needs to be integrated on the redirect page.
  • It's essential to handle the events triggered by the login process on the redirect page, ensuring a seamless user experience from start to finish.
HTML
<script defer
  src="https://js.klarna.com/web-sdk/v1/klarna.js">
</script>

<script>
  window.onload = async function () {
    const klarnaSDK = await Klarna.init({
      clientId: "klarna_live_client_elZGI1B5dHBIRWcjZrNldnbEVj[...]",
      environment: "production",
      locale: "en-GB"

An example of where you need to implement the logic.

The integration process for Sign in with Klarna involves handling four critical events that mark different stages in the identity lifecycle:

  • ready: Triggered after the button has been mounted and displayed to the customer, showing it’s ready to be clicked.
  • clicked: Triggered when the Sign in with Klarna button is clicked by the user, initiating the sign-in process.
  • signin: Occurs after the user successfully completes the login and consent flow, at which point the tokens are generated. Remember to implement signin and error event handlers on the redirect page.
HTML
siwkButton.on("ready", () => {
   // implement logic
});

siwkButton.on("click", () => {
   // implement logic
});

klarna.Identity.on("signin", (data) => {
   // implement logic

An example of how to implement the event listeners to handle these events appropriately.

Upon a successful sign-in, you'll receive customer information and the refresh_token in the signin event handler. 

HTML
{
  "user_account_profile": {
    "sub": "<klarna-user-id>",
    "given_name": "",
    "family_name": "",
    "email": "",
    "phone": ""
  },
  "user_account_linking": {
    "user_account_linking_refresh_token": "",

An example of a payload from the signin event.

Before using data from the id_token, it needs to be validated. More about it under Token Validation.

Upon completing the sign-in process, utilize a specific claim (such as phone, email, or national identification number for Sweden) as a unique customer identifier. 

Make sure you are handling the following scenarios to ensure seamless integration:

  • New Users: If the identifier does not match any existing user in your database, check if the consumer consented to share all the data you requested. If additional information is required, remember to show your onboarding UI after Sign in with Klarna flow. Once onboarding is complete, create a new user account using the data returned from Klarna and store the user_account_linking_refresh_token within that record.
  • Existing Klarna Users: In cases where the identifier is already linked to a Klarna account, Sign in with Klarna always returns fresh customer data. Update your user record with this data to ensure that the information in your database remains current.
  • Existing Users: For users already in your database but not connected to Klarna, consider these approaches:
Account MergingUser Confirmation for Merging
Merge the account automatically, add customer data from Klarna that was missing in the existing record and save the user_account_linking_refresh_token in itPrompt the user to confirm if they wish to merge their existing account. If yes, follow Account Merging above. If not, ask them to login with a different Klarna account

By carefully managing these scenarios, you can provide a fluid and integrated user experience, leveraging the comprehensive data and functionality offered through the Sign in with Klarna.

For those who have already integrated Klarna Payments or Klarna Checkout, Sign in with Klarna enhances user experience by enabling automatic login within these products. To achieve this, simply pass the access_token, obtained from a token refresh call (see Refresh Token), to your existing integrations. You can find examples below depending if you have Klarna Payment or Klarna Checkout. 

access_token has a limited lifespan of only 5 minutes. Therefore, it's essential to renew the token right before initiating the checkout process. To receive a new set of token, perform a token exchange through a POST request to the token endpoint. Remember to always save the new refreshed token in the database, since the old one will be invalid.

For Klarna Payments 

Include the access_token in the POST create a payment session request to the Klarna payments API. Add the key to the customer object as klarna_access_token key as shown in the example below.

JAVASCRIPT
fetch("https://api.klarna.com/payments/v1/sessions", {
	method: "POST",
	headers: {
		"Content-Type": "application/json"
	},
	body: {
	  ...
  	  "customer": {
    	    ...
    	    "klarna_access_token": "access_token",

For Klarna Checkout 

Include the access_token in the POST create order request to the Klarna checkout API. Add the key to the customer object as klarna_access_token key as shown in the example below.

JAVASCRIPT
fetch("https://api.klarna.com/checkout/v3/orders", {
	method: "POST",
	headers: {
		"Content-Type": "application/json"
	},
	body: {
	  ...
  	  "customer": {
    	    ...
    	    "klarna_access_token": "access_token",