# @universal-packages/express-session

> Express session manager.

Latest version **1.9.0** (published 2024-12-09) · MIT license · 0 weekly downloads

## Install

```sh
npm install @universal-packages/express-session
pnpm add @universal-packages/express-session
yarn add @universal-packages/express-session
bun add @universal-packages/express-session
```

## Health

**Score 35/100 (D)** — status: maintenance-mode.

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

Warnings: low downloads; no esm support.

Negative: stale; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.9.0 |
| Published | 2024-12-09 |
| First published | 2023-01-02 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 25.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | David De Anda |
| Maintainers | omarandstuff |

## Links

- npm: https://www.npmjs.com/package/@universal-packages/express-session
- Repository: https://github.com/universal-packages/universal-express-session
- Homepage: https://github.com/universal-packages/universal-express-session#readme
- Issues: https://github.com/universal-packages/universal-express-session/issues
- npm.io page: https://npm.io/package/@universal-packages/express-session

## Dependencies (1)

- [@universal-packages/token-registry](https://npm.io/package/@universal-packages/token-registry.md) ^1.8.1

## Recent versions

- 1.9.0 (latest) — 2024-12-09
- 1.8.2 — 2024-11-30
- 1.8.1 — 2024-11-30
- 1.8.0 — 2024-11-30
- 1.7.1 — 2024-11-27
- 1.7.0 — 2024-11-18
- 1.6.12 — 2024-08-25
- 1.6.11 — 2024-08-25
- 1.6.10 — 2024-08-25
- 1.6.9 — 2024-03-23
- 1.6.8 — 2024-03-23
- 1.6.7 — 2024-03-22
- 1.6.6 — 2024-01-01
- 1.6.5 — 2024-01-01
- 1.6.4 — 2023-10-31
- … 13 more at https://npm.io/package/@universal-packages/express-session/versions

## README

# Express Session

[![npm version](https://badge.fury.io/js/@universal-packages%2Fexpress-session.svg)](https://www.npmjs.com/package/@universal-packages/express-session)
[![Testing](https://github.com/universal-packages/universal-express-session/actions/workflows/testing.yml/badge.svg)](https://github.com/universal-packages/universal-express-session/actions/workflows/testing.yml)
[![codecov](https://codecov.io/gh/universal-packages/universal-express-session/branch/main/graph/badge.svg?token=CXPJSN8IGL)](https://codecov.io/gh/universal-packages/universal-express-session)

Express session manager.

## Install

```shell
npm install @universal-packages/express-session

npm install express
```

## Middleware

#### **`session([options])`**

Initialize a Session object

```js
import { session } from '@universal-packages/express-session'
import { RedisEngine } from '@universal-packages/universal-token-registry-redis'
import express from 'express'

const engine = new RedisEngine({ host: 'localhost' })
await engine.connect()

const app = express()

app.use(session({ engine }))
```

#### Options

`Session` takes the same options as [Token Registry](https://github.com/universal-packages/universal-token-registry#options)

Additionally:

- **`cookieName`** `String` `default: "session"`
  Name of the cookie to fetch for the session token.

- **`registryId`** `String`
  String to use to add randomness to the token generation.

- **`trackSessionAccess`** `Boolean`
  Update registry every time a request is made to track ip and last access changes.

#### **`authenticateRequest`**

Use this for a simple request rejection if the session was not authenticated.If not authenticated the middleware ends the response with unauthorized status.

```js
import { authenticateRequest } from '@universal-packages/express-session'

app.get('/private', authenticateRequest, async (request, response) => {
  response.end()
})
```

### Create your own

Authenticating request is very simple you can even add your own logic like setting a current user to use later.

```js
export async function authenticateRequest(request, response, next) {
  if (request.session.authenticated) {
    request.currentUser = await User.find(request.session.userId)

    next()
  } else {
    response.status(401).end()
  }
}
```

### Request authentication

You can either set the header `Authorization` in the format `bearer <token>` or configure express to parse cookies and set a `session` cookie with the token value, more about how to get a token below.

## Session

When the middleware is in use a `Session` object will be available in the request object.

```js
app.get('/', async (request, response) => {
  const currentUser = await User.find(request.session.userID)

  response.end()
})
```

### Properties

#### authenticated `Boolean`

True whe a request was authenticated with a token.

#### id `String`

A unique id for the session aside from the token.

#### userId `String`

The same id used to create the session at log in.

#### token `String`

The token that came with the request.

#### firstAccessed `Date`

Date in which the session was created at log in.

#### lastAccessed `Date`

Date of the current moment using the session token.

#### firstIp `String`

Request ip when the session was created at log in.

#### lastIp `String`

Request ip of the current moment using the session token.

#### userAgent `String`

User agent in which the session was created at log in.

### Instance methods

#### **`logIn(userID: String)`** `Async`

Creates a new session using the user id and sets the cookie `session` as well as the `Authorization` response header to return to the user when ending the response.

#### **`logOut(token? string)`** `Async`

Disposes the current session from the registry so the token is no longer valid, or if a token is provided it will dispose that session instead.

#### **`activeSessions()`** `Async`

Returns all the active sessions for the current session user.

### Static methods

#### **`activeSessions(userId: String, [options: Object])`** `Async`

Returns all the active sessions for the user id.

- **`userId`** `String`
  The id of the user to get the active sessions from.
- **`options`** `Object`
  Same options as [Token Registry](https://github.com/universal-packages/universal-token-registry#options)

## Global methods

#### **`injectSession(request: Request, response: Response, options?: ExpressSessionOptions)`**

To only inject the session object into the request and don't behave as middle ware use this method. In case you are doing some custom middleware.

```js
import { injectSession } from '@universal-packages/express-session'
import express from 'express'

const app = express()

app.use(async (request, response, next) => {
  await injectSession(request, response, options)

  next()
})
```

## Typescript

In order for typescript to see the global types you need to reference the types somewhere in your project, normally `./src/globals.d.ts`.

```ts
/// <reference types="@universal-packages/express-session" />
```

This library is developed in TypeScript and shipped fully typed.

## Contributing

The development of this library happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving this library.

- [Code of Conduct](./CODE_OF_CONDUCT.md)
- [Contributing Guide](./CONTRIBUTING.md)

### License

[MIT licensed](./LICENSE).

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