# @sempervirens/authorizer

> Middleware for authorizing requests to an Express server

Latest version **1.0.0** (published 2026-07-06) · MIT license · 0 weekly downloads

## Install

```sh
npm install @sempervirens/authorizer
pnpm add @sempervirens/authorizer
yarn add @sempervirens/authorizer
bun add @sempervirens/authorizer
```

## Health

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

Positive: esm support; no vulnerabilities.

Warnings: low downloads; no types.

## Facts

| | |
|---|---|
| Version | 1.0.0 |
| Published | 2026-07-06 |
| First published | 2022-06-22 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | ESM + CommonJS |
| Dependencies | 1 |
| Unpacked size | 32.2 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Luke Dupuis |
| Maintainers | sempervirens |
| Keywords | Express, authorization, middleware |

## Links

- npm: https://www.npmjs.com/package/@sempervirens/authorizer
- Repository: https://github.com/lukedupuis/sempervirens-authorizer
- Homepage: https://github.com/lukedupuis/sempervirens-authorizer#readme
- Issues: https://github.com/lukedupuis/sempervirens-authorizer/issues
- npm.io page: https://npm.io/package/@sempervirens/authorizer

## Dependencies (1)

- [jsonwebtoken](https://npm.io/package/jsonwebtoken.md) ^9.0.3

## Alternatives

- [@sindresorhus/slugify](https://npm.io/package/@sindresorhus/slugify.md) — 3.7M weekly downloads
- [solid-js](https://npm.io/package/solid-js.md) — 2.7M weekly downloads
- [expo-glass-effect](https://npm.io/package/expo-glass-effect.md) — 2.5M weekly downloads
- [nanoassert](https://npm.io/package/nanoassert.md) — 780.8K weekly downloads
- [@ffmpeg/ffmpeg](https://npm.io/package/@ffmpeg/ffmpeg.md) — 529.5K weekly downloads

## Recent versions

- 1.0.0 (latest) — 2026-07-06
- 0.6.0 — 2022-08-16
- 0.5.0 — 2022-07-18
- 0.4.0 — 2022-07-18
- 0.3.0 — 2022-07-18
- 0.2.1 — 2022-07-17
- 0.2.0 — 2022-07-14
- 0.1.0 — 2022-07-09
- 0.0.3 — 2022-07-01
- 0.0.1 — 2022-06-22

## README

# Sempervirens Authorizer
Middleware for authorizing requests to an Express server.

![Tests badge](https://github.com/lukedupuis/sempervirens-authorizer/actions/workflows/main.yml/badge.svg?event=push) ![Version badge](https://img.shields.io/static/v1?label=Node&labelColor=30363c&message=16.x&color=blue)

## Installation

`npm i @sempervirens/authorizer`

## Usage

### Overview

1. Create JWT private and public keys.

```
mkdir security && cd security && mkdir jwt && cd jwt
ssh-keygen -t rsa -b 4096 -m PEM -f jwtRS256.key
openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub
```

2. Import `authorizer` into the server's main file, and then initialize `authorizer` with the JWT public and private keys.

3. Set up a route that uses `authorizer.encrypt` to create a token and return the token to the client.

4. Set up another route with a protected resource that requires a valid token.

5. From the client, send a request to the server to get the token.

6. From the client, send a second request for the protected resource, including the `'Authorization': 'Bearer ${token}'` header.

### Example

```
import { readFileSync } from 'fs';
import express from 'express';
import authorizer from '@sempervirens/authorizer';

const jwtPublicKey = readFileSync('./security/jwt/jwtRS256.key.pub', 'utf8');
const jwtPrivateKey = readFileSync('./security/jwt/jwtRS256.key', 'utf8');

authorizer.init({ jwtPublicKey, jwtPrivateKey });

const app = express();
app.use(express.json());

// Set up a /login route
app.post('/login', async (req, res, next) => {
  const { email, password } = req.body;
  // Validate email/password combination; do not use the following except for testing
  const isValid = email == 'test@test.com' && password == 'testpassword';
  if (isValid) {
    const token = authorizer.encrypt({
      expiresIn: '10m',
      data: { email }
    });
    res.json({ token });
  } else {
    res.json({ error: 'Invalid credentials' });
  }
});

// Set up a protected resource route
app.get('/profile/:id', async (req, res, next) => {
  if (authorizer.isAuthorized(req)) { // Pass request header 'Authorization': 'Bearer ${token}'
    const profile = {
      email: 'test@test.com',
      name: 'FirstTest LastTest'
    };
    res.json({ profile });
  } else {
    authorizer.sendUnauthorized(res); // Or send a custom response
  }
});

```

## API

### authorizer (Singleton instance)

| Prop  | Type | Params | Description |
|-------|------|--------|-------------|
| `init` | function | `{ jwtPublicKey = '', jwtPrivateKey = '' }` | Initializes the instance properties. |
| `encrypt` | function | `{ expiresIn = '', data: {} }` | Returns a JWT token. |
| `decrypt` | function | `tokenOrReq` | Decrypts a JWT token. The token itself or an Express request object containing the authorization header may be given. |
| `isValid` | function | `tokenOrReq` | Returns `true` or `false`. The token itself or an Express request object containing the authorization header may be given. |
| `invalidate` | function | `tokenOrReq` | Invalidates a token within `authorizer`. |
| `reset` | function | `tokenOrReq` | Decrypts the original token, calculates the original token's `expiresIn`, and adds the `origIat` property to the data before generating a new token. |
| `isAuthorized` | function | `req: express.Request` | Parses a token from the `'Authorization': 'Bearer ${token}'`, checks if it's valid, and returns `true` or `false`. |
| `authorize` | function | `req: express.Request, res: express.Request, next` | Checks if the token is valid. If so, it calls next. If not, it calls `sendUnauthorized`.|
| `sendUnauthorized` | function | `res: express.Request` | Sends a 401 response with a pre-formatted data object in the same shape as `@sempervirens/endpoint`'s error response. |

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