@companieshouse/node-session-handler

中文文档
5.2.23发布于 2026/11/02MITTypeScriptCommonJS近 30 天下载 2432

Node.js session handler for Companies House

原始使用文档
文档目录9 节
  1. Compatible Node.js Versions
  2. Prerequisite
  3. How to use it
  4. Session
  5. SessionStore
  6. SessionMiddleware
  7. EnsureSessionCookiePresentMiddleware
  8. Development
  9. Linting and testing

node-session-handler

Module provides a way of handling Companies House sessions.

Module offers the following artifacts:

  • Session that reflects structure of the session including elements of Single Sign-On
  • SessionStore that is responsible for reading and writing session data from / to database taking care of data encoding / decoding
  • SessionMiddleware that provides easy to use express.js middleware reading session based on the request cookie

Compatible Node.js Versions

This package has been upgraded to be compatible with Node v24. Presently, it's backward compatible with v20 and v18 but compatibility is primarily required for v24 as all CH Node services are in the process of being upgraded to v24.

Prerequisite

Module requires request.cookies map to be populated with an object keyed by the cookie names. It can be achieved by use of cookie-parser module.

In short run npm install cookie-parser command to install dependency and add the following snipped to the application to apply cookie parsing middleware:

import * as cookieParser from 'cookie-parser'
...
app.use(cookieParser())

Note: Cookie parsing must happen before request is passed to session middleware.

How to use it

To bring this module as dependency please add the following fragment to package.json:

"@companieshouse/node-session-handler": "~4.1.0"

Session

The session class is a wrapper around the raw session data: ISession (as retrieved from accounts after signing in).

To keep the ISession type consistent, we added an extra field called extra_data (SessionKey.ExtraData) to store any data that apps might need in the session making session itself extensible.

The class provides these methods:

  • get<T = ISessionValue>(key: SessionKey): T | undefined - allows retrieving session data for keys defined in the SessionKey enum that represents all possible types than can be retrieved from the session
  • getExtraData<T>(key: string): T | undefined - allows retrieving session data populated by the applications
  • setExtraData<T>(key: string, val: T): void - allows amending session data used by the applications by replacing existing value (if present)
  • deleteExtraData(key: string): boolean - deletes a key from the session data populated by an application (if exists)
  • verify = (): void - ensures that the session is valid i.e. contains the right fields, and it's not expired

SessionStore

Session store offers a way to load SessionStore.load, store SessionStore.store and delete SessionStore.delete session from database without worrying about data encoding or decoding.

All above methods take instance of Cookie class which holds combination of session ID and signature. Use of that argument type helps to ensure that database operations are only performed for verified session identifiers.

SessionMiddleware

Session middleware provides convenient integration point for express.js applications. Middleware does:

  1. read cookie value from request HTTP headers
  2. verify cookie signature if cookie is present
  3. load session from store using verified cookie if present
  4. sets verified session in request scope
  5. stores session in store on request end if session data changed

Express.js applications wishing to introduce session handling should register middleware in the following way:


const sessionStore = new SessionStore(new Redis(`redis://${process.env.CACHE_SERVER}`))
const middleware = SessionMiddleware({
    cookieName: process.env.COOKIE_NAME,
    cookieDomain: process.env.COOKIE_DOMAIN,
    cookieSecureFlag: process.env.COOKIE_SECURE_ONLY,
    cookieTimeToLiveInSeconds: process.env.DEFAULT_SESSION_EXPIRATION,
    cookieSecret: process.env.COOKIE_SECRET
}, sessionStore)

app.use(middleware)

Such application will then have access to session instance via request.session as long as __SID cookie is set to correct value.

There is also an option to have not authenticated sessions without sign-in info. In such cases middleware creates empty session as long as no valid session was found in the request.

To enable support for non authenticated sessions pass true as a last argument to the middleware factory function e.g. SessionMiddleware(config, sessionStore, true).

EnsureSessionCookiePresentMiddleware

Convenient Express middleware function which ensures requests contain the Session ID Cookie and forces a redirect if not. This is necessary if subsequent middlewares require the Cookie to be present in the request.

Should be used alongside the SessionMiddleware and be placed following it in the chain of middleware functions.

Should be used in the following way:

// Create CookieConfig as required
const cookieConfig = { ... };

// Create sessionMiddleware using same cookie config, refer to previous section
// for explicit instructions
const sessionMiddleware = ...;
const ensureSessionCookiePresentMiddleware =
    EnsureSessionCookiePresentMiddleware({
        // Ensure use the same cookie name as session, spreading cookie config
        // will accomplish this
        ...cookieConfig,
        // Supply values for redirectHeaderName and redirectHeaderValue
        // to customise the header which is used to validate the redirected
        // request. (Defaults to name: `x-redirection-count` value: `1`)
        redirectHeaderName: "not-redirect",
        redirectHeaderValue: "not-true",
    })

app.use(sessionMiddleware)
app.use(ensureSessionCookiePresentMiddleware)

Development

Module requires dependencies that can be installed via npm install command.

Linting and testing

Code is linted using ts-lint which can be run via npm run lint command.

Tests in turn can be run via npm test command.

版本与发布记录

@companieshouse/node-session-handler 共发布 42 个版本,首次发布于 2020/09/26;过去 12 个月发布了 16 个版本。

版本发布日期距今
5.2.23latest2026/11/028 天前
5.2.222026/10/1229 天前
5.2.212026/10/081 个月前
5.2.202026/09/181 个月前
5.2.192026/09/181 个月前
5.2.182026/08/172 个月前

关于 @companieshouse/node-session-handler 的常见问题

@companieshouse/node-session-handler 是什么?

Node.js session handler for Companies House

如何安装 @companieshouse/node-session-handler?

在项目目录运行 npm install @companieshouse/node-session-handler,或使用 pnpm add / yarn add / bun add。

@companieshouse/node-session-handler 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@companieshouse/node-session-handler 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@companieshouse/node-session-handler 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@companieshouse/node-session-handler 可以商用吗?

@companieshouse/node-session-handler 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@companieshouse/node-session-handler 的下载量有多少?

根据 npm 官方下载统计,@companieshouse/node-session-handler 在 2026/10/11 – 2026/11/09 这 30 天内被下载 2,432 次,日均约 81 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@companieshouse/node-session-handler 还在维护吗?

最新版本 5.2.23 发布于 2026/11/02(8 天前);至今共发布 42 个版本,其中过去 12 个月发布了 16 个;首次发布于 2020/09/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。