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 🙏

© 2025 – Pkg Stats / Ryan Hefner

swedbank-json

v1.0.1

Published

Node.js Swedbank API client (unofficial) based on walle89/swedbank-json

Readme

swedbank-json

npm version npm downloads TypeScript MIT License

A modern TypeScript port of walle89/SwedbankJson that interacts with Swedbank's mobile APIs. It supports Mobile BankID QR login, session caching, cookie management, account overview, transaction previews, and complete transaction history with pagination.

This project is not affiliated with Swedbank or Sparbanken. Use for personal/educational purposes only.

Table of Contents

Features

  • Mobile BankID QR and same-device login
  • Session caching & cookie persistence (persist the returned session to skip QR on the next run)
  • Built-in Mobile app headers (User-Agent, X-Client, Authorization) with AppData cache
  • Accounts overview, reminders, savings portfolios
  • Transaction preview (accountTransactions) and full history pagination (getFullTransactionHistory)
  • Transfers, quick balance subscriptions, and transaction detail lookups
  • Written in modern TypeScript with rich TSDoc for IDEs

Installation

npm install swedbank-json

TypeScript/ESM import:

import { loginWithBankID, SwedbankClient } from "swedbank-json";

CommonJS require:

const { loginWithBankID, SwedbankClient } = require("swedbank-json");

Authentication: Mobile BankID QR Login

import { loginWithBankID, SwedbankClient } from "swedbank-json";

async function main() {
  const { auth, session } = await loginWithBankID({
    personnummer: "YYYYMMDDXXXX", // optional for QR, required for same-device
    bankApp: "sparbanken",
    cachePath: "./cache/session.json", // where you persist the session/AppData cache
    sameDevice: false, // set true to deep-link to the BankID app instead of QR
  });

  // Render QR by polling in your own loop (pseudo):
  const status = await auth.pollStatus();
  console.log(status.imageChallengeData); // base64 for animated QR frames

  await auth.verify(); // waits for COMPLETE

  const client = new SwedbankClient(auth);
  const accounts = await client.accountList();
  console.log(accounts.transactionAccounts.map((a: any) => a.name));
}

Valid bankApp values: swedbank, sparbanken, savingsbank, swedbank_foretag, sparbanken_foretag.

Session caching behavior

  • loginWithBankID returns { auth, session }. Persist session to disk (e.g., fs.writeFileSync("./cache/session.json", JSON.stringify(session))).
  • On the next run, load the JSON and pass it to new SwedbankClient(loadedSession) to reuse cookies/user agent without scanning a new QR (until Swedbank expires the session).
  • App metadata (User-Agent/AppID) is also cached to the cachePath so repeat runs avoid remote lookups.

Cookie handling

  • All Set-Cookie headers are merged into the in-memory session and reused on subsequent requests.
  • When you persist session, those cookies are preserved and replayed when you reconstruct SwedbankClient with the saved session.

Fetch Accounts

const client = new SwedbankClient(auth);
const overview = await client.accountList();

// Transaction accounts
for (const account of overview.transactionAccounts) {
  console.log(`${account.name} (${account.id}) -> balance: ${account.balance.amount} ${account.balance.currency}`);
}

// Savings/investments
if (overview.savingsAccounts) {
  console.log(`You have ${overview.savingsAccounts.length} savings accounts`);
}

Account categories commonly present in engagement/overview:

  • transactionAccounts: Current/checking accounts
  • savingsAccounts: Savings & investment accounts
  • cardAccounts: Credit card accounts
  • loans: Loan products (mortgage, consumer loans)

Fetch Transactions

Basic preview (single page):

const accountId = overview.transactionAccounts[0].id;
const page = await client.accountTransactions(accountId, 40, 1);
console.log(page.transactions.length); // Up to ~40, depending on the API default

Full history with pagination (recommended):

const allTransactions = await client.getFullTransactionHistory(accountId);
console.log(`Fetched ${allTransactions.length} transactions`);

// Example: find the latest card charge
const latestCard = allTransactions.find((t) => t.type === "CARD");
console.log(latestCard);

getFullTransactionHistory follows Swedbank's links.next.uri pagination until moreTransactionsAvailable is false, so you get the complete list the API exposes.

Directory Structure

├─ src/              # TypeScript sources with rich TSDoc
│  ├─ auth/          # Mobile BankID, security token, and unauth flows
│  ├─ swedbank/      # SwedbankClient and high-level banking helpers
│  ├─ http/          # HTTP wrapper with headers/cookies
│  ├─ appdata/       # AppData cache (User-Agent/AppID)
│  └─ index.ts       # Public entrypoint (loginWithBankID, exports)
├─ dist/             # Compiled JavaScript + type declarations (npm publishes this)
├─ cache/            # (suggested) store session JSON and AppData cache here
├─ test/             # Vitest tests
├─ package.json
├─ tsconfig.json
└─ README.md

