# token2session

> little middleware to check jwt validity and add decode to any request object (set session by default)

Latest version **4.0.0** (published 2024-09-06) · ISC license · 0 weekly downloads

## Install

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

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 4.0.0 |
| Published | 2024-09-06 |
| First published | 2022-12-13 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 4 |
| Unpacked size | 18.2 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Julien A.U BARDIN |
| Maintainers | slade850 |
| Keywords | jwt, session, auth, decode |

## Links

- npm: https://www.npmjs.com/package/token2session
- npm.io page: https://npm.io/package/token2session

## Dependencies (4)

- [jwk-to-pem](https://npm.io/package/jwk-to-pem.md) ^2.0.5
- [superagent](https://npm.io/package/superagent.md) ^10.1.0
- [jsonwebtoken](https://npm.io/package/jsonwebtoken.md) ^9.0.2
- [cookie-parser](https://npm.io/package/cookie-parser.md) ^1.4.6

## Alternatives

- [@pothos/plugin-authz](https://npm.io/package/@pothos/plugin-authz.md) — 12.4K weekly downloads
- [@bounded-sh/client](https://npm.io/package/@bounded-sh/client.md) — 3.2K weekly downloads
- [@luigi-project/plugin-auth-oauth2](https://npm.io/package/@luigi-project/plugin-auth-oauth2.md) — 2.3K weekly downloads
- [@nocobase/plugin-verification](https://npm.io/package/@nocobase/plugin-verification.md) — 2.0K weekly downloads
- [escher-request](https://npm.io/package/escher-request.md) — 545 weekly downloads

## Recent versions

- 4.0.0 (latest) — 2024-09-06
- 3.0.1 — 2023-06-01
- 3.0.0 — 2023-06-01
- 2.2.2 — 2023-04-13
- 2.2.1 — 2023-04-13
- 2.2.0 — 2023-04-13
- 2.1.4 — 2022-12-20
- 2.1.3 — 2022-12-20
- 2.1.2 — 2022-12-20
- 2.1.1 — 2022-12-20
- 2.1.0 — 2022-12-20
- 2.0.17 — 2022-12-15
- 2.0.16 — 2022-12-15
- 2.0.15 — 2022-12-15
- 2.0.14 — 2022-12-15
- … 15 more at https://npm.io/package/token2session/versions

## README

# Token to Session (token2session)

This is an Express middleware that adds a session provided by a JSON Web Token (JWT) to the request object. It can also be used as a security overlay by rejecting invalid tokens.

Installation

<pre><code>npm i token2session</code></pre>

Usage in ESM and Typescript:

<pre><code>
import express from "express";
import tokenToSession from "token2session";

const app = express();
 ...
app.use(
  tokenToSession({
    secret: "your_jwt_secret",
    routeToOmit: ['/home', '/login', '/opened-route*'],
  })
);

</code></pre>

Usage in commonJs:

<pre><code>
const express = require("express");
const tokenToSession = require("token2session").default;

const app = express();
 ...
app.use(
  tokenToSession({
    secret: "your_jwt_secret",
    routeToOmit: ['/home', '/login', '/opened-route*'],
  })
);

</code></pre>

</code></pre>

Usage with jwksEndpoint and customKeySetHandler:

<pre><code>
 ...
app.use(
  tokenToSession({
    jwksEndpoint: "https://your-jwks-endpoint-url",
    customKeySetHandler: (kid, keySet) => {
      /* eg with custom keySet: keySet = { kid1: "public_key..", kid2: "public_key.."  } */
      return keySet?.[kid];
    },
    routeToOmit: ['/home', '/login', '/opened-route*'],
  })
);

</code></pre>

</code></pre>

Usage with customKeySetHandler asynchronus:

<pre><code>
 ...
app.use(
  tokenToSession({
    customKeySetHandler: async (kid) => {
      ...do something async
      return result (public_key or secret);
    },
    routeToOmit: ['/home', '/login', '/opened-route*'],
  })
);

</code></pre>

## Options

#### \* = look at the Notes

| Option                            | Type                | Default         | Description                                                                                                                                                                                                                        |
| --------------------------------- | ------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| secret \* (optional)              | string              |                 | Secret used to sign the JWT.                                                                                                                                                                                                       |
| jwksEndpoint \* (optional)        | string              |                 | JWKS endpoint url to fetch public keys from (simple get).                                                                                                                                                                          |
| customKeySetHandler \* (optional) | function            |                 | Custom handler to return the public key, which can be synchronous or asynchronous. If you're using jwksEnpoint, this function receives 2 parameters 'kid of token' and 'the return of enpoint', otherwise it will only take 'kid'. |
| jwtOptions (optional)             | object              |                 | Options to pass to the jwt.verify function.                                                                                                                                                                                        |
| headerKey \* (optional)           | undifined or string | "authorization" | Header key used to pass the token.                                                                                                                                                                                                 |
| cookieKey \* (optional)           | string              |                 | Cookie name used to pass the token.                                                                                                                                                                                                |
| cookieSecret (optional)           | string              |                 | Cookie secret used to sign the cookie.                                                                                                                                                                                             |
| session (optional)                | string              | "session"       | Session name used to store in the req object.                                                                                                                                                                                      |
| sessionInTokenKey (optional)      | string              |                 | Key if the session is in a sub-object of the decoded token.                                                                                                                                                                        |
| useBearer (optional)              | boolean             | true            | Set to false if you aren't using a bearer token.                                                                                                                                                                                   |
| rejectOnError (optional)          | boolean             | true            | reject all requests if the token is not valid. Set to false if you want to pass even in case of error.                                                                                                                             |
| rejectMessage (optional)          | string              | "Unauthorized"  | Sentence to return on reject.                                                                                                                                                                                                      |
| routeToOmit \* (optional)         | array               | []              | Array of routes that should not be rejected.                                                                                                                                                                                       |

---

## Notes

- The `secret` option is required if you're not using a `jwksEndpoint` or `customKeySetHandler` function.
- If you use `jwksEndpoint` or `customKeySetHandler` function or both, the `secret` is useless.
- If no `headerKey` or `cookieKey` is provided and `useBearer` aren't set to false, the middleware will use the authorization header and assume a bearer token.
- If no `headerKey` or `cookieKey` is provided and `useBearer` is set to false, an error will be thrown.
- The `routeToOmit` option accepts an array of routes that should not be rejected. A route pattern can include a \* wildcard to match multiple routes.

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