# jwtbutler

> [![build status](https://github.com/vielhuber/jwtbutler/actions/workflows/ci.yml/badge.svg)](https://github.com/vielhuber/jwtbutler/actions) [![GitHub Tag](https://img.shields.io/github/v/tag/vielhuber/jwtbutler)](https://github.com/vielhuber/jwtbutler/ta

Latest version **2.2.5** (published 2026-11-17) · MIT license · 0 weekly downloads

## Install

```sh
npm install jwtbutler
pnpm add jwtbutler
yarn add jwtbutler
bun add jwtbutler
```

## Health

**Score 60/100 (C)** — status: active.

Positive: no vulnerabilities; has provenance; recently updated; high maintenance score.

Warnings: low downloads; no types; no esm support.

## Facts

| | |
|---|---|
| Version | 2.2.5 |
| Published | 2026-11-17 |
| First published | 2018-07-16 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Node | >=18 |
| Dependencies | 0 |
| Unpacked size | 48.2 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 2 |
| Author | David |
| Maintainers | vielhuber |

## Links

- npm: https://www.npmjs.com/package/jwtbutler
- Repository: https://github.com/vielhuber/jwtbutler
- Homepage: https://github.com/vielhuber/jwtbutler#readme
- Issues: https://github.com/vielhuber/jwtbutler/issues
- npm.io page: https://npm.io/package/jwtbutler

## Recent versions

- 2.2.5 (latest) — 2026-11-17
- 2.2.4 — 2026-11-17
- 2.2.3 — 2026-11-17
- 2.2.2 — 2026-10-25
- 2.2.1 — 2026-10-16
- 2.2.0 — 2026-10-13
- 2.1.9 — 2026-09-23
- 2.1.8 — 2026-09-05
- 2.1.7 — 2026-08-28
- 2.1.6 — 2026-08-19
- 2.1.5 — 2026-08-18
- 2.1.3 — 2026-08-03
- 2.1.2 — 2026-07-28
- 2.1.1 — 2026-07-25
- 2.1.0 — 2026-07-21
- … 72 more at https://npm.io/package/jwtbutler/versions

## README

[![build status](https://github.com/vielhuber/jwtbutler/actions/workflows/ci.yml/badge.svg)](https://github.com/vielhuber/jwtbutler/actions)
[![GitHub Tag](https://img.shields.io/github/v/tag/vielhuber/jwtbutler)](https://github.com/vielhuber/jwtbutler/tags)
[![Code Style](https://img.shields.io/badge/code_style-psr--12-ff69b4.svg)](https://www.php-fig.org/psr/psr-12/)
[![License](https://img.shields.io/github/license/vielhuber/jwtbutler)](https://github.com/vielhuber/jwtbutler/blob/main/LICENSE.md)
[![Last Commit](https://img.shields.io/github/last-commit/vielhuber/jwtbutler)](https://github.com/vielhuber/jwtbutler/commits)
[![node version](https://img.shields.io/node/v/jwtbutler)](https://www.npmjs.com/package/jwtbutler)
[![npm Version](https://img.shields.io/npm/v/jwtbutler)](https://www.npmjs.com/package/jwtbutler)
[![npm Downloads](https://img.shields.io/npm/dt/jwtbutler)](https://www.npmjs.com/package/jwtbutler)

# 🗝️ jwtbutler 🗝️

jwtbutler is a helper library for setting up a single sign on with jwt in a multi domain environment in no time.

## features

- works in all js-applications
- renders a simple loginform if needed
- requires no code changes on the auth server
- has a fetch helper function for api calls that do all the heavy lifting (e.g. refreshing token, repeating calls) under the hood
- provides a fallback for clients that have third party cookies disabled
- includes a timeout for broken connections
- syncs cookies via iframes through postmessage
- works also without single sign on
- full chrome support (SameSite=None)

## requirements

- a fully setup jwt auth server (like [simpleauth](https://github.com/vielhuber/simpleauth)) with the following routes

| route         | method | arguments      | header                      | response                                                                                                                                                                |
| ------------- | ------ | -------------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| /auth/login   | POST   | email password | --                          | `([ 'success' => true, 'message' => 'auth successful', 'public_message' => '...', 'data' => [ 'access_token' => '...', 'expires_in' => 3600, 'user_id' => 42 ] ], 200)` |
| /auth/refresh | POST   | --             | Authorization: Bearer token | `([ 'success' => true, 'message' => 'auth successful', 'public_message' => '...', 'data' => [ 'access_token' => '...', 'expires_in' => 3600, 'user_id' => 42 ] ], 200)` |
| /auth/logout  | POST   | --             | Authorization: Bearer token | `([ 'success' => true, 'message' => 'logout successful', 'public_message' => '...' ], 200)`                                                                             |
| /auth/check   | POST   | access_token   | --                          | `([ 'success' => true, 'message' => 'valid token', 'public_message' => '...', 'data' => [ 'expires_in' => 3600, 'user_id' => 42, 'client_id' => 7000000 ] ], 200)`      |

- 401 response code on bad authentication

## installation

install the javascript module:

```bash
npm install jwtbutler
```

```js
import jwtbutler from 'jwtbutler';
```

you also can embed it in legacy applications like this:

```html
<script src="jwtbutler.js"></script>
```

now instantiate the object with the basic configuration:

```js
const api = new jwtbutler({
    auth_server: 'https://example-auth-server.vielhuber.dev/auth',
    auth_login: 'email',
    language: 'en'
});
```

`jwtbutler` can also render captchas (currently `hCaptcha` and `Cloudflare Turnstile`). note that `jwtbutler` only renders the widget and sends the resulting token to `/login` — your auth server must verify that token (e.g. [simpleauth](https://github.com/vielhuber/simpleauth) supports this out of the box):

```js
const api = new jwtbutler({
    /* ... */
    captcha: {
        provider: '...', // 'turnstile'|'hcaptcha'
        sitekey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
        theme: 'light'
    }
});
```

if your auth server uses passkeys and you want to show \
the passkey button in the default login form, enable it:

```js
const api = new jwtbutler({
    /* ... */
    passkeys: true
});
```

### single sign on

if you want to use sso, add all pages to the configuration object:

```js
sso: [
    'https://example-auth-page1.vielhuber.dev',
    'https://example-auth-page2.vielhuber.dev',
    'https://example-auth-page3.vielhuber.dev'
];
```

then deploy the helper file [sso.html](https://github.com/vielhuber/jwtbutler/blob/main/_dist/sso.html) in the root public directories of all pages that use single sign on. don't forget to fill out all origin page domains in line 7. Also make sure to add a valid Content-Security-Policy (for example with the help of a [.htaccess](https://github.com/vielhuber/jwtbutler/blob/main/_dist/.htaccess) file).

### custom login dom

if you need a custom login html dom instead of the default one, simply pass it as an arg:

```js
login_form: `
    <div class="login-form">
        <div class="login-form__inner">
            <form class="login-form__form">
                <ul class="login-form__items">
                    <li class="login-form__item">
                        <label class="login-form__label login-form__label--email" for="login-form__label--email">E-Mail-Adresse</label>
                        <input class="login-form__input login-form__input--email" id="login-form__label--email" type="text" required="required" autocomplete="email" name="email" />
                    </li>
                    <li class="login-form__item">
                        <label class="login-form__label login-form__label--password" for="login-form__label--password">Passwort</label>
                        <input class="login-form__input login-form__input--password" id="login-form__label--password" type="password" required="required" autocomplete="current-password" name="password" />
                    </li>
                    <li class="login-form__item">
                        <input class="login-form__submit" type="submit" value="Anmelden" />
                    </li>
                </ul>
            </form>
        </div>
    </div>
`;
```

if you want to define a special parent container (instead of the body tag), pass a selector:

```js
login_form_parent: '.container';
```

if you want to call a special callback function after the login form rendered, use this event:

```js
login_form_rendered: dom => {
    dom.querySelector('.login-form__input--email').value = 'foo';
    dom.querySelector('.login-form__input--password').value = 'bar';
    dom.querySelector('.login-form__submit').click();
};
```

## usage

```js
// this function
// ...checks if the user is logged in
// ...tries to generate a new token if possible
// ...if nothing works, renders a login form inside document.body
// ...on submit logs the user in on all pages
api.login().then(() => {
    alert('logged in everywhere!');
});

// check if logged in
if (api.isLoggedIn()) {
}

// get jwt data
api.getPayload();
api.getUserId();

// make ajax calls via fetch
// access tokens are automatically refreshed if needed and the request then is called again
// if the user is not logged in and a new token cannot be generated,
// a login form is rendered and after a succesful login, the request is again repeated
// fetch has the same interface as the official javascript Fetch API
api.fetch('https://example-auth-page1.vielhuber.dev/protected/');
api.fetch('https://example-auth-page2.vielhuber.dev/protected/', {
    method: 'POST',
    body: JSON.stringify({ foo: 'bar' }),
    cache: 'no-cache',
    headers: { 'content-type': 'application/json' }
})
    .then(res => res.json())
    .catch(err => err)
    .then(response => {
        console.log(response);
    });

// this function logs out on all pages
api.logout().then(() => {
    alert('logged out everywhere!');
});

// manage passkeys
api.passkeyRegister();
api.passkeyDelete(42);
```

## styling

use the following classes to style idle states:

- `html.jwtbutler-logging-in`
- `html.jwtbutler-logging-out`
- `html.jwtbutler-loading` (for logging in and out)
- `html.jwtbutler-fetching`
- `html.jwtbutler-login-form-visible`

to style the login form, use the class of the main container:

- `.login-form`

some basic styling of the login form can look like this:

```css
html.jwtbutler-login-form-visible .login-form {
    position: fixed;
    top: 10%;
    left: 10%;
    bottom: 10%;
    right: 10%;
    background-color: #c0ffee;
    border: 7px solid #f00;
    z-index: 2147483638;
}
```

## backend validation

you can easily check inside a backend on another page via php, if the provided access token is valid without even contacting the auth server.

#### installation

```bash
composer require firebase/php-jwt
```

#### index.php

```php
require_once __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

// cors
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if (@$_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    die();
}

try {
    // access token is delivered via authorization header or cookie
    $token = null;
    if ($_SERVER['HTTP_AUTHORIZATION'] ?? '') {
        $token = str_replace('Bearer ', '', $_SERVER['HTTP_AUTHORIZATION']);
    } elseif ($_COOKIE['access_token'] ?? '') {
        $token = str_replace('Bearer ', '', $_COOKIE['access_token']);
    }
    $user_id = JWT::decode(
        $token,
        new Key('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'HS256'), // secret key
    )->sub;
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'data' => [
            'id' => $user_id,
            'foo' => 'bar'
        ]
    ]);
    die();
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'unauthorized',
        'public_message' => '...'
    ]);
    die();
}
```

#### .htaccess

```.htaccess
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
```

## testing

setup the following vhosts:

- https://example-auth-server.vielhuber.dev/auth => jwt auth server (like [simpleauth](https://github.com/vielhuber/simpleauth))
- https://example-auth-page1.vielhuber.dev => \_tests/page1
- https://example-auth-page2.vielhuber.dev => \_tests/page2
- https://example-auth-page3.vielhuber.dev => \_tests/page3

and then run the test:

```bash
npm run js:tests
```

## pseudo code

- if pageX wants to check if user is logged in on client side (without a backend call)
    - pageX frontend checks if access_token is present in cookie and can be decoded (the token is not validated and it also can be expired)
        - if no, the user is considered to be logged out
        - if yes, the user is considered to be logged in
- if a logged in user makes an backend/api call on pageX
    - pageX frontend checks if access_token is present in cookie and can be decoded (the token is not validated and it also can be expired)
        - if no, the user is considered to be not logged in
            - see login procedure
            - the call is repeated automatically after a succesful login
        - if yes, the user is considered to be logged in
            - the user sets the access_token in the header ("Bearer")
            - pageX backend validates the access token with the secret key
                - if the validation is ok
                    - the backend extracts the user id from the token and uses that to provide data
                    - the final response is served to the client
                - if the validation is not ok
                    - an error is served to the client
                    - the client tries to generate a new token from the old one
                        - if that was successful
                            - pageX sets cookie for oneself
                            - if user has enabled third party cookies
                                - pageX server sets new access token in cookie via iframes for all other pages
                            - the call will be repeated automatically
                        - if that was not successful
                            - see login procedure
                            - the call is repeated automatically after a succesful login
- login procedure
    - pageX frontend verifies the access_token via secret_key via the /check route
        - if available and not expired
            - pageX sets cookie for oneself
            - if user has enabled third party cookies
                - pageX server sets new access token in cookie via iframes for all other pages
        - if available and expired
            - pageX frontend tries to generate a new token from old token via the /refresh route
                - if it worked
                    - pageX sets cookie for oneself
                    - if user has enabled third party cookies
                        - pageX server sets new access token in cookie via iframes for all other pages
                - if it didn't work
                    - render login form
        - if not available
            - render login form
- if the user submits the rendered login form on pageX
    - pageX gets back access token from auth server
    - pageX sets cookie for oneself
    - if user has enabled third party cookies
        - pageX sets cookie via iframes for all other pages
- if the user calls the logout function on pageX
    - pageX calls auth server to logout (this invalidates the token on the server side)
    - pageX removes cookie for oneself
    - if user has enabled third party cookies
        - pageX removes cookie via iframes for all other pages

---
_Source: https://npm.io/package/jwtbutler · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