Environment Variables

.env example (with dotenv):

SWEDBANK_PERSONNUMMER=YYYYMMDDXXXX
SWEDBANK_BANKAPP=sparbanken
SWEDBANK_CACHE_PATH=./cache/session.json
SWEDBANK_SAME_DEVICE=false
SWEDBANK_DEBUG=1

Usage:

import "dotenv/config";
import { loginWithBankID } from "swedbank-json";

const { auth } = await loginWithBankID({
  personnummer: process.env.SWEDBANK_PERSONNUMMER,
  bankApp: process.env.SWEDBANK_BANKAPP || "swedbank",
  cachePath: process.env.SWEDBANK_CACHE_PATH || "./cache/session.json",
  sameDevice: process.env.SWEDBANK_SAME_DEVICE === "true",
});

Error Handling

Common errors thrown by the client:

  • Unable to use Mobile BankID. Check if the user has enabled Mobile BankID. – initiation failed
  • Mobile BankID verification timed out. User did not complete authentication in time. – QR not scanned within timeout
  • The user is not a customer in Swedbank... or ...Sparbanken – profile selection mismatches the chosen bankApp
  • Not a valid AccountID / Not a valid DetailsTransactionID – invalid identifiers passed to account/transaction endpoints
  • There are no registered transactions to confirm. – attempting to confirm transfers when none exist
  • PROFILE_SELECTION_NEEDED / MULTIPLE_PROFILES – some users must select a profile; use selectProfileIfNeeded or set profileID

Catch errors around your calls to provide better user messaging or retries.

Debug Logging

Set SWEDBANK_DEBUG=1 to log request URLs, headers, cookies, and short response excerpts. By default, the client is quiet aside from thrown errors.

SWEDBANK_DEBUG=1 node your-script.js

Full API Reference

loginWithBankID(options: LoginWithBankIDOptions)

Starts Mobile BankID authentication and returns { auth, session }. Persist session to disk to skip QR next time; use auth.pollStatus() for QR frames and auth.verify() to block until done.

Classes

SwedbankClient

  • constructor(authOrSession) – pass a MobileBankIDAuth instance or a persisted Session object
  • profileList() – list available profiles for the authenticated user
  • accountList(profileID?) – fetch engagement overview (transactionAccounts, savingsAccounts, cardAccounts, loans)
  • accountTransactions(accountID?, transactionsPerPage?, page?) – single-page transaction preview (legacy)
  • accountDetails(accountID?, transactionsPerPage?, page?) – alias of accountTransactions
  • getFullTransactionHistory(accountID?) – traverse pagination and return all transactions
  • transactionDetails(detailsTransactionID) – fetch additional info for a transaction
  • portfolioList(profileID?) – list savings/investment holdings
  • reminders() – fetch message reminders
  • transferBaseInfo() – base info for payments (limits, defaults)
  • transferRegisterPayment(amount, fromAccountId, recipientAccountId, fromAccountNote?, recipientAccountMessage?, transferDate?, periodicity?)
  • transferListRegistered() / transferListConfirmed() – list pending/confirmed payments
  • transferConfirmPayments() – confirm all registered transfers
  • transferDeletePayment(transferId) – delete a payment
  • quickBalanceAccounts(profileID?) – list accounts eligible for quick balance
  • quickBalanceSubscription(accountQuickBalanceSubID) / quickBalance(subscriptionId) / quickBalanceUnsubscription(subscriptionId, profileID?)
  • selectProfileIfNeeded(accountsResp) – helper to auto-select a profile when the API requests it
  • terminate() – end the authentication session

MobileBankIDAuth

  • initAuth() – start Mobile BankID (QR or same-device)
  • pollStatus() – non-blocking status + animated QR payload
  • verify() / verifyLoop() – block until authentication is complete
  • getAutoStartToken() – deep-link token for same-device flows
  • getImageChallengeData() – latest QR frame payload
  • setSameDevice(sameDevice) – toggle between QR and same-device modes
  • terminate() – logout

SecurityTokenAuth

Hardware token/OTP flow (legacy): getChallenge(), login(responseCode), isUseOneTimePassword().

UnAuth

Device registration without full login: login() registers the device; useful for unauthenticated endpoints.

Utilities

  • AppData / AppDataCache – fetch and cache mobile app metadata
  • HttpClient – Swedbank-aware fetch wrapper with cookie + header management
  • Types: Session, SwedbankTransaction, LoginWithBankIDOptions, MobileBankIDAuthOptions, SecurityTokenAuthOptions, UnAuthOptions

Contributing

PRs are welcome! Please:

  1. Run npm test to execute Vitest suites.
  2. Include updates to TSDoc/README when changing public APIs.
  3. Keep logs behind SWEDBANK_DEBUG to avoid noisy defaults.

License

MIT